21#include "mlir/IR/Attributes.h"
22#include "mlir/Interfaces/DataLayoutInterfaces.h"
23#include "mlir/Pass/Pass.h"
24#include "llvm/ADT/EquivalenceClasses.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/FormatVariadic.h"
34#define DEBUG_TYPE "aie-objectfifo-allocate"
41#define GEN_PASS_DEF_AIEOBJECTFIFOALLOCATE
42#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
47struct AIEObjectFifoAllocatePass
48 :
public xilinx::AIE::impl::AIEObjectFifoAllocateBase<
49 AIEObjectFifoAllocatePass> {
53 OpBuilder builder{
static_cast<MLIRContext *
>(
nullptr)};
55 DenseMap<Value, Operation *> lastPlaced;
57 std::shared_ptr<PoolLocks> poolLocks;
60 SmallVector<Operation *> loweredFlows;
63 DenseMap<StringAttr, SmallVector<RouteOp>> sourcedFlows;
64 llvm::MapVector<ObjectFifoDmaEndpointOp, llvm::StringMap<PacketInfoAttr>>
68 llvm::MapVector<Operation *, Operation *> channelSharers;
69 llvm::MapVector<Operation *, ShimDMAAllocationOp> allocationSharers;
70 DenseMap<Operation *, SmallVector<Value>> bufferPlacements;
71 DenseMap<Operation *, int> channelAssignments;
72 DenseMap<Operation *, Value> localPools;
73 DenseMap<Operation *, SmallVector<Value>> poolUsers;
74 DenseMap<Operation *, SmallVector<Operation *>> lockUsers;
75 DenseMap<Operation *, Value> lockPlacements;
79 DenseMap<Operation *, SmallVector<DMAStartOp>> endpointStarts;
80 DenseMap<Operation *, SmallVector<AIEX::DMAConfigureTaskForOp>> endpointTasks;
85 DMAChannelAnalysis::TakenBDs takenBDs;
87 using BDDemand = DenseMap<std::tuple<int, int, int, int>, int64_t>;
88 static std::tuple<int, int, int, int>
89 demandKey(
int col,
int row, DMAChannelDir dir,
int channel) {
90 return {col, row,
static_cast<int>(dir), channel};
97 BDDemand channelDemand;
100 DenseMap<Operation *, unsigned> structuralRank;
101 RouteEndpoint channelFailure;
104 bool bdShortfall =
false;
107 llvm::SetVector<Operation *> bdPlanned;
109 llvm::SetVector<Operation *> turnWalked;
112 DenseMap<StringAttr, bool> hostMovesFirstCache;
115 ObjectFifoPoolOp bufferFailure;
118 SmallVector<TileOp> spillTiles;
120 Operation *lockAccessFailure =
nullptr;
122 ObjectFifoPoolOp lockSearchStoppedOn;
124 bool semaphoreLocks =
false;
125 bool walkSearchStopped =
false;
126 bool lockSearchStopped =
false;
128 bool sameTile(Value a, Value b) {
131 auto first = cast<TileLike>(a.getDefiningOp());
132 auto second = cast<TileLike>(b.getDefiningOp());
133 auto ac = first.tryGetCol(), ar = first.tryGetRow();
134 auto bc = second.tryGetCol(), br = second.tryGetRow();
135 return ac && ar && bc && br && ac == bc && ar == br;
141 DenseMap<TileID, unsigned> memTilePositions;
142 DenseMap<Operation *, unsigned> unplacedMemTiles;
143 SmallVector<std::optional<TileID>> memTileAt;
145 std::optional<unsigned> memTileIndex(Value tile) {
146 auto like = cast<TileLike>(tile.getDefiningOp());
147 if (!like.isMemTile())
149 auto col = like.tryGetCol(), row = like.tryGetRow();
151 return memTilePositions.lookup({*col, *row});
152 return unplacedMemTiles.lookup(like);
156 MemTileSpillSearch memTileSearch() {
157 const auto &target = device.getTargetModel();
158 memTilePositions.clear();
159 unplacedMemTiles.clear();
161 SmallVector<MemTileSpillSearch::Tile> tiles;
162 auto add = [&](std::optional<TileID> at) {
163 memTileAt.push_back(at);
164 tiles.push_back({target.getMemTileSize(), {}});
165 return static_cast<unsigned>(tiles.size() - 1);
167 for (
auto tile : device.getOps<TileLike>()) {
168 if (!tile.isMemTile())
170 auto col = tile.tryGetCol(), row = tile.tryGetRow();
172 unplacedMemTiles[tile] = add(std::nullopt);
176 if (!memTilePositions.count(at))
177 memTilePositions[at] = add(at);
178 if (isa<TileOp>(tile.getOperation()))
180 if (!memTilePositions.count(neighbour))
181 memTilePositions[neighbour] = add(neighbour);
183 int64_t alignment = target.getMemTileLoadStoreBusWidth() / 8;
184 for (
auto buffer : device.getOps<BufferOp>())
185 if (std::optional<unsigned> index = memTileIndex(buffer.getTile()))
186 tiles[*index].fixed.push_back({buffer.getAllocationSize(),
187 buffer.getAligned() ? alignment : 1,
188 buffer.getAddress()});
189 return MemTileSpillSearch(std::move(tiles), alignment);
192 LogicalResult collectFixedMemory() {
193 MemTileSpillSearch search = memTileSearch();
194 for (
auto tile : device.getOps<TileLike>()) {
195 std::optional<unsigned> index = memTileIndex(tile->getResult(0));
198 int64_t bytes = search.
used(*index);
199 int64_t capacity = device.getTargetModel().getMemTileSize();
200 if (bytes > capacity)
201 return tile->emitOpError(
"existing buffers require ")
202 << bytes <<
" bytes, exceeding MemTile capacity of " << capacity
210 SmallVector<TileID> compatiblePositions(TileLike tile) {
211 const auto &target = device.getTargetModel();
212 SmallVector<TileID> compatible;
213 auto col = tile.tryGetCol(), row = tile.tryGetRow();
214 for (
int c = 0; c < target.columns(); ++c) {
215 if (col && c != *col)
217 for (
int r = 0; r < target.rows(); ++r) {
218 if ((!row || r == *row) &&
219 target.getTileType(c, r) == tile.getTileType())
220 compatible.push_back({c, r});
226 bool canAccess(Value user, Value memory,
bool localOnly =
false) {
229 auto memoryTile = dyn_cast<TileLike>(memory.getDefiningOp());
231 canAccess(user, compatiblePositions(memoryTile), localOnly);
236 bool canAccess(Value user, ArrayRef<TileID> memoryPositions,
237 bool localOnly =
false) {
238 auto userTile = dyn_cast<TileLike>(user.getDefiningOp());
240 compatiblePositions(userTile),
241 memoryPositions, localOnly);
244 Value lockPlacement(ObjectFifoPoolOp pool, Operation *group) {
245 if (Value placed = lockPlacements.lookup(group))
247 Value local = localPools.lookup(pool);
248 return local ? local : pool.getTile();
252 static int bufferCount(ObjectFifoPoolOp pool) {
253 return pool.getContiguous() ? 1 : pool.getDepth();
255 static int64_t bufferBytes(ObjectFifoPoolOp pool) {
256 return pool.getObjectSizeInBytes() * pool.getObjectsPerBuffer();
267 LogicalResult planBuffers(ArrayRef<ObjectFifoPoolOp> pools) {
268 bufferPlacements.clear();
269 bufferFailure =
nullptr;
270 MemTileSpillSearch search = memTileSearch();
271 auto reachable = [&](ObjectFifoPoolOp pool,
auto memory) {
272 return llvm::all_of(poolUsers[pool],
273 [&](Value user) {
return canAccess(user, memory); });
275 for (
auto pool : pools) {
276 if (!localPools.contains(pool))
278 Value tile = localPools.lookup(pool);
279 int count = pool.getBuffers() ? 0 : bufferCount(pool);
280 int64_t size = bufferBytes(pool);
281 std::optional<unsigned> index = memTileIndex(tile);
282 if (!canAccess(pool.getTile(), tile) || !reachable(pool, tile) ||
283 (index && !search.
fits(*index, size, count))) {
284 bufferFailure = pool;
288 search.
reserve(*index, size, count);
290 const auto &target = device.getTargetModel();
291 SmallVector<MemTileSpillSearch::Buffer> buffers;
292 SmallVector<ObjectFifoPoolOp> owners;
293 for (
auto pool : pools) {
294 if (pool.getBuffers()) {
295 for (
auto buffer : pool.getBufferOps()) {
296 Value tile = buffer.getBufferTile();
297 if (tile && ((localPools.contains(pool) &&
298 !sameTile(tile, localPools.lookup(pool))) ||
299 !reachable(pool, tile))) {
300 bufferFailure = pool;
303 bufferPlacements[pool].push_back(tile);
307 if (pool.getTileLike().isShimTile())
309 if (localPools.contains(pool)) {
310 bufferPlacements[pool].append(bufferCount(pool),
311 localPools.lookup(pool));
314 Value home = pool.getTile();
315 bool atHome = reachable(pool, home);
316 std::optional<unsigned> index = memTileIndex(home);
319 bufferFailure = pool;
322 bufferPlacements[pool].append(bufferCount(pool), home);
327 SmallVector<unsigned, 2> neighbours;
328 if (
auto homeOp = dyn_cast<TileOp>(home.getDefiningOp()))
331 if (reachable(pool, ArrayRef<TileID>{at}))
332 neighbours.push_back(memTilePositions.lookup(at));
333 for (
int i = 0, e = bufferCount(pool); i < e; ++i) {
334 buffers.push_back({bufferBytes(pool), *index, atHome, neighbours});
335 owners.push_back(pool);
338 bool placed = search.
place(buffers);
341 for (
auto [buffer, pool] : llvm::zip(buffers, owners)) {
342 auto homeOp = dyn_cast<TileOp>(pool.getTile().getDefiningOp());
343 if (!homeOp || !search.
weighed[buffer.home])
345 for (
int col : {homeOp.getCol() - 1, homeOp.getCol() + 1})
346 if (col >= 0 && col < target.columns())
347 spillTile(col, homeOp.getRow(), pool.getLoc());
350 bufferFailure = owners[search.
failed];
353 for (
auto [buffer, tile, pool] : llvm::zip(buffers, search.
chosen, owners))
354 bufferPlacements[pool].push_back(
355 tile == buffer.home ? pool.getTile()
356 : spillTile(memTileAt[tile]->col,
357 memTileAt[tile]->row, pool.getLoc())
363 TileOp spillTile(
int col,
int row, Location loc) {
364 bool declared = llvm::any_of(device.getOps<TileOp>(), [&](TileOp t) {
365 return t.getCol() == col && t.getRow() == row;
367 TileOp tile = TileOp::getOrCreate(builder, device, col, row, loc);
369 spillTiles.push_back(tile);
375 void setInsertionPointOn(Value tile) {
376 Operation *after = lastPlaced.lookup(tile);
378 after = tile.getDefiningOp();
381 builder.setInsertionPointAfter(after);
383 builder.setInsertionPointToStart(device.getBody());
387 void allocateBuffers(ObjectFifoPoolOp pool) {
388 if (pool.getBuffers()) {
391 TileLike home = pool.getTileLike();
392 if (home.isShimTile()) {
396 ArrayRef<Attribute> initValues;
397 if (
auto initAttr = pool.getInitValues()) {
398 initValues = initAttr->getValue();
400 int filled = initValues.size();
401 StringRef base = pool.getBaseName();
403 SmallVector<Attribute> names;
404 MemRefType type = pool.getElemType();
406 if (pool.getContiguous()) {
407 int64_t objectElements = type.getNumElements();
408 type = MemRefType::get({pool.getObjectsPerBuffer() * objectElements},
409 type.getElementType());
411 RankedTensorType::get(type.getShape(), type.getElementType());
412 Attribute zero = builder.getZeroAttr(type.getElementType());
416 auto zeroObjects = pool.getZeroObjects();
417 SmallVector<Attribute> values(
418 (zeroObjects ? (*zeroObjects)[0] : 0) * objectElements, zero);
419 for (
int i = 0; i < pool.getDepth(); i++) {
423 cast<DenseElementsAttr>(initValues[i]).getValues<Attribute>());
425 values.append(objectElements, zero);
427 values.append((zeroObjects ? (*zeroObjects)[1] : 0) * objectElements,
429 zeros = DenseElementsAttr::get(tensor, values);
430 }
else if (pool.getZeroObjects()) {
431 zeros = DenseElementsAttr::get(tensor, zero);
435 for (
int i = 0; i < bufferCount(pool); i++) {
436 ElementsAttr init = !pool.getContiguous() && i < filled
437 ? cast<ElementsAttr>(initValues[i])
439 std::string name = (base +
"__buf" + std::to_string(i)).str();
440 Value placement = bufferPlacements[pool][i];
441 setInsertionPointOn(placement);
442 lastPlaced[placement] = BufferOp::create(
443 builder, pool.getLoc(), type, placement, builder.getStringAttr(name),
446 names.push_back(FlatSymbolRefAttr::get(builder.getContext(), name));
448 pool.setBuffersAttr(builder.getArrayAttr(names));
451 LockOp createLock(ObjectFifoPoolOp pool, Value tile, StringRef name,
453 setInsertionPointOn(tile);
454 auto lock = LockOp::create(builder, pool.getLoc(), tile, value);
455 lastPlaced[tile] = lock;
456 lock->setAttr(SymbolTable::getSymbolAttrName(),
457 builder.getStringAttr(name));
461 LogicalResult planLocks(ArrayRef<ObjectFifoPoolOp> pools) {
463 lockAccessFailure =
nullptr;
464 lockSearchStopped =
false;
465 lockPlacements.clear();
466 LockPlan plan(device.getTargetModel());
467 SmallVector<Value> tileValues;
468 DenseMap<Value, unsigned> tileIndex;
469 auto indexOf = [&](Value tile) {
470 auto [at, fresh] = tileIndex.try_emplace(tile, tileValues.size());
472 auto like = cast<TileLike>(tile.getDefiningOp());
473 auto col = like.tryGetCol(), row = like.tryGetRow();
475 {compatiblePositions(like),
476 col && row ? std::optional<TileID>({*col, *row}) : std::nullopt});
477 tileValues.push_back(tile);
481 for (
auto lock : device.getOps<LockOp>())
482 if (!plan.
reserve(indexOf(lock.getTile()), 1)) {
483 lockFailure = lock.getTile();
488 SmallVector<TileLike> tiles(device.getOps<TileLike>());
489 llvm::stable_sort(tiles, [&](TileLike a, TileLike b) {
490 auto aRank = structuralRank.find(a), bRank = structuralRank.find(b);
491 if ((aRank == structuralRank.end()) != (bRank == structuralRank.end()))
492 return bRank == structuralRank.end();
493 return aRank != structuralRank.end() && aRank->second < bRank->second;
495 SmallVector<unsigned> ranked;
496 for (
auto tile : tiles)
497 if (!llvm::is_contained(spillTiles, tile.getOperation()))
498 ranked.push_back(indexOf(tile->getResult(0)));
499 SmallVector<LockPlan::Group> groups;
500 SmallVector<Operation *> groupOps;
501 SmallVector<ObjectFifoPoolOp> groupPools;
502 auto add = [&](ObjectFifoPoolOp pool, Operation *group,
int count) {
503 SmallVector<unsigned> buffers;
504 for (Value tile : bufferPlacements[pool])
505 if (tile && !llvm::is_contained(spillTiles, tile.getDefiningOp()))
506 buffers.push_back(indexOf(tile));
507 SmallVector<LockPlan::User> users;
508 for (Operation *user : lockUsers[group]) {
509 Value tile = user->getOperand(0);
512 isa<ObjectFifoDmaEndpointOp>(user) &&
514 cast<TileLike>(tile.getDefiningOp()).getTileType())});
518 localPools.contains(pool), buffers, users, ranked));
519 groupOps.push_back(group);
520 groupPools.push_back(pool);
522 for (
auto pool : pools) {
523 if (!poolLocks->needsLocks(pool))
525 SmallVector<Operation *> owners =
527 for (
auto [owner, count] : llvm::zip_equal(
529 pool.getDepth(), owners.size())))
530 add(pool, owner, count);
532 LockPlan::Assignment assignment = plan.
assign(groups);
534 Operation *group = groupOps[*assignment.
failed];
535 const LockPlan::Placed &missed = assignment.
failure;
536 lockSearchStopped = assignment.
stopped;
537 lockSearchStoppedOn = groupPools[*assignment.
failed];
538 lockFailure = missed.
full ? tileValues[*missed.
full] : Value();
539 if (!missed.
reachable && !lockUsers[group].empty())
540 lockAccessFailure = lockUsers[group].front();
543 for (
auto [group, tile] : llvm::zip(groupOps, assignment.
tiles))
545 lockPlacements[group] = tileValues[*tile];
546 auto check = [&](
auto endpoint) {
547 for (Value tile : endpointLockTiles(endpoint)) {
548 if (!canAccessLocks(endpoint, tile)) {
549 lockAccessFailure = endpoint;
555 for (
auto endpoint : device.getOps<ObjectFifoCoreEndpointOp>())
556 if (failed(check(endpoint)))
558 for (
auto endpoint : device.getOps<ObjectFifoDmaEndpointOp>())
559 if (failed(check(endpoint)))
564 void allocateLocks(ObjectFifoPoolOp pool) {
565 if (!poolLocks->needsLocks(pool))
567 StringRef base = pool.getBaseName();
568 int depth = pool.getDepth();
569 auto initValues = pool.getInitValues();
570 int filled = initValues ? initValues->size() : 0;
571 int repeat = pool.getRepeatCount().value_or(1);
573 if (!semaphoreLocks) {
574 if (pool.getLocks()) {
577 SmallVector<Attribute> names;
578 for (
int i = 0; i < depth; i++) {
579 std::string name = (base +
"__lock" + std::to_string(i)).str();
580 createLock(pool, lockPlacement(pool, pool), name, i < filled ? 1 : 0);
581 names.push_back(FlatSymbolRefAttr::get(builder.getContext(), name));
583 pool.setLocksAttr(builder.getArrayAttr(names));
587 for (
auto [index, segment] : llvm::enumerate(pool.getSegmentOps())) {
588 if (segment.getProduceLock() && segment.getConsumeLock()) {
591 std::string produce = (base +
"__prodlock" + std::to_string(index)).str();
592 std::string consume = (base +
"__conslock" + std::to_string(index)).str();
593 Value tile = lockPlacement(pool, segment);
594 createLock(pool, tile, produce, (depth - filled) * repeat);
595 createLock(pool, tile, consume, filled * repeat);
596 segment.setProduceLockAttr(
597 FlatSymbolRefAttr::get(builder.getContext(), produce));
598 segment.setConsumeLockAttr(
599 FlatSymbolRefAttr::get(builder.getContext(), consume));
603 bool canAccessLocks(Operation *endpoint, Value tile) {
604 Value user = endpoint->getOperand(0);
605 if (isa<ObjectFifoDmaEndpointOp>(endpoint) &&
607 cast<TileLike>(user.getDefiningOp()).getTileType()))
608 return canAccess(user, tile,
true);
609 return canAccess(user, tile);
612 template <
typename Endpo
intOp>
613 void collectLockUsers(EndpointOp endpoint) {
614 auto pool = endpoint.getPoolOp();
615 if (!semaphoreLocks) {
616 lockUsers[pool].push_back(endpoint);
619 for (
auto segment : endpoint.getSelectedSegments())
620 lockUsers[segment].push_back(endpoint);
625 template <
typename Endpo
intOp>
626 SmallVector<Value> endpointLockTiles(EndpointOp endpoint) {
627 SmallVector<Value> tiles;
628 auto pool = endpoint.getPoolOp();
629 if (pool.getDepth() == 0)
631 if (!semaphoreLocks) {
632 if (poolLocks->needsLocks(pool) && !pool.getLocks())
633 tiles.push_back(lockPlacement(pool, pool));
635 for (
auto lock : pool.getLockOps())
636 tiles.push_back(lock.getTile());
639 for (
auto segment : endpoint.getSelectedSegments()) {
640 if (poolLocks->needsLocks(pool) &&
641 !(segment.getProduceLock() && segment.getConsumeLock())) {
642 tiles.push_back(lockPlacement(pool, segment));
646 {segment.getProduceLockAttr(), segment.getConsumeLockAttr()})
649 tiles.push_back(lock.getTile());
658 bool reachesAdjacentTile(RouteEndpoint endpoint) {
659 if (ownReachesAdjacentTile(endpoint))
661 for (
auto [sharer, owner] : channelSharers)
662 if (owner == endpoint.getOperation() &&
663 ownReachesAdjacentTile(cast<RouteEndpoint>(sharer)))
670 bool ownReachesAdjacentTile(RouteEndpoint endpoint) {
671 if (
auto route = dyn_cast<RouteEndpointOp>(endpoint.getOperation()))
672 return programReachesAdjacentTile(route);
673 auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation());
674 if (!dma || !dma.getTileLike().isMemTile()) {
677 ObjectFifoPoolOp pool = dma.getPoolOp();
678 auto remote = [&](Value tile) {
679 return tile && !sameTile(tile, endpoint.getTile());
681 return pool && (llvm::any_of(bufferPlacements[pool], remote) ||
682 llvm::any_of(endpointLockTiles(dma), remote));
685 TileLike tileOf(RouteEndpoint endpoint) {
686 return dyn_cast<TileLike>(endpoint.getTile().getDefiningOp());
691 static bool isProgramOwned(RouteEndpoint endpoint) {
692 auto route = dyn_cast<RouteEndpointOp>(endpoint.getOperation());
693 return route && route.getBundle() == WireBundle::DMA &&
694 !route.getTileLike().isShimTile();
697 static int64_t countBDs(Region &taskBody) {
699 taskBody.walk([&](DMABDOp) { bds++; });
704 int64_t endpointBDs(Operation *endpoint) {
706 for (DMAStartOp start : endpointStarts.lookup(endpoint))
713 int64_t bdsOf(RouteEndpoint endpoint) {
714 if (
auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation()))
715 return dma.getNumBDs();
716 if (isProgramOwned(endpoint))
717 return endpointBDs(endpoint.getOperation());
722 int64_t endpointTaskBDs(Operation *endpoint) {
724 for (
auto task : endpointTasks.lookup(endpoint))
725 largest = std::max(largest, countBDs(task.getBody()));
731 bool programReachesAdjacentTile(RouteEndpointOp endpoint) {
732 if (!endpoint.getTileLike().isMemTile())
734 auto remote = [&](Operation *op) {
736 if (
auto bd = dyn_cast<DMABDOp>(op)) {
738 dyn_cast_or_null<BufferOp>(bd.getBuffer().getDefiningOp()))
739 tile = buffer.getTile();
740 }
else if (
auto use = dyn_cast<UseLockOp>(op)) {
741 if (
auto lock = dyn_cast_or_null<LockOp>(use.getLock().getDefiningOp()))
742 tile = lock.getTile();
744 return tile && !sameTile(tile, endpoint.getTile());
746 for (DMAStartOp start : endpointStarts.lookup(endpoint))
748 if (llvm::any_of(block->getOperations(),
749 [&](Operation &op) { return remote(&op); }))
751 for (
auto task : endpointTasks.lookup(endpoint)) {
752 bool reaches =
false;
753 task.getBody().walk([&](Operation *op) { reaches |= remote(op); });
762 void collectChannelPrograms() {
763 endpointStarts.clear();
764 endpointTasks.clear();
766 takenBDs = DMAChannelAnalysis::TakenBDs(device);
767 const AIETargetModel &target = device.getTargetModel();
770 [&](Value tile, DMAChannelDir dir,
771 int channel) -> std::optional<std::tuple<int, int, int, int>> {
772 auto placed = cast<TileLike>(tile.getDefiningOp());
773 auto col = placed.tryGetCol(), row = placed.tryGetRow();
776 if ((dir == DMAChannelDir::MM2S || dir == DMAChannelDir::S2MM) &&
777 target.
getBdPoolId(*col, *row, channel, DMAChannelDir::MM2S) ==
778 target.
getBdPoolId(*col, *row, channel, DMAChannelDir::S2MM))
779 dir = DMAChannelDir::S2MM;
780 return demandKey(*col, *row, dir, channel);
782 for (
auto program : device.getOps<DmaBody>())
783 for (Block &block : program.getDmaBody())
784 for (
auto start : block.getOps<DMAStartOp>())
785 if (
auto endpoint = start.getEndpointOp())
786 endpointStarts[endpoint].push_back(start);
787 device.walk([&](Operation *op) {
788 if (
auto task = dyn_cast<AIEX::DMAConfigureTaskForOp>(op)) {
789 if (
auto endpoint = dyn_cast_or_null<RouteEndpointOp>(
790 SymbolTable::lookupNearestSymbolFrom(
791 device, task.getAlloc().getRootReference())))
792 endpointTasks[endpoint].push_back(task);
793 }
else if (
auto task = dyn_cast<AIEX::DMAConfigureTaskOp>(op)) {
795 key(task.getTile(), task.getDirection(), task.getChannel())) {
796 int64_t unpinned = 0;
797 task.getBody().walk([&](DMABDOp bd) { unpinned += !bd.getBdId(); });
798 int64_t &largest = taskBDs[*at];
799 largest = std::max(largest, unpinned);
809 void rankStructurally() {
810 StructuralGraph graph;
812 DenseMap<std::pair<int, int>, Operation *> placed;
813 DenseMap<Operation *, Operation *> tileNode;
814 for (
auto tile : device.getOps<TileLike>()) {
815 auto col = tile.tryGetCol(), row = tile.tryGetRow();
817 graph.
add(tileNode[tile] = tile);
820 auto [it, first] = placed.try_emplace({*col, *row}, tile);
821 tileNode[tile] = it->second;
823 graph.
nodes.push_back(tile);
824 llvm::raw_string_ostream(graph.
features[tile])
825 <<
"tile " << *col <<
' ' << *row <<
' '
826 << stringifyAIETileType(tile.getTileType());
829 auto link = [&](Operation *from, Operation *to, StringRef label) {
830 if (Operation *tile = tileNode.lookup(to))
832 graph.
link(from, to, label);
834 for (
auto pool : device.getOps<ObjectFifoPoolOp>()) {
835 llvm::raw_string_ostream os(graph.
add(pool));
836 for (
auto segment : pool.getSegmentOps())
837 os <<
" [" << segment.getOffset() <<
", " << segment.getSize() <<
"]";
838 link(pool, pool.getTile().getDefiningOp(),
"tile");
840 DenseMap<StringAttr, Operation *> coreEndpoints;
841 for (
auto endpoint : device.getOps<ObjectFifoCoreEndpointOp>()) {
842 coreEndpoints[endpoint.getSymNameAttr()] = endpoint;
843 llvm::raw_string_ostream os(graph.
add(endpoint));
844 for (
auto segment : endpoint.getSelectedSegments())
845 os <<
" @" << segment.getOffset();
846 link(endpoint, endpoint.getTile().getDefiningOp(),
"tile");
847 link(endpoint, endpoint.getPoolOp(),
"pool");
849 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
850 llvm::raw_string_ostream os(graph.
add(endpoint));
852 dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation())) {
853 for (
auto segment : dma.getSelectedSegments())
854 os <<
" @" << segment.getOffset();
855 link(endpoint, dma.getPoolOp(),
"pool");
857 link(endpoint, endpoint.getTile().getDefiningOp(),
"tile");
859 for (
auto route : device.getOps<RouteOp>()) {
861 for (StringRef source : route.getSourceNames())
862 link(route, lookupEndpoint(source),
"source");
863 for (StringRef dest : route.getDestinationNames())
864 link(route, lookupEndpoint(dest),
"dest");
866 DenseMap<Operation *, unsigned> rank = graph.
rank();
870 for (Operation *node : graph.
nodes)
871 graph.
features[node] = llvm::formatv(
"{0,10}", rank[node]).str();
872 for (
auto core : device.getOps<CoreOp>()) {
874 llvm::SmallPtrSet<Operation *, 8> acquired;
875 core.walk([&](ObjectFifoAcquireOp acquire) {
876 Operation *endpoint =
877 coreEndpoints.lookup(acquire.getObjFifoNameAttr().getAttr());
878 if (endpoint && acquired.insert(endpoint).second)
879 graph.
link(core, endpoint,
880 llvm::formatv(
"acquire {0,10}", acquired.size()).str());
884 for (
auto [tile, node] : tileNode)
885 rank[tile] = rank[node];
886 structuralRank = std::move(rank);
891 int64_t bdRoom(TileLike tile,
int col,
int row, DMAChannelDir dir,
892 int channel,
const BDDemand &demand) {
893 const AIETargetModel &target = device.getTargetModel();
894 int numChannels = std::max(tile.getNumSourceConnections(WireBundle::DMA),
895 tile.getNumDestConnections(WireBundle::DMA));
896 SmallVector<DMAChannelAnalysis::BDGroup> groups =
900 llvm::find_if(groups, [&](
const DMAChannelAnalysis::BDGroup &g) {
901 return llvm::is_contained(g.
users, user);
903 if (group == groups.end())
905 int64_t room = group->size;
906 for (
auto [otherDir, other] : group->users)
907 if (
auto it = demand.find(demandKey(col, row, otherDir, other));
916 DMAChannelAnalysis::BDPlanEnd planEnd(RouteEndpoint endpoint,
bool adjacent,
918 DMAChannelDir dir = endpoint.getRouteDirection();
920 dir, bdsOf(endpoint),
922 keepPin ? endpoint.getRouteChannel() : std::nullopt};
929 int chooseChannel(DMAChannelAnalysis &channels, RouteEndpoint endpoint,
930 const BDDemand &demand,
bool adjacent) {
931 TileLike tile = tileOf(endpoint);
932 DMAChannelDir dir = endpoint.getRouteDirection();
933 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
936 endpoint.getOperation());
938 int64_t bestRoom = 0;
940 for (
int channel = 0; channel < limit; ++channel) {
943 int64_t room = bdRoom(tile, *col, *row, dir, channel, demand);
944 if (best < 0 || room > bestRoom) {
952 endpoint.getOperation());
955 void noteChannelOwner(InFlightDiagnostic &diag, Operation *owner,
956 std::optional<int> channel = std::nullopt) {
957 auto ¬e = diag.attachNote(owner->getLoc());
958 if (
auto endpoint = dyn_cast<RouteEndpoint>(owner)) {
959 note <<
"DMA endpoint @" << cast<SymbolOpInterface>(owner).getName();
960 if (
auto fifo = owner->getAttrOfType<StringAttr>(
"fifoName"))
961 note <<
" for ObjectFifo @" << fifo.getValue();
962 if (reachesAdjacentTile(endpoint))
963 note <<
" requires adjacent MemTile access";
965 note <<
"; occupies channel " << *channel;
966 }
else if (channel) {
967 note <<
"pre-existing " << owner->getName() <<
" reserves DMA channel "
973 DenseSet<Operation *> packetEndpoints() {
974 DenseSet<Operation *> endpoints;
975 for (
auto flow : device.getOps<RouteOp>()) {
976 if (!flow.getPacket())
978 for (StringRef source : flow.getSourceNames())
979 endpoints.insert(lookupEndpoint(source).getOperation());
980 for (StringRef dest : flow.getDestinationNames())
981 endpoints.insert(lookupEndpoint(dest).getOperation());
988 LogicalResult checkStreamPorts() {
989 DMAChannelAnalysis channels(device);
990 DenseSet<Operation *> packetEndpoints = this->packetEndpoints();
992 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
993 if (endpoint.getRouteBundle() != WireBundle::Core)
995 std::optional<int> channel = endpoint.getRouteChannel();
997 return endpoint->emitOpError(
"a stream port names its own channel");
999 tileOf(endpoint), {endpoint.getRouteDirection(), *channel},
1000 endpoint.getOperation(),
1001 packetEndpoints.contains(endpoint.getOperation())));
1003 return failure(clash);
1008 bool drawsOwnChannel(RouteEndpoint endpoint) {
1009 return endpoint.getRouteBundle() != WireBundle::Core &&
1010 !channelSharers.contains(endpoint.getOperation()) &&
1011 !allocationSharers.contains(endpoint.getOperation());
1016 bool sharesPinnedChannel(RouteEndpoint endpoint, DMAChannelDir dir) {
1019 auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation());
1020 if (dir == DMAChannelDir::S2MM)
1021 return !ObjectFifoCreateOp::sharedReceiveRefusal(
1022 tileOf(endpoint).isShimTile(), dma && dma.getOutOfOrder());
1023 if (!tileOf(endpoint).isShimTile() &&
1024 !(dma && dma.getReleaseStrategy() == ObjectFifoRelease::PushQueue))
1026 bool hasPacketRoute =
false;
1027 for (
auto flow : device.getOps<RouteOp>()) {
1028 if (llvm::none_of(flow.getSourceNames(), [&](StringRef name) {
1029 return lookupEndpoint(name).getOperation() ==
1030 endpoint.getOperation();
1033 if (!flow.getPacket())
1035 hasPacketRoute =
true;
1037 return hasPacketRoute;
1040 LogicalResult assignChannels(DMAChannelAnalysis &channels,
1041 bool diagnose =
true) {
1042 channelAssignments.clear();
1043 channelFailure =
nullptr;
1044 bdShortfall =
false;
1045 SmallVector<RouteEndpoint> pending;
1049 for (
auto [col, row] : takenBDs.positions())
1050 for (
auto [user, bds] : takenBDs.at(device.getTargetModel(), col, row))
1051 demand[demandKey(col, row, user.first, user.second)] += bds;
1052 auto noteDemand = [&](RouteEndpoint endpoint,
int channel) {
1053 TileLike tile = tileOf(endpoint);
1054 auto col = tile.tryGetCol(), row = tile.tryGetRow();
1056 demand[demandKey(*col, *row, endpoint.getRouteDirection(), channel)] +=
1059 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
1060 DMAChannelDir dir = endpoint.getRouteDirection();
1061 std::optional<int> channel = endpoint.getRouteChannel();
1062 if (!drawsOwnChannel(endpoint))
1066 if (reachesAdjacentTile(endpoint) &&
1069 channelFailure = endpoint;
1072 return endpoint->emitOpError(
"pinned ")
1073 << stringifyDMAChannelDir(dir) <<
" DMA channel " << *channel
1074 <<
" cannot access adjacent MemTile buffers or locks";
1077 tileOf(endpoint), dir, *channel, endpoint.getOperation(),
1078 sharesPinnedChannel(endpoint, dir)) < 0) {
1081 auto diag = endpoint->emitOpError(
"pinned ");
1082 diag << stringifyDMAChannelDir(dir) <<
" DMA channel " << *channel
1083 <<
" is out of range or already in use on this tile";
1084 if (Operation *owner =
1086 noteChannelOwner(diag, owner, channel);
1089 noteDemand(endpoint, *channel);
1092 pending.push_back(endpoint);
1097 std::map<std::pair<int, int>, SmallVector<RouteEndpoint>> pinnedEnds;
1098 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
1099 TileLike tile = tileOf(endpoint);
1100 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
1101 if (tile.isMemTile() && col && row && endpoint.getRouteChannel() &&
1102 drawsOwnChannel(endpoint))
1103 pinnedEnds[{*col, *row}].push_back(endpoint);
1105 for (
auto &[at, onTile] : pinnedEnds) {
1106 auto [col, row] = at;
1107 SmallVector<DMAChannelAnalysis::BDPlanEnd> ends;
1108 for (RouteEndpoint endpoint : onTile)
1109 ends.push_back(planEnd(endpoint,
false,
true));
1110 std::map<DMAChannelAnalysis::BDUser, int64_t> taken =
1111 takenBDs.at(device.getTargetModel(), col, row);
1113 device.getTargetModel(), col, row, ends,
1114 [](DMAChannelDir,
int) { return true; },
1115 [&](DMAChannelDir dir,
int channel) {
1116 auto it = taken.find({dir, channel});
1117 return it == taken.end() ? 0 : it->second;
1120 int pinnedCol = col, pinnedRow = row;
1121 auto roomOf = [&](RouteEndpoint endpoint) {
1122 return bdRoom(tileOf(endpoint), pinnedCol, pinnedRow,
1123 endpoint.getRouteDirection(), *endpoint.getRouteChannel(),
1127 SmallVector<RouteEndpoint> starved;
1128 for (RouteEndpoint endpoint : onTile)
1129 if (roomOf(endpoint) < 0)
1130 starved.push_back(endpoint);
1131 assert(!starved.empty() &&
1132 "bdRoom and planBDChannels weigh the same BD ids");
1133 llvm::stable_sort(starved, [&](RouteEndpoint a, RouteEndpoint b) {
1134 return std::make_tuple(bdsOf(b), structuralRank.lookup(a)) <
1135 std::make_tuple(bdsOf(a), structuralRank.lookup(b));
1137 RouteEndpoint deepest = starved.front();
1138 channelFailure = deepest;
1142 InFlightDiagnostic diag =
1143 deepest->emitOpError(
"needs ")
1144 << bdsOf(deepest) <<
" buffer descriptors, but pinned "
1145 << stringifyDMAChannelDir(deepest.getRouteDirection())
1146 <<
" DMA channel " << *deepest.getRouteChannel()
1147 <<
" of its tile has " << roomOf(deepest) + bdsOf(deepest)
1148 <<
" left beside the ends on the channels sharing its BD ids";
1149 for (RouteEndpoint other : llvm::drop_begin(starved))
1150 diag.attachNote(other->getLoc())
1151 <<
"this end, on pinned "
1152 << stringifyDMAChannelDir(other.getRouteDirection())
1153 <<
" DMA channel " << *other.getRouteChannel() <<
", needs "
1154 << bdsOf(other) <<
" of them too";
1163 DenseMap<Operation *, int64_t> programBDs;
1164 for (
auto endpoint : pending)
1165 if (isProgramOwned(endpoint))
1166 programBDs[endpoint.getOperation()] =
1167 endpointBDs(endpoint.getOperation());
1168 llvm::stable_sort(pending, [&](RouteEndpoint a, RouteEndpoint b) {
1169 bool aAdjacent = reachesAdjacentTile(a);
1170 bool bAdjacent = reachesAdjacentTile(b);
1171 if (aAdjacent != bAdjacent)
1173 bool aProgram = isProgramOwned(a), bProgram = isProgramOwned(b);
1174 if (aProgram != bProgram)
1176 int64_t aBDs = programBDs.lookup(a.getOperation());
1177 int64_t bBDs = programBDs.lookup(b.getOperation());
1180 return structuralRank.lookup(a.getOperation()) <
1181 structuralRank.lookup(b.getOperation());
1186 DenseMap<Operation *, int> planned;
1187 for (Operation *tileOp : bdPlanned) {
1188 TileLike tile = cast<TileLike>(tileOp);
1189 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
1192 SmallVector<RouteEndpoint> onTile;
1193 SmallVector<DMAChannelAnalysis::BDPlanEnd> ends, unweighted;
1194 for (RouteEndpoint endpoint : pending) {
1195 if (tileOf(endpoint).getOperation() != tileOp)
1197 onTile.push_back(endpoint);
1198 ends.push_back(planEnd(endpoint, reachesAdjacentTile(endpoint),
1200 DMAChannelAnalysis::BDPlanEnd &zeroed =
1201 unweighted.emplace_back(ends.back());
1204 auto free = [&](DMAChannelDir dir,
int channel) {
1207 const AIETargetModel &target = device.getTargetModel();
1209 target, *col, *row, ends, free, [&](DMAChannelDir dir,
int channel) {
1210 return demand.lookup(demandKey(*col, *row, dir, channel));
1213 for (
auto [endpoint, channel] : llvm::zip_equal(onTile, *plan))
1214 planned[endpoint.getOperation()] = channel;
1219 target, *col, *row, unweighted, free,
1220 [](DMAChannelDir,
int) -> int64_t {
return 0; }))
1222 RouteEndpoint deepest =
1223 *llvm::max_element(onTile, [&](RouteEndpoint a, RouteEndpoint b) {
1224 return bdsOf(a) < bdsOf(b);
1226 channelFailure = deepest;
1231 for (
const DMAChannelAnalysis::BDPlanEnd &end : ends)
1233 return deepest->emitOpError(
"needs ")
1234 << bdsOf(deepest) <<
" buffer descriptors, but the tile's "
1235 << ends.size() <<
" unpinned DMA ends need " << total
1236 <<
" in all, more than their channels' BD ids hold";
1239 for (
auto endpoint : pending) {
1240 DMAChannelDir dir = endpoint.getRouteDirection();
1241 TileLike tile = tileOf(endpoint);
1242 bool adjacent = reachesAdjacentTile(endpoint);
1243 if (
auto it = planned.find(endpoint.getOperation());
1244 it != planned.end()) {
1245 channelAssignments[endpoint.getOperation()] =
1247 endpoint.getOperation());
1248 noteDemand(endpoint, it->second);
1254 auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation());
1255 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
1256 if (dma && col && row) {
1258 for (
int free = 0; free < limit; ++free) {
1262 bdRoom(tile, *col, *row, dir, free, demand) >= dma.getNumBDs();
1266 int channel = isProgramOwned(endpoint) || !roomy
1267 ? chooseChannel(channels, endpoint, demand, adjacent)
1269 endpoint.getOperation());
1270 if (channel >= 0 && dma && col && row && tile.isMemTile() &&
1271 bdRoom(tile, *col, *row, dir, channel, demand) < dma.getNumBDs()) {
1272 channelFailure = endpoint;
1276 return endpoint->emitOpError(
"needs ")
1277 << dma.getNumBDs() <<
" buffer descriptors, but channel "
1278 << channel <<
" of its tile has "
1279 << bdRoom(tile, *col, *row, dir, channel, demand)
1280 <<
" left beside the channels sharing its BD ids";
1283 channelFailure = endpoint;
1289 tile.emitOpError(dir == DMAChannelDir::MM2S
1290 ?
"number of output DMA channel exceeded!"
1291 :
"number of input DMA channel exceeded!");
1292 diag <<
" requires at least " << capacity + 1 <<
" "
1293 << stringifyDMAChannelDir(dir) <<
" channels, but capacity is "
1296 diag <<
" for adjacent MemTile access";
1298 for (
int i = 0; i < capacity; ++i)
1300 noteChannelOwner(diag, owner, i);
1301 noteChannelOwner(diag, endpoint.getOperation());
1304 channelAssignments[endpoint.getOperation()] = channel;
1305 noteDemand(endpoint, channel);
1307 DenseSet<Operation *> claimedAllocations;
1308 for (
auto [endpoint, alloc] : allocationSharers) {
1309 auto end = cast<RouteEndpoint>(endpoint);
1310 int channel = alloc.getChannelIndex();
1311 if (claimedAllocations.insert(alloc).second &&
1313 channel, endpoint,
true) < 0) {
1314 channelFailure = end;
1317 auto diag = endpoint->emitOpError(
"cannot share ");
1318 diag << stringifyDMAChannelDir(alloc.getChannelDir()) <<
" DMA channel "
1319 << channel <<
": already in use or unavailable";
1321 tileOf(end), alloc.getChannelDir(), channel))
1322 noteChannelOwner(diag, owner, channel);
1325 channelAssignments[endpoint] = channel;
1326 noteDemand(end, channel);
1328 for (
auto [sharer, owner] : channelSharers)
1329 channelAssignments[sharer] = channelAssignments.lookup(owner);
1333 for (
auto &[at, bds] : taskBDs)
1335 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
1336 TileLike tile = tileOf(endpoint);
1337 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
1338 std::optional<int> channel = endpoint.getRouteChannel();
1339 if (
auto it = channelAssignments.find(endpoint.getOperation());
1340 it != channelAssignments.end())
1341 channel = it->second;
1342 if (isProgramOwned(endpoint) && channel && col && row)
1343 demand[demandKey(*col, *row, endpoint.getRouteDirection(), *channel)] +=
1344 endpointTaskBDs(endpoint.getOperation());
1346 channelDemand = std::move(demand);
1354 bool planShimSharing(TileLike exhausted, DMAChannelDir dir) {
1359 [&](StringAttr symbol) {
1363 SmallVector<Operation *> candidates;
1364 SmallVector<StringAttr> fifos, names;
1365 for (
auto endpoint : device.getOps<RouteEndpointOp>()) {
1366 if (endpoint.getBundle() != WireBundle::DMA ||
1367 endpoint.getChannelIndex() ||
1368 endpoint.getTile() != exhausted->getResult(0) ||
1369 endpoint.getRouteDirection() != dir)
1371 candidates.push_back(endpoint);
1373 names.push_back(endpoint.getSymNameAttr());
1375 SmallVector<ShimDMAAllocationOp> allocations;
1376 SmallVector<ShimTransferSpans::SharedChannel> shared;
1377 for (
auto alloc : device.getOps<ShimDMAAllocationOp>()) {
1378 auto allowed = AIEDialect::ShareableWithAttrHelper(alloc->getContext())
1380 if (!allowed || alloc.getTile() != exhausted->getResult(0) ||
1381 alloc.getChannelDir() != dir)
1383 SmallVector<StringAttr> listed;
1384 for (Attribute attr : allowed)
1385 if (
auto symbol = dyn_cast<FlatSymbolRefAttr>(attr))
1386 listed.push_back(symbol.getAttr());
1388 llvm::any_of(device.getOps<RouteEndpoint>(), [&](RouteEndpoint end) {
1389 return end.getRouteBundle() == WireBundle::DMA &&
1390 sameTile(end.getTile(), alloc.getTile()) &&
1391 end.getRouteDirection() == dir &&
1392 end.getRouteChannel() == alloc.getChannelIndex();
1394 allocations.push_back(alloc);
1395 shared.emplace_back(std::move(listed), pinned);
1398 for (
unsigned channel : llvm::seq<unsigned>(0, shared.size()))
1399 for (
auto [candidate, taken] : llvm::zip(candidates, plan.
sharedChannel))
1400 if (taken == channel &&
1401 allocationSharers.try_emplace(candidate, allocations[channel])
1404 for (
auto &members : plan.
groups)
1405 for (
unsigned sharer : llvm::drop_begin(members))
1407 .insert({candidates[sharer], candidates[members.front()]})
1416 bool canWalkWhole(ObjectFifoPoolOp pool,
1417 ArrayRef<ObjectFifoDmaEndpointOp> regrouped = {}) {
1418 return pool && pool.canWalkWhole() &&
1419 llvm::all_of(device.getOps<ObjectFifoDmaEndpointOp>(),
1420 [&](ObjectFifoDmaEndpointOp end) {
1421 return end.getPoolOp() != pool || !end.getTurns() ||
1422 llvm::is_contained(regrouped, end);
1430 SmallVector<ObjectFifoPoolOp> pools;
1431 SmallVector<DMAChannelAnalysis::BDWalkPool> walkable;
1432 SmallVector<DMAChannelAnalysis::BDPlanEnd> ends;
1433 SmallVector<unsigned> poolOf;
1435 HomeBDPlan homeBDPlan(ArrayRef<ObjectFifoDmaEndpointOp> dmas) {
1437 for (
auto dma : dmas)
1438 if (!llvm::is_contained(plan.pools, dma.getPoolOp()))
1439 plan.pools.push_back(dma.getPoolOp());
1440 llvm::stable_sort(plan.pools, [&](ObjectFifoPoolOp a, ObjectFifoPoolOp b) {
1441 return structuralRank.lookup(a) < structuralRank.lookup(b);
1443 for (ObjectFifoPoolOp pool : plan.pools)
1444 plan.walkable.push_back(
1445 {pool.getDepth(), pool.getObjectSizeInBytes(), canWalkWhole(pool)});
1446 for (
auto dma : dmas) {
1447 auto endpoint = cast<RouteEndpoint>(dma.getOperation());
1448 if (!drawsOwnChannel(endpoint))
1450 plan.ends.push_back(planEnd(endpoint,
false,
1452 plan.poolOf.push_back(llvm::find(plan.pools, dma.getPoolOp()) -
1453 plan.pools.begin());
1462 bool walkForBDShortfall(TileLike tile,
1463 MutableArrayRef<ObjectFifoPoolOp> pools) {
1464 if (walkHomeBDPools(pools))
1466 SmallVector<ObjectFifoDmaEndpointOp> dmas;
1467 for (
auto dma : device.getOps<ObjectFifoDmaEndpointOp>())
1468 if (sameTile(dma.getTile(), tile->getResult(0)) && dma.getPoolOp())
1469 dmas.push_back(dma);
1470 HomeBDPlan plan = homeBDPlan(dmas);
1472 plan.ends, plan.poolOf, plan.walkable,
1473 SmallVector<bool>(plan.pools.size(),
false));
1475 plan.pools[*next].setContiguous(
true);
1476 return next.has_value();
1483 bool walkHomeBDPools(MutableArrayRef<ObjectFifoPoolOp> pools) {
1484 std::map<std::pair<int, int>, SmallVector<ObjectFifoDmaEndpointOp>> ends;
1485 for (
auto dma : device.getOps<ObjectFifoDmaEndpointOp>()) {
1486 TileLike tile = tileOf(cast<RouteEndpoint>(dma.getOperation()));
1487 auto col = tile.tryGetCol(), row = tile.tryGetRow();
1488 if (tile.isMemTile() && col && row && dma.getPoolOp())
1489 ends[{*col, *row}].push_back(dma);
1494 DMAChannelAnalysis::BDWalkSets found;
1495 SmallVector<ObjectFifoDmaEndpointOp> dmas;
1496 unsigned applied = 0;
1498 SmallVector<Tile, 0> tiles;
1502 for (
auto &[at, dmas] : ends) {
1503 HomeBDPlan home = homeBDPlan(dmas);
1504 TileLike tile = tileOf(cast<RouteEndpoint>(dmas.front().getOperation()));
1505 std::map<DMAChannelAnalysis::BDUser, int64_t> taken =
1506 takenBDs.at(device.getTargetModel(), at.first, at.second);
1509 device.getTargetModel(), at.first, at.second, home.ends,
1510 home.poolOf, home.walkable,
1511 [&](DMAChannelDir dir,
int channel) {
1512 return channels.isChannelFree(tile, dir, channel);
1514 [&](DMAChannelDir dir,
int channel) {
1515 auto it = taken.find({dir, channel});
1516 return it == taken.end() ? 0 : it->second;
1519 found.
sets.emplace_back();
1520 found.
bytes.push_back(0);
1521 for (
auto [pool, walkable] : llvm::enumerate(home.walkable))
1522 if (walkable.walkable) {
1523 found.
sets.back().push_back(pool);
1524 found.
bytes.back() += walkable.depth * walkable.objectBytes;
1527 if (!found.
sets.empty())
1529 {{at.first, at.second}, std::move(home), std::move(found), dmas});
1531 auto setWalked = [&](Tile &tile,
bool walked) {
1532 for (
unsigned pool : tile.found.sets[tile.applied])
1533 tile.home.pools[pool].setContiguous(walked);
1535 auto homeOf = [](ObjectFifoPoolOp pool) -> std::optional<TileID> {
1536 TileLike tile = pool.getTileLike();
1537 auto col = tile.tryGetCol(), row = tile.tryGetRow();
1538 if (!tile.isMemTile() || !col || !row)
1539 return std::nullopt;
1540 return TileID{*col, *row};
1542 std::set<std::pair<int, int>> homeSet;
1543 for (ObjectFifoPoolOp pool : pools)
1544 if (std::optional<
TileID> at = homeOf(pool))
1545 homeSet.insert({at->col, at->row});
1546 for (Tile &tile : tiles)
1547 homeSet.insert({tile.at.col, tile.at.row});
1548 SmallVector<TileID> homes;
1549 for (
auto [col, row] : homeSet)
1550 homes.push_back({col, row});
1551 SmallVector<unsigned> componentIds =
1553 std::map<std::pair<int, int>,
unsigned> componentAt;
1554 for (
auto [home,
id] : llvm::zip_equal(homes, componentIds))
1555 componentAt[{home.col, home.row}] = id;
1557 bool walkedAny =
false;
1558 std::set<unsigned> searched;
1559 for (Tile &first : tiles) {
1560 unsigned component = componentAt[{first.at.col, first.at.row}];
1561 if (!searched.insert(component).second)
1563 SmallVector<Tile *> members;
1564 for (Tile &tile : tiles)
1565 if (componentAt[{tile.at.col, tile.at.row}] == component)
1566 members.push_back(&tile);
1567 SmallVector<ObjectFifoPoolOp> componentPools;
1568 for (ObjectFifoPoolOp pool : pools)
1569 if (std::optional<TileID> at = homeOf(pool);
1570 at && componentAt[{at->col, at->row}] == component)
1571 componentPools.push_back(pool);
1572 SmallVector<SmallVector<int64_t>> bytes;
1573 for (Tile *tile : members)
1574 bytes.push_back(tile->found.bytes);
1575 auto apply = [&](ArrayRef<unsigned> choice) {
1576 for (
auto [tile, set] : llvm::zip_equal(members, choice)) {
1577 setWalked(*tile,
false);
1578 tile->applied = set;
1579 setWalked(*tile,
true);
1585 [&](ArrayRef<unsigned> choice) {
1587 SmallVector<ObjectFifoPoolOp> trial(componentPools);
1590 return succeeded(planBuffers(trial));
1594 walkSearchStopped |= choice.stopped;
1595 for (Tile *tile : members) {
1596 if (tile->found.sets[tile->applied].empty())
1599 for (
auto dma : tile->dmas)
1601 tileOf(cast<RouteEndpoint>(dma.getOperation())).getOperation());
1610 bool hostMovesFirst(StringAttr fifo) {
1611 if (
auto it = hostMovesFirstCache.find(fifo);
1612 it != hostMovesFirstCache.end())
1614 bool result = hostMovesFirstUncached(fifo);
1615 hostMovesFirstCache[fifo] = result;
1618 bool hostMovesFirstUncached(StringAttr fifo) {
1619 SymbolTableCollection symbols;
1620 for (
auto seq : device.getOps<RuntimeSequenceOp>()) {
1621 auto names = [&](Operation *op) {
1624 auto waits = [](Operation *op) {
1625 return isa<AIEX::NpuDmaWaitOp, AIEX::DMAAwaitTaskOp, AIEX::NpuSyncOp,
1626 AIEX::NpuMaskPollOp>(op);
1628 bool waited =
false;
1629 WalkResult walk = seq.walk<WalkOrder::PreOrder>([&](Operation *op) {
1632 return WalkResult::advance();
1634 Operation *transfer = op;
1635 if (
auto start = dyn_cast<AIEX::DMAStartTaskOp>(op))
1636 transfer = start.getTask().getDefiningOp();
1638 !isa<AIEX::NpuDmaMemcpyNdOp, AIEX::DMAConfigureTaskForOp,
1639 AIEX::DMAStartBdChainForOp>(transfer) ||
1640 isa<AIEX::DMAConfigureTaskForOp>(op) || !names(transfer))
1641 return WalkResult::advance();
1643 return WalkResult::interrupt();
1644 for (Operation *parent = op->getParentOp(); parent != seq;
1645 parent = parent->getParentOp())
1647 ->walk([&](Operation *inner) {
1648 return waits(inner) ? WalkResult::interrupt()
1649 : WalkResult::advance();
1652 return WalkResult::interrupt();
1653 return WalkResult::advance();
1655 if (walk.wasInterrupted())
1663 ObjectFifoDmaEndpointOp circuitPeer(ObjectFifoDmaEndpointOp endpoint) {
1664 ObjectFifoDmaEndpointOp peer;
1665 StringRef name = endpoint.getSymName();
1666 for (RouteOp route : device.getOps<RouteOp>()) {
1667 SmallVector<StringRef> sources = llvm::to_vector(route.getSourceNames());
1668 SmallVector<StringRef> dests =
1669 llvm::to_vector(route.getDestinationNames());
1670 bool source = llvm::is_contained(sources, name);
1671 if (!source && !llvm::is_contained(dests, name))
1673 if (peer || route.getPacket() || sources.size() != 1 || dests.size() != 1)
1675 RouteEndpoint other = lookupEndpoint(source ? dests[0] : sources[0]);
1676 peer = other ? dyn_cast<ObjectFifoDmaEndpointOp>(other.getOperation())
1677 : ObjectFifoDmaEndpointOp();
1686 ObjectFifoCoreEndpointOp coreEndOf(ObjectFifoDmaEndpointOp endpoint) {
1687 ObjectFifoCoreEndpointOp found;
1688 for (
auto core : device.getOps<ObjectFifoCoreEndpointOp>()) {
1689 if (core.getPool() != endpoint.getPool())
1691 if (found || core.drains() == endpoint.drains())
1701 static SmallVector<std::pair<int64_t, int64_t>>
1702 turnCounts(ArrayRef<ObjectFifoDmaEndpointOp> ends, ArrayRef<unsigned> turns) {
1703 SmallVector<std::pair<int64_t, int64_t>> counts;
1704 for (
auto [i, constEnd] : llvm::enumerate(ends)) {
1705 ObjectFifoDmaEndpointOp end = constEnd;
1706 counts.push_back({llvm::count(turns, i), end.getPoolOp().getContiguous()
1708 : end.getNumDescriptors()});
1716 static bool contiguousWalkersFit(ArrayRef<ObjectFifoDmaEndpointOp> ends,
1717 ArrayRef<unsigned> turns) {
1718 SmallVector<std::pair<int64_t, int64_t>> counts = turnCounts(ends, turns);
1720 for (
auto [i, constEnd] : llvm::enumerate(ends)) {
1721 ObjectFifoDmaEndpointOp end = constEnd;
1722 if (end.getPoolOp().getContiguous() &&
1723 (end.walksStream() ||
1724 end.getPoolOp().getDepth() % (counts[i].first * passes)))
1731 void takeTurns(MutableArrayRef<ObjectFifoDmaEndpointOp> ends,
1732 ArrayRef<unsigned> order) {
1733 SmallVector<Attribute> names;
1734 for (
unsigned i : order)
1735 names.push_back(FlatSymbolRefAttr::get(ends[i].getSymNameAttr()));
1736 ArrayAttr turns = builder.getArrayAttr(names);
1737 Operation *owner = ends[order.front()];
1738 channelSharers.erase(owner);
1739 for (ObjectFifoDmaEndpointOp end : ends) {
1740 end.setTurnsAttr(turns);
1742 channelSharers[end] = owner;
1750 bool planTurnSharing(TileLike exhausted, DMAChannelDir dir) {
1755 DenseMap<Operation *, ObjectFifoCoreEndpointOp> coreEndCache;
1756 DenseMap<Operation *, ObjectFifoDmaEndpointOp> circuitPeerCache;
1757 DenseMap<Operation *, SmallVector<ObjectFifoDmaEndpointOp>> poolEnds;
1758 for (
auto dma : device.getOps<ObjectFifoDmaEndpointOp>()) {
1759 coreEndCache[dma] = coreEndOf(dma);
1760 circuitPeerCache[dma] = circuitPeer(dma);
1761 poolEnds[dma.getPoolOp()].push_back(dma);
1763 auto endsOf = [&](Operation *pool) -> ArrayRef<ObjectFifoDmaEndpointOp> {
1764 auto it = poolEnds.find(pool);
1765 return it == poolEnds.end() ? ArrayRef<ObjectFifoDmaEndpointOp>()
1770 DenseMap<Operation *, ObjectFifoDmaEndpointOp> senderOf;
1771 DenseSet<Operation *> byShim;
1772 auto onShim = [](RouteEndpoint end) {
1773 auto tile = end.getTile().getDefiningOp<TileLike>();
1774 return tile && tile.isShimTile();
1776 for (RouteOp route : device.getOps<RouteOp>()) {
1777 SmallVector<StringRef> sources = llvm::to_vector(route.getSourceNames());
1778 RouteEndpoint source = sources.size() == 1 && !route.getPacket()
1779 ? lookupEndpoint(sources[0])
1783 auto sender = dyn_cast<ObjectFifoDmaEndpointOp>(source.getOperation());
1784 SmallVector<RouteEndpoint> dests;
1785 for (StringRef dest : route.getDestinationNames())
1786 dests.push_back(lookupEndpoint(dest));
1787 for (RouteEndpoint end : dests) {
1789 senderOf[end.getOperation()] = sender;
1790 if (end && onShim(source))
1791 byShim.insert(end.getOperation());
1793 if (llvm::all_of(dests,
1794 [&](RouteEndpoint end) {
return end && onShim(end); }))
1795 byShim.insert(source.getOperation());
1797 auto cachedCoreEnd = [&](ObjectFifoDmaEndpointOp dma) {
1798 return coreEndCache.lookup(dma);
1800 auto cachedCircuitPeer = [&](ObjectFifoDmaEndpointOp dma) {
1801 return circuitPeerCache.lookup(dma);
1803 SmallVector<ObjectFifoDmaEndpointOp> candidates;
1804 for (
auto dma : device.getOps<ObjectFifoDmaEndpointOp>())
1805 if (sameTile(dma.getTile(), exhausted->getResult(0)) &&
1806 dma.getRouteDirection() == dir && cachedCoreEnd(dma) &&
1807 (dma.getTurns() ?
turnEndpoints(dma).front() : dma).canTakeTurns())
1808 if (ObjectFifoDmaEndpointOp peer = cachedCircuitPeer(dma);
1809 peer && peer.canTakeTurns())
1810 candidates.push_back(dma);
1811 llvm::stable_sort(candidates, [&](Operation *a, Operation *b) {
1812 return structuralRank.lookup(a) < structuralRank.lookup(b);
1815 llvm::dbgs() <<
"turns on " << exhausted->getLoc() <<
": "
1816 << candidates.size() <<
" candidate ends\n";
1817 for (
auto dma : device.getOps<ObjectFifoDmaEndpointOp>())
1818 if (sameTile(dma.getTile(), exhausted->getResult(0)) &&
1819 dma.getRouteDirection() == dir)
1820 llvm::dbgs() <<
" " << dma.getSymName() <<
": core end "
1821 << bool(cachedCoreEnd(dma)) <<
", takes turns "
1822 << dma.canTakeTurns() <<
", peer takes turns "
1823 << (cachedCircuitPeer(dma) &&
1824 cachedCircuitPeer(dma).canTakeTurns())
1827 auto groupOf = [](ObjectFifoDmaEndpointOp end) {
1828 SmallVector<ObjectFifoDmaEndpointOp> group =
turnEndpoints(end);
1829 return group.empty() ? SmallVector<ObjectFifoDmaEndpointOp>{end} : group;
1831 for (
auto [i, a] : llvm::enumerate(candidates)) {
1832 for (ObjectFifoDmaEndpointOp b : llvm::drop_begin(candidates, i + 1)) {
1833 SmallVector<ObjectFifoDmaEndpointOp> group = groupOf(a);
1834 if (llvm::is_contained(group, b))
1836 llvm::append_range(group, groupOf(b));
1837 SmallVector<ObjectFifoCoreEndpointOp> cores;
1838 SmallVector<ObjectFifoDmaEndpointOp> peers;
1839 SmallVector<int64_t> depths;
1840 for (ObjectFifoDmaEndpointOp end : group) {
1841 cores.push_back(cachedCoreEnd(end));
1842 peers.push_back(cachedCircuitPeer(end));
1843 depths.push_back(end.getPoolOp().getDepth());
1845 if (llvm::any_of(peers, [&](ObjectFifoDmaEndpointOp peer) {
1846 return !sameTile(peer.getTile(), peers.front().getTile()) ||
1848 return !llvm::is_contained(peers, other);
1851 LLVM_DEBUG(llvm::dbgs()
1852 <<
" " << a.getSymName() <<
" + " << b.getSymName()
1853 <<
": senders on different tiles\n");
1858 if (succeeded(turns.
read(cores, reason)) && !turns.
keepsUp(depths))
1859 reason =
"would stall";
1869 SmallVector<ObjectFifoCoreEndpointOp> peerCores;
1870 SmallVector<int64_t> peerDepths;
1871 SmallVector<unsigned> fed(peers.size(), ~0u);
1872 DenseMap<Operation *, unsigned> fedByPool;
1873 bool lost =
false, hostWaits =
false;
1874 auto wholePool = [&](ObjectFifoDmaEndpointOp peer) {
1875 bool drains = peer.drains();
1876 return peer.getSegments() &&
1877 llvm::all_of(endsOf(peer.getPoolOp()), [&](
auto end) {
1878 return end.drains() != drains ||
1879 llvm::is_contained(peers, end);
1882 for (
auto [i, peer] : llvm::enumerate(peers)) {
1883 if (wholePool(peer)) {
1884 auto segment = fedByPool.find(peer.getPoolOp());
1885 if (segment != fedByPool.end()) {
1886 fed[i] = segment->second;
1890 int64_t depth = peer.getPoolOp().getDepth();
1891 ObjectFifoCoreEndpointOp core = cachedCoreEnd(peer);
1892 SmallPtrSet<Operation *, 8> seen;
1893 for (ObjectFifoDmaEndpointOp at = peer; !core;) {
1894 SmallVector<ObjectFifoDmaEndpointOp> across;
1895 for (ObjectFifoDmaEndpointOp end : endsOf(at.getPoolOp()))
1896 if (end.drains() != at.drains())
1897 across.push_back(end);
1898 if (!seen.insert(at).second || across.size() != 1) {
1902 if (byShim.contains(across.front())) {
1903 hostWaits |= !hostMovesFirst(across.front().getFifoNameAttr());
1906 at = across.front().drains() ? cachedCircuitPeer(across.front())
1907 : senderOf.lookup(across.front());
1912 depth += at.getPoolOp().getDepth();
1913 core = cachedCoreEnd(at);
1917 if (llvm::is_contained(peerCores, core)) {
1921 fed[i] = peerCores.size();
1922 if (wholePool(peer))
1923 fedByPool[peer.getPoolOp()] = fed[i];
1924 peerCores.push_back(core);
1925 peerDepths.push_back(depth);
1927 if (reason.empty() && lost)
1928 reason =
"a peer's feeding core is not known, or feeds two peers";
1929 if (reason.empty() && hostWaits)
1930 reason =
"the host waits before it moves a peer fed by the shim";
1935 SmallVector<unsigned> peerOrder;
1936 DenseMap<unsigned, int64_t> asked;
1937 SmallVector<int64_t> taken(peers.size(), 0);
1938 for (
unsigned turn : turns.
turns()) {
1939 if (fed[turn] == ~0u)
1941 int64_t part = ++taken[turn];
1942 if (part > asked[fed[turn]]) {
1943 asked[fed[turn]] = part;
1944 peerOrder.push_back(fed[turn]);
1946 ObjectFifoPoolOp pool = peers[turn].getPoolOp();
1947 int64_t fewest = part;
1948 for (
auto [j, other] : llvm::enumerate(peers))
1949 if (other.getPoolOp() == pool)
1950 fewest = std::min(fewest, taken[j]);
1951 if (reason.empty() && asked[fed[turn]] - fewest > pool.getDepth())
1952 reason =
"a pool's segments hold more objects open than it has";
1954 for (
auto [i, peer] : llvm::enumerate(peers))
1955 for (
auto [j, other] : llvm::enumerate(peers))
1956 if (reason.empty() && other.getPoolOp() == peer.getPoolOp() &&
1957 taken[i] != taken[j])
1958 reason =
"a pool's segments take different counts of turns";
1959 if (reason.empty() && !peerCores.empty()) {
1961 if (llvm::any_of(peerCores, [&](ObjectFifoCoreEndpointOp c) {
1962 return !sameTile(c.getTile(), peerCores.front().getTile());
1964 reason =
"several cores feed the peers";
1965 else if (succeeded(peerTurns.
read(peerCores, reason)) &&
1966 !peerTurns.
keepsUp(peerOrder, peerDepths))
1967 reason =
"the core at the peers' far end would stall";
1971 bool overflows =
false;
1972 if (reason.empty()) {
1973 SmallVector<std::pair<int64_t, int64_t>> counts =
1974 turnCounts(peers, turns.
turns());
1975 TileLike tile = peers.front().getTileLike();
1976 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
1980 device.getTargetModel().getNumBDsForChannel(*col, *row, 0);
1986 SmallVector<ObjectFifoPoolOp> walked;
1987 if (reason.empty() &&
1988 (overflows || !contiguousWalkersFit(peers, turns.
turns())))
1989 for (ObjectFifoDmaEndpointOp peer : peers) {
1990 ObjectFifoPoolOp pool = peer.getPoolOp();
1991 SmallVector<ObjectFifoDmaEndpointOp> others;
1992 for (
auto end : device.getOps<ObjectFifoDmaEndpointOp>())
1993 if (end.getPoolOp() == pool && end.getTurns() &&
1994 !llvm::is_contained(peers, end))
1995 others.push_back(end);
1996 SmallVector<ObjectFifoDmaEndpointOp> ignored(peers);
1997 llvm::append_range(ignored, others);
1998 if (!canWalkWhole(pool, ignored)) {
1999 LLVM_DEBUG(llvm::dbgs() <<
" " << pool.getSymName()
2000 <<
" cannot be walked whole\n");
2003 pool.setContiguous(
true);
2005 llvm::all_of(others, [&](ObjectFifoDmaEndpointOp end) {
2006 SmallVector<ObjectFifoDmaEndpointOp> ends =
2008 SmallVector<unsigned> order;
2010 end.getTurnsAttr().getAsRange<FlatSymbolRefAttr>())
2013 [&](ObjectFifoDmaEndpointOp e) {
2014 return e.getSymNameAttr() ==
2018 return contiguousWalkersFit(ends, order);
2022 <<
" " << pool.getSymName() <<
" walked whole"
2023 << (linedUp ?
"" :
", but its other turns would not line up")
2026 walked.push_back(pool);
2027 turnWalked.insert(pool);
2029 pool.setContiguous(
false);
2031 if (reason.empty() && (!contiguousWalkersFit(group, turns.
turns()) ||
2032 !contiguousWalkersFit(peers, turns.
turns()))) {
2033 reason =
"a contiguous pool's objects do not divide among its turns";
2034 for (ObjectFifoPoolOp pool : walked)
2035 pool.setContiguous(
false);
2037 if (!reason.empty()) {
2038 LLVM_DEBUG(llvm::dbgs() <<
" " << a.getSymName() <<
" + "
2039 << b.getSymName() <<
": " << reason <<
"\n");
2042 takeTurns(group, turns.
turns());
2043 takeTurns(peers, turns.
turns());
2054 LogicalResult headShimSharingRoutes() {
2055 DenseMap<Operation *, Operation *> channelOf;
2056 for (
auto [sharer, owner] : channelSharers) {
2057 if (!tileOf(cast<RouteEndpoint>(owner)).isShimTile())
2059 channelOf[sharer] = owner;
2060 channelOf[owner] = owner;
2062 for (
auto [endpoint, alloc] : allocationSharers)
2063 channelOf[endpoint] = alloc.getOperation();
2064 auto channelsOf = [&](RouteOp route) {
2065 SmallVector<Operation *> channels;
2066 auto note = [&](StringRef name) {
2067 if (
auto endpoint = lookupEndpoint(name);
2068 endpoint && channelOf.count(endpoint.getOperation()))
2069 channels.push_back(channelOf.lookup(endpoint.getOperation()));
2071 llvm::for_each(route.getSourceNames(), note);
2072 llvm::for_each(route.getDestinationNames(), note);
2075 DenseMap<Operation *, DenseSet<int>> idsOn;
2076 for (
auto route : device.getOps<RouteOp>())
2077 if (PacketInfoAttr packet = route.getPacketAttr();
2078 packet && packet.isAssigned())
2079 for (Operation *channel : channelsOf(route))
2080 idsOn[channel].insert(packet.assignedId());
2082 SmallVector<int> reused;
2083 for (
auto route : device.getOps<RouteOp>()) {
2084 SmallVector<Operation *> channels = channelsOf(route);
2085 if (route.getPacket() || channels.empty())
2087 auto freeOnAll = [&](
int id) {
2088 return llvm::none_of(channels, [&](Operation *channel) {
2089 return idsOn[channel].contains(
id);
2092 std::optional<int> id;
2093 if (
auto *it = llvm::find_if(reused, freeOnAll); it != reused.end())
2095 else if ((
id = ids.takeLowestFrom()))
2096 reused.push_back(*
id);
2098 return route.emitOpError(
"shares a shim channel, but no packet id is "
2099 "left to tell its transfers apart");
2100 for (Operation *channel : channels)
2101 idsOn[channel].insert(*
id);
2102 route.setPacketAttr(PacketInfoAttr::get(builder.getContext(), 0,
2103 static_cast<uint16_t
>(*
id)));
2111 void warnOvercommittedBDs() {
2113 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
2114 auto it = channelAssignments.find(endpoint.getOperation());
2115 TileLike tile = tileOf(endpoint);
2116 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
2117 if (it == channelAssignments.end() || !isProgramOwned(endpoint) || !col ||
2120 int channel = it->second;
2121 DMAChannelDir dir = endpoint.getRouteDirection();
2122 int64_t room = bdRoom(tile, *col, *row, dir, channel, channelDemand);
2126 endpoint->emitWarning(
"")
2127 << stringifyDMAChannelDir(endpoint.getRouteDirection())
2128 <<
" DMA channel " << channel <<
" can use " << numBDs
2129 <<
" BDs, but it and the channels sharing them need " << numBDs - room
2130 <<
" at once; BD id assignment fails unless tasks free their BDs "
2131 "before others start";
2142 LogicalResult planAllocation(ArrayRef<ObjectFifoPoolOp> pools,
2143 std::set<std::vector<unsigned>> &tried) {
2144 std::vector<unsigned> key;
2145 for (
auto [index, pool] : llvm::enumerate(pools)) {
2146 if (
auto tile = localPools.lookup(pool)) {
2147 auto placed = cast<TileLike>(tile.getDefiningOp());
2148 auto col = placed.tryGetCol(), row = placed.tryGetRow();
2149 assert(col && row &&
"locality repair requires resolved coordinates");
2150 key.push_back(index);
2151 key.push_back(*col);
2152 key.push_back(*row);
2155 if (tried.size() >= 64 || !tried.insert(key).second ||
2156 failed(planBuffers(pools)) || failed(planLocks(pools)))
2159 if (succeeded(assignChannels(channels,
false)))
2161 if (!channelFailure || !tileOf(channelFailure).isMemTile() ||
2162 !tileOf(channelFailure).tryGetCol() ||
2163 !tileOf(channelFailure).tryGetRow())
2166 Value localTile = channelFailure.getTile();
2167 SmallVector<ObjectFifoPoolOp> candidates;
2168 for (
auto dma : device.getOps<ObjectFifoDmaEndpointOp>()) {
2169 auto endpoint = cast<RouteEndpoint>(dma.getOperation());
2170 auto pool = dma.getPoolOp();
2171 if (!pool || localPools.contains(pool) ||
2172 !sameTile(endpoint.getTile(), channelFailure.getTile()) ||
2173 endpoint.getRouteDirection() != channelFailure.getRouteDirection() ||
2174 (channelFailure.getRouteChannel() && endpoint != channelFailure) ||
2175 (endpoint.getRouteChannel() && endpoint != channelFailure) ||
2176 !ownReachesAdjacentTile(endpoint) ||
2177 llvm::is_contained(candidates, pool))
2179 candidates.push_back(pool);
2181 llvm::stable_sort(candidates, [&](ObjectFifoPoolOp a, ObjectFifoPoolOp b) {
2183 a.getBuffers() ? 0 : a.getObjectSizeInBytes() * a.getDepth();
2185 b.getBuffers() ? 0 : b.getObjectSizeInBytes() * b.getDepth();
2186 if (aBytes != bBytes)
2187 return aBytes < bBytes;
2188 return structuralRank.lookup(a) < structuralRank.lookup(b);
2190 for (
auto pool : candidates) {
2191 localPools[pool] = localTile;
2192 if (succeeded(planAllocation(pools, tried)))
2194 localPools.erase(pool);
2203 LogicalResult lowerPacketFlow(RouteOp flow, ArrayRef<RouteEndpoint> sources,
2204 PacketInfoAttr header) {
2205 int packetID = header.assignedId();
2206 for (
auto [name, endpoint] : llvm::zip_equal(
2207 flow.getSources().getAsRange<FlatSymbolRefAttr>(), sources)) {
2208 RouteEndpoint source = endpoint;
2210 if (
auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(*source);
2211 dma && dma.getDispatch()) {
2212 dispatchHeaders[dma][*flow.getDestinationNames().begin()] = header;
2215 if (sourcedFlows.at(name.getAttr()).size() == 1)
2216 source.setRoutePacket(header);
2221 bool keepHeader = flow.getKeepPktHeader();
2222 for (StringRef destName : flow.getDestinationNames())
2223 if (
auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(
2224 lookupEndpoint(destName).getOperation()))
2225 keepHeader |= dma.getOutOfOrder();
2227 builder.setInsertionPoint(flow);
2228 auto packetFlow = PacketFlowOp::create(
2229 builder, flow.getLoc(),
2230 builder.getIntegerAttr(builder.getI8Type(), packetID),
2231 keepHeader ? builder.getBoolAttr(
true) :
nullptr,
nullptr);
2232 OpBuilder::InsertionGuard g(builder);
2233 Block &ports = packetFlow.getRegion().emplaceBlock();
2234 builder.setInsertionPointToStart(&ports);
2235 EndOp::create(builder, flow.getLoc());
2237 builder.setInsertionPointToStart(&ports);
2238 for (RouteEndpoint source : sources) {
2239 PacketSourceOp::create(builder, flow.getLoc(), source.getTile(),
2240 source.getRouteBundle(), channelOf(source));
2242 for (StringRef destName : flow.getDestinationNames()) {
2243 auto dest = lookupEndpoint(destName);
2246 if (
auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(dest.getOperation()))
2247 if (dma.getOutOfOrder())
2248 dest.setRoutePacket(header);
2249 PacketDestOp::create(builder, flow.getLoc(), dest.getTile(),
2250 dest.getRouteBundle(), channelOf(dest));
2256 int channelOf(RouteEndpoint endpoint) {
2257 std::optional<int> channel = endpoint.getRouteChannel();
2258 assert(channel &&
"channels are assigned before flows are lowered");
2262 RouteEndpoint lookupEndpoint(StringRef name) {
2263 return dyn_cast_or_null<RouteEndpoint>(SymbolTable::lookupNearestSymbolFrom(
2264 device, StringAttr::get(device.getContext(), name)));
2267 LogicalResult lowerFlows() {
2270 DenseMap<std::tuple<Value, int, int>, Operation *> pushedPacketSources;
2271 for (RouteOp flow : device.getOps<RouteOp>()) {
2272 auto packet = flow.getPacket();
2273 if (!packet || !packet->isAssigned())
2275 for (StringRef name : flow.getSourceNames()) {
2276 auto source = dyn_cast<ObjectFifoDmaEndpointOp>(
2277 lookupEndpoint(name).getOperation());
2279 source.getReleaseStrategy() != ObjectFifoRelease::PushQueue)
2281 auto [it, inserted] = pushedPacketSources.try_emplace(
2282 std::make_tuple(source.getTile(), channelOf(source),
2283 packet->assignedId()),
2284 source.getOperation());
2285 if (!inserted && it->second != source.getOperation()) {
2286 auto diag = source.emitOpError(
2287 "core-pushed senders sharing an MM2S channel require distinct "
2289 diag.attachNote(it->second->getLoc()) <<
"other sender is here";
2294 DenseSet<std::tuple<Value, int, Value, int>> circuits;
2295 for (RouteOp flow : device.getOps<RouteOp>())
2296 for (
auto name : flow.getSources().getAsRange<FlatSymbolRefAttr>())
2297 sourcedFlows[name.getAttr()].push_back(flow);
2298 for (
auto flow : device.getOps<RouteOp>()) {
2299 SmallVector<RouteEndpoint> sources;
2300 for (StringRef name : flow.getSourceNames()) {
2301 sources.push_back(lookupEndpoint(name));
2303 loweredFlows.push_back(flow);
2307 if (std::optional<PacketInfoAttr> packet = flow.getPacket()) {
2308 if (!packet->isAssigned()) {
2309 return flow.emitOpError(
"has a packet header with no pkt_id; run "
2310 "--aie-assign-packet-ids before this pass");
2312 if (failed(lowerPacketFlow(flow, sources, *packet))) {
2319 RouteEndpoint source = sources.front();
2321 int sourceChannel = channelOf(source);
2322 builder.setInsertionPoint(flow);
2323 for (StringRef destName : flow.getDestinationNames()) {
2324 auto dest = lookupEndpoint(destName);
2327 .insert({source.getTile(), sourceChannel, dest.getTile(),
2331 FlowOp::create(builder, flow.getLoc(), source.getTile(),
2332 source.getRouteBundle(), sourceChannel, dest.getTile(),
2333 dest.getRouteBundle(), channelOf(dest));
2336 for (
auto &[endpoint, byDest] : dispatchHeaders) {
2337 SmallVector<Attribute> headers;
2338 for (StringRef dest :
2339 endpoint.getDispatchAttr().getAsValueRange<FlatSymbolRefAttr>())
2340 headers.push_back(byDest.lookup(dest));
2341 endpoint.setDispatchPacketsAttr(builder.getArrayAttr(headers));
2349 LogicalResult bindRearmTargets() {
2350 if (poolLocks->rearms().empty()) {
2354 builder.setInsertionPoint(device.getBody()->getTerminator());
2355 for (
auto &[fifoName, users] : poolLocks->rearms()) {
2356 SmallVector<Value> channelTiles, lockValues;
2357 SmallVector<int32_t> channelDirs, channelIndices, lockInits;
2359 SmallVector<Location> locs;
2361 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
2362 std::optional<int> channel = endpoint.getRouteChannel();
2363 if (endpoint.getFifoName() != fifoName ||
2364 tileOf(endpoint).isShimTile() || !channel) {
2368 dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation());
2369 dma && dma.getReleaseStrategy() == ObjectFifoRelease::PushQueue) {
2370 for (AIEX::DmaChannelResetForOp user : users)
2372 "does not support core-pushed DMA channels; reset requires "
2373 "coordination with the issuing core and all shared senders");
2376 channelTiles.push_back(endpoint.getTile());
2377 channelDirs.push_back(
2378 static_cast<int32_t
>(endpoint.getRouteDirection()));
2379 channelIndices.push_back(*channel);
2380 locs.push_back(endpoint->getLoc());
2382 for (
auto pool : device.getOps<ObjectFifoPoolOp>()) {
2383 if (pool.getFifoName() != fifoName || pool.getTileLike().isShimTile()) {
2386 locs.push_back(pool.getLoc());
2387 for (LockOp lock : pool.getLockOps()) {
2388 lockValues.push_back(lock.getResult());
2389 lockInits.push_back(lock.getInit().value_or(0));
2393 if (channelTiles.empty() && lockValues.empty()) {
2394 for (AIEX::DmaChannelResetForOp user : users) {
2395 user.emitOpError() <<
"objectFIFO '" << fifoName
2396 <<
"' has no resident core/mem DMA channels or "
2402 std::string name = (fifoName +
"__rearm").str();
2405 name = (fifoName +
"__rearm" + std::to_string(suffix + 1)).str();
2409 ObjectFifoRearmBindingOp::create(
2410 builder, FusedLoc::get(builder.getContext(), locs),
2411 builder.getStringAttr(name), ValueRange(channelTiles),
2412 ValueRange(lockValues), builder.getDenseI32ArrayAttr(channelDirs),
2413 builder.getDenseI32ArrayAttr(channelIndices),
2414 builder.getDenseI32ArrayAttr(lockInits),
2415 DenseI32ArrayAttr(),
2416 DenseI32ArrayAttr());
2417 auto target = FlatSymbolRefAttr::get(builder.getContext(), name);
2418 for (AIEX::DmaChannelResetForOp user : users) {
2419 user.setObjfifoAttr(target);
2426 LogicalResult resolveStart(DMAStartOp start, RouteEndpointOp endpoint,
2427 ArrayRef<RouteOp> flows, ArrayRef<int> ids,
2429 DMAChannelDir dir = endpoint.getRouteDirection();
2430 if (start.getChannelDir() != dir)
2431 return start.emitOpError(
"starts ")
2432 << stringifyDMAChannelDir(start.getChannelDir()) <<
" on "
2433 << start.getEndpoint() <<
", but its route makes it "
2434 << stringifyDMAChannelDir(dir);
2437 bool packet = !flows.empty() && RouteOp(flows.front()).getPacket();
2439 SmallVector<DMABDOp> bds;
2441 llvm::append_range(bds, block->getOps<DMABDOp>());
2442 if (failed(checkHeaders(endpoint, ids, bds)))
2445 start.setChannelAttr(builder.getI32IntegerAttr(channel));
2451 LogicalResult checkHeaders(RouteEndpointOp endpoint, ArrayRef<int> ids,
2452 ArrayRef<DMABDOp> bds) {
2453 for (DMABDOp bd : bds) {
2454 std::optional<int> id;
2455 if (
auto packet = bd.getPacket())
2456 id = packet->getPktId();
2457 else if (
auto ops = bd->getBlock()->getOps<DMABDPACKETOp>(); !ops.empty())
2458 id = (*ops.begin()).getPacketId();
2459 if (
id && llvm::is_contained(ids, *
id))
2461 return bd.emitOpError(
"sends on @")
2462 << endpoint.getSymName()
2463 <<
" without the packet header of one of its flows, ids " << ids;
2471 LogicalResult checkSharedSourceUsers(RouteEndpointOp endpoint,
2472 ArrayRef<int> ids) {
2473 auto uses = SymbolTable::getSymbolUses(endpoint, device);
2476 for (
const SymbolTable::SymbolUse &use : *uses) {
2477 Operation *user = use.getUser();
2478 if (
auto task = dyn_cast<AIEX::DMAConfigureTaskForOp>(user)) {
2479 SmallVector<DMABDOp> bds;
2480 task.getBody().walk([&](DMABDOp bd) { bds.push_back(bd); });
2481 if (failed(checkHeaders(endpoint, ids, bds)))
2485 if (
auto start = dyn_cast<AIEX::DMAStartBdChainForOp>(user)) {
2486 auto chain = device.lookupSymbol<BDChainOp>(start.getSymbol());
2488 return start.emitOpError(
"symbol does not reference valid BD chain");
2489 SmallVector<DMABDOp> bds;
2490 chain.getBody().walk([&](DMABDOp bd) { bds.push_back(bd); });
2491 if (failed(checkHeaders(endpoint, ids, bds)))
2495 auto memcpy = dyn_cast<AIEX::NpuDmaMemcpyNdOp>(user);
2498 std::optional<PacketInfoAttr> packet = memcpy.getPacket();
2499 if (packet && llvm::is_contained(ids, packet->getPktId()))
2501 return memcpy.emitOpError(
"sends on @")
2502 << endpoint.getSymName()
2503 <<
", a source several packet routes share, which has no one "
2504 "header to stamp; it needs a packet header of its own, one of "
2513 void resolveTask(AIEX::DMAConfigureTaskForOp task, RouteEndpointOp endpoint,
2515 builder.setInsertionPoint(task);
2516 auto configured = AIEX::DMAConfigureTaskOp::create(
2517 builder, task.getLoc(), builder.getIndexType(), endpoint.getTile(),
2518 DMAChannelDirAttr::get(builder.getContext(),
2519 endpoint.getRouteDirection()),
2520 builder.getI32IntegerAttr(channel),
2521 builder.getBoolAttr(task.getIssueToken()),
2522 builder.getI32IntegerAttr(task.getRepeatCount()),
2523 task.getRepeatCountVal(), endpoint.getPacketAttr(),
2524 UnitAttr(), FlatSymbolRefAttr());
2525 task.getResult().replaceAllUsesWith(configured.getResult());
2526 configured.getBody().takeBody(task.getBody());
2533 LogicalResult resolveEndpointUses() {
2534 for (
auto endpoint : device.getOps<RouteEndpointOp>()) {
2535 auto starts = endpointStarts.lookup(endpoint);
2536 auto tasks = endpointTasks.lookup(endpoint);
2537 auto sourced = sourcedFlows.find(endpoint.getSymNameAttr());
2538 ArrayRef<RouteOp> flows;
2539 if (sourced != sourcedFlows.end())
2540 flows = sourced->second;
2541 SmallVector<int> ids;
2542 for (RouteOp flow : flows)
2543 if (std::optional<PacketInfoAttr> packet = flow.getPacket();
2544 packet && packet->isAssigned())
2545 ids.push_back(packet->assignedId());
2546 bool shared = flows.size() > 1;
2547 if (shared && failed(checkSharedSourceUsers(endpoint, ids)))
2549 if (starts.empty() && tasks.empty())
2551 std::optional<int> channel = endpoint.getRouteChannel();
2552 assert(channel &&
"assignChannels gives every routed endpoint one");
2553 for (DMAStartOp start : starts)
2554 if (failed(resolveStart(start, endpoint, flows, ids, *channel)))
2556 if (endpoint.getTileLike().isShimTile() && endpoint.getFifoName())
2558 for (
auto task : tasks)
2559 resolveTask(task, endpoint, *channel);
2566 void emitShimAllocations() {
2567 builder.setInsertionPoint(device.getBody()->getTerminator());
2572 llvm::StringMap<unsigned> shimEndsSeen;
2573 for (
auto endpoint : device.getOps<RouteEndpoint>()) {
2574 std::optional<StringRef> fifoName = endpoint.getFifoName();
2576 if (
auto named = dyn_cast<RouteEndpointOp>(endpoint.getOperation()))
2577 fifoName = named.getSymName();
2578 std::optional<int> channel = endpoint.getRouteChannel();
2579 if (!tileOf(endpoint).isShimTile() || !fifoName || !channel) {
2582 std::string name = (*fifoName +
"__shim_alloc").str();
2583 unsigned ordinal = shimEndsSeen[*fifoName]++;
2587 create = !SymbolTable::lookupNearestSymbolFrom<ShimDMAAllocationOp>(
2588 device, builder.getStringAttr(name));
2590 for (
unsigned suffix = ordinal - 1; device.lookupSymbol(name);
2593 (*fifoName +
"__shim_alloc" + std::to_string(suffix + 1)).str();
2599 auto routeEndpoint = dyn_cast<RouteEndpointOp>(endpoint.getOperation());
2600 ShimDMAAllocationOp::create(
2601 builder, endpoint.getLoc(), builder.getStringAttr(name),
2603 DMAChannelDirAttr::get(builder.getContext(),
2604 endpoint.getRouteDirection()),
2605 builder.getI64IntegerAttr(*channel),
2606 builder.getBoolAttr(endpoint.getRouteBundle() == WireBundle::PLIO),
2607 endpoint->getAttrOfType<PacketInfoAttr>(
"packet"),
2608 routeEndpoint ? routeEndpoint.getConsumedByAttr() : ArrayAttr());
2611 (void)SymbolTable::replaceAllSymbolUses(
2612 endpoint, builder.getStringAttr(name), device);
2620 void sizeOrder(MutableArrayRef<ObjectFifoPoolOp> pools) {
2621 SmallVector<size_t> memTileSlots;
2622 SmallVector<ObjectFifoPoolOp> memTilePools;
2623 for (
auto [index, pool] : llvm::enumerate(pools)) {
2624 if (pool.getTileLike().isMemTile()) {
2625 memTileSlots.push_back(index);
2626 memTilePools.push_back(pool);
2629 llvm::stable_sort(memTilePools, [](ObjectFifoPoolOp a, ObjectFifoPoolOp b) {
2630 auto home = [](ObjectFifoPoolOp pool) {
2631 TileLike tile = pool.getTileLike();
2632 auto col = tile.tryGetCol(), row = tile.tryGetRow();
2633 return std::make_tuple(!col || !row, col.value_or(0), row.value_or(0));
2635 return home(a) < home(b);
2638 for (
auto [slot, pool] : llvm::zip(memTileSlots, memTilePools))
2644 SmallVector<ObjectFifoPoolOp>
2645 demandOrderedPools(ArrayRef<ObjectFifoPoolOp> pools) {
2646 DenseMap<Operation *, std::pair<int, int>> poolChannelDemand;
2647 for (
auto endpoint : device.getOps<ObjectFifoDmaEndpointOp>()) {
2648 ObjectFifoPoolOp pool = endpoint.getPoolOp();
2649 if (!sameTile(endpoint.getTile(), pool.getTile()))
2651 auto &demand = poolChannelDemand[pool];
2652 if (endpoint.getRouteDirection() == DMAChannelDir::S2MM)
2657 SmallVector<size_t> memTileSlots;
2658 SmallVector<Value> homes;
2659 SmallVector<SpillPool> records;
2660 for (
size_t index = 0, e = pools.size(); index < e; ++index) {
2661 ObjectFifoPoolOp pool = pools[index];
2662 if (!pool.getTileLike().isMemTile())
2664 memTileSlots.push_back(index);
2665 auto *home = llvm::find_if(
2666 homes, [&](Value known) {
return sameTile(pool.getTile(), known); });
2667 if (home == homes.end()) {
2668 homes.push_back(pool.getTile());
2669 home = std::prev(homes.end());
2671 auto [input, output] = poolChannelDemand.lookup(pool.getOperation());
2672 records.push_back({bufferBytes(pool), bufferCount(pool),
2673 static_cast<unsigned>(home - homes.begin()),
2674 std::max(input, output)});
2676 SmallVector<ObjectFifoPoolOp> ordered(pools);
2677 for (
auto [slot, index] :
2679 ordered[slot] = pools[memTileSlots[index]];
2683 void runOnOperation()
override {
2684 device = getOperation();
2685 builder = OpBuilder(device.getContext());
2690 channelSharers.clear();
2691 allocationSharers.clear();
2693 loweredFlows.clear();
2694 sourcedFlows.clear();
2698 lockPlacements.clear();
2700 dispatchHeaders.clear();
2701 channelSharers.clear();
2704 hostMovesFirstCache.clear();
2705 bufferPlacements.clear();
2706 channelAssignments.clear();
2707 endpointStarts.clear();
2708 endpointTasks.clear();
2711 channelDemand.clear();
2712 structuralRank.clear();
2713 channelFailure =
nullptr;
2714 bufferFailure =
nullptr;
2715 lockFailure =
nullptr;
2716 lockAccessFailure =
nullptr;
2717 walkSearchStopped =
false;
2719 if (failed(collectFixedMemory()) || failed(checkStreamPorts()))
2720 return signalPassFailure();
2721 collectChannelPrograms();
2726 SmallVector<ObjectFifoPoolOp> pools(device.getOps<ObjectFifoPoolOp>());
2727 llvm::stable_sort(pools, [&](ObjectFifoPoolOp a, ObjectFifoPoolOp b) {
2728 return structuralRank.lookup(a) < structuralRank.lookup(b);
2732 poolLocks = std::make_shared<PoolLocks>(device);
2733 for (
auto endpoint : device.getOps<ObjectFifoCoreEndpointOp>()) {
2734 poolUsers[endpoint.getPoolOp()].push_back(endpoint.getTile());
2735 collectLockUsers(endpoint);
2737 for (
auto endpoint : device.getOps<ObjectFifoDmaEndpointOp>()) {
2738 poolUsers[endpoint.getPoolOp()].push_back(endpoint.getTile());
2739 collectLockUsers(endpoint);
2741 for (
auto &[group, users] : lockUsers)
2742 llvm::stable_sort(users, [&](Operation *a, Operation *b) {
2743 return structuralRank.lookup(a) < structuralRank.lookup(b);
2746 std::set<std::vector<unsigned>> tried;
2747 LogicalResult allocated = planAllocation(pools, tried);
2748 if (failed(allocated)) {
2749 auto demandOrdered = demandOrderedPools(pools);
2750 if (!llvm::equal(pools, demandOrdered)) {
2754 allocated = planAllocation(demandOrdered, tried);
2764 if (channelFailure) {
2765 TileLike tile = tileOf(channelFailure);
2766 DMAChannelDir dir = channelFailure.getRouteDirection();
2768 if (bdPlanned.insert(tile.getOperation()) ||
2769 walkForBDShortfall(tile, pools))
2771 }
else if (tile.isShimTile() ? planShimSharing(tile, dir)
2772 : planTurnSharing(tile, dir)) {
2777 return failed(planBuffers(pools)) && walkHomeBDPools(pools);
2779 while (failed(allocated) && repair()) {
2783 allocated = planAllocation(pools, tried);
2785 if (succeeded(allocated) &&
2786 (!channelSharers.empty() || !allocationSharers.empty()) &&
2787 failed(headShimSharingRoutes()))
2788 return signalPassFailure();
2789 if (failed(allocated)) {
2791 if (failed(planBuffers(pools))) {
2792 InFlightDiagnostic error =
2794 ? bufferFailure.emitOpError(
2795 "could not place buffers: the search for which pools "
2796 "to make contiguous (one buffer, one BD per side) "
2799 <<
" placements tried in one group of neighbouring "
2802 if (std::optional<StringRef> fifo = bufferFailure.getFifoName())
2803 error <<
" for objectFIFO "
2804 << SymbolRefAttr::get(
2805 device.getSymNameAttr(),
2806 {FlatSymbolRefAttr::get(device.getContext(), *fifo)});
2807 SmallVector<Attribute> walked;
2808 for (Operation *op : turnWalked) {
2809 auto pool = cast<ObjectFifoPoolOp>(op);
2810 std::optional<StringRef> name = pool.getFifoName();
2811 if (pool.getContiguous() && name &&
2812 cast<TileLike>(pool.getTile().getDefiningOp()).isMemTile())
2813 walked.push_back(SymbolRefAttr::get(
2814 device.getSymNameAttr(),
2815 {FlatSymbolRefAttr::get(device.getContext(), *name)}));
2817 if (!walked.empty()) {
2818 Diagnostic ¬e = error.attachNote();
2820 llvm::interleaveComma(walked, note);
2822 }
else if (failed(planLocks(pools))) {
2823 if (lockSearchStopped) {
2824 InFlightDiagnostic error =
2825 lockSearchStoppedOn.emitOpError(
2826 "could not decide whether the locks fit: the lock packing "
2827 "search stopped after ")
2829 if (std::optional<StringRef> fifo = lockSearchStoppedOn.getFifoName())
2830 error <<
" for objectFIFO "
2831 << SymbolRefAttr::get(
2832 device.getSymNameAttr(),
2833 {FlatSymbolRefAttr::get(device.getContext(), *fifo)});
2834 }
else if (lockAccessFailure)
2835 lockAccessFailure->emitOpError(
"cannot access pool locks");
2837 lockFailure.getDefiningOp()->emitOpError(
2838 "could not place locks within tile lock capacity");
2841 (void)assignChannels(channels);
2843 "could not find a spill-aware allocation with size-first and "
2844 "demand-first packing and bounded local-pool retries; tile "
2845 "placement and buffer packing remain greedy");
2847 return signalPassFailure();
2849 for (ObjectFifoPoolOp pool : pools) {
2850 allocateBuffers(pool);
2851 allocateLocks(pool);
2853 for (TileOp tile : spillTiles)
2854 if (tile->use_empty())
2856 for (
auto endpoint : device.getOps<RouteEndpoint>())
2857 if (
auto it = channelAssignments.find(endpoint.getOperation());
2858 it != channelAssignments.end())
2859 endpoint.setRouteChannel(it->second);
2860 warnOvercommittedBDs();
2865 llvm::EquivalenceClasses<Operation *> matchingPools;
2866 DenseMap<Operation *, int64_t> descriptorCounts;
2867 for (
auto flow : device.getOps<RouteOp>()) {
2868 if (flow.getSources().size() != 1)
2870 ObjectFifoPoolOp first;
2871 for (
auto destName : flow.getDestinationNames()) {
2872 RouteEndpoint receiver = lookupEndpoint(destName);
2875 ? dyn_cast<ObjectFifoDmaEndpointOp>(receiver.getOperation())
2877 if (!dst || !dst.getOutOfOrder())
2879 ObjectFifoPoolOp pool = dst.getPoolOp();
2882 matchingPools.unionSets(first.getOperation(), pool.getOperation());
2883 descriptorCounts[pool] = dst.getNumDescriptors();
2886 int32_t nextTag = 0;
2887 DenseMap<Operation *, DenseI32ArrayAttr> tagsOfGroup;
2888 for (ObjectFifoPoolOp pool : pools) {
2889 auto member = matchingPools.findLeader(pool.getOperation());
2890 if (member == matchingPools.member_end())
2892 Operation *leader = *member;
2893 auto &tags = tagsOfGroup[leader];
2895 SmallVector<int32_t> values;
2896 for (int64_t slot = 0; slot < descriptorCounts.lookup(pool); ++slot)
2897 values.push_back(nextTag++);
2898 tags = builder.getDenseI32ArrayAttr(values);
2900 pool.setOutOfOrderTagsAttr(tags);
2905 for (
auto flow : device.getOps<RouteOp>()) {
2906 if (flow.getSources().size() != 1)
2908 RouteEndpoint sender = lookupEndpoint(*flow.getSourceNames().begin());
2910 ? dyn_cast<ObjectFifoDmaEndpointOp>(sender.getOperation())
2912 if (!src || !src.getOutOfOrder())
2914 for (
auto destName : flow.getDestinationNames()) {
2915 RouteEndpoint receiver = lookupEndpoint(destName);
2918 ? dyn_cast<ObjectFifoDmaEndpointOp>(receiver.getOperation())
2920 if (dst && dst.getOutOfOrder()) {
2921 src.setOutOfOrderTagsAttr(dst.getPoolOp().getOutOfOrderTagsAttr());
2927 if (failed(bindRearmTargets())) {
2928 return signalPassFailure();
2930 if (failed(lowerFlows()) || failed(resolveEndpointUses())) {
2931 return signalPassFailure();
2933 emitShimAllocations();
2934 for (Operation *flow : loweredFlows) {
2942std::unique_ptr<OperationPass<DeviceOp>>
2944 return std::make_unique<AIEObjectFifoAllocatePass>();
uint32_t getNumBDsForChannel(int col, int row, int channel, DMAChannelDir dir) const
virtual uint32_t getBdPoolId(int col, int row, int channel, DMAChannelDir dir) const
Return the pool channel in direction dir draws its BDs from.
The order one core moves objects through several pools, read off its program, so that one DMA channel...
mlir::LogicalResult read(llvm::ArrayRef< ObjectFifoCoreEndpointOp > ends, std::string &reason)
Reads the order off the program of the core working through ends, all draining (the channel fills the...
bool keepsUp(llvm::ArrayRef< int64_t > depths)
Whether a channel moving objects in turns() order forever, through pools of depths,...
llvm::ArrayRef< unsigned > turns() const
Indices into ends, one per object the channel moves in a period of the core's steady state.
Which DMA channels of each tile are already spoken for, so that a channel is handed out at most once ...
int getDMAChannelIndex(TileLike tile, DMAChannelDir dir, bool requiresAdjacentTileAccessChannels, mlir::Operation *owner=nullptr)
Next free channel of tile in dir, or -1 when the tile has none left.
static std::optional< unsigned > nextPoolToWalk(llvm::ArrayRef< BDPlanEnd > ends, llvm::ArrayRef< unsigned > poolOf, llvm::ArrayRef< BDWalkPool > pools, llvm::ArrayRef< bool > whole)
The walkable pool not yet whole to walk next: the deepest, then the one with the smallest objects,...
static std::optional< llvm::SmallVector< int > > planBDChannels(const AIETargetModel &target, int col, int row, llvm::ArrayRef< BDPlanEnd > ends, llvm::function_ref< bool(DMAChannelDir, int)> free, llvm::function_ref< int64_t(DMAChannelDir, int)> spent)
A channel of the tile at (col, row) for each of ends: its pinned one, else one free leaves that no ot...
mlir::Operation * getDMAChannelOwner(TileLike tile, DMAChannelDir dir, int channel)
Operation reserving or routing this channel; null if none.
bool isChannelFree(TileLike tile, DMAChannelDir dir, int channel)
Whether first-free assignment could hand out channel: nothing reserves it and no explicit flow routes...
static constexpr unsigned kMaxWalkPlacements
static int64_t countBDs(DMAStartOp start)
static llvm::SmallVector< BDGroup > bdGroups(const AIETargetModel &target, int col, int row, int numChannels)
static WalkChoice searchWalkProduct(llvm::ArrayRef< llvm::SmallVector< int64_t > > bytes, llvm::function_ref< bool(llvm::ArrayRef< unsigned >)> places, unsigned maxTries)
Tries the choices of one set per tile, bytes[tile] giving each of its sets' bytes walked whole,...
static llvm::SmallVector< mlir::Block * > chainOf(DMAStartOp start)
Blocks of the BD chain start begins, following next_bd.
static BDWalkSets walkSetsThatFit(const AIETargetModel &target, int col, int row, llvm::ArrayRef< BDPlanEnd > ends, llvm::ArrayRef< unsigned > poolOf, llvm::ArrayRef< BDWalkPool > pools, llvm::function_ref< bool(DMAChannelDir, int)> free, llvm::function_ref< int64_t(DMAChannelDir, int)> spent, unsigned maxSets=std::numeric_limits< unsigned >::max())
Every set of walkable pools whose walk lets planBDChannels fit ends (poolOf gives each end's pool),...
static int getDMAChannelLimit(TileLike tile, DMAChannelDir dir, bool requiresAdjacentTileAccessChannels)
Exclusive upper bound on channel indices eligible for this transfer.
std::pair< DMAChannelDir, int > BDUser
mlir::LogicalResult checkAIEStreamIndex(TileLike tile, DMAChannel chan, mlir::Operation *user, bool packet=false)
Claim a raw stream port for user, reporting on it when the port is taken; packet users may share it w...
int reservePinnedChannel(TileLike tile, DMAChannelDir dir, int channel, mlir::Operation *owner=nullptr, bool shareable=false)
Claim channel for (tile, dir) so first-free assignment cannot take it.
static llvm::SmallVector< mlir::Operation * > lockOwners(const AIETargetModel &target, ObjectFifoPoolOp pool)
The ops whose locks allocation and the SA each make for pool: with semaphore locks,...
static llvm::SmallVector< int > groupCounts(const AIETargetModel &target, int64_t depth, int owners)
The lock groups owners lock owners of a pool of depth objects take, by count.
static constexpr int64_t kPackBudget
Steps the exact packing of groups of different counts may take on each connected component.
unsigned addTile(Tile tile)
Assignment assign(llvm::ArrayRef< Group > groups, Memo *memo=nullptr, bool callerOrder=true)
Places groups first fit: with callerOrder, in order on each one's candidates, then in canonical order...
static bool dmaLocalOnly(AIETileType type)
Whether a DMA on a tile of type uses only its own tile's locks: every DMA does but a mem tile's.
bool reserve(unsigned tile, int count)
Takes count locks on tile, or returns false when it has too few left.
static bool reaches(const AIETargetModel &target, llvm::ArrayRef< TileID > user, llvm::ArrayRef< TileID > memory, bool localOnly)
Whether a tile at one of user reaches memory at one of memory; with localOnly, only at its own positi...
static Group group(int count, unsigned home, bool local, llvm::ArrayRef< unsigned > buffers, llvm::ArrayRef< User > users, llvm::ArrayRef< unsigned > ranked)
A group of count locks a pool's objects are counted by: on home, else, unless the pool must stay loca...
void reserve(unsigned tile, int64_t bytes, int count=1)
bool place(llvm::ArrayRef< Buffer > buffers)
Places buffers in order on top of what the tiles hold.
llvm::SmallVector< bool > weighed
Homes a spill from was weighed: aie-objectfifo-allocate gives their neighbours tile ops,...
bool fits(unsigned tile, int64_t bytes, int count=1) const
llvm::SmallVector< unsigned > chosen
int64_t used(unsigned tile, int64_t bytes=0, int count=0) const
The bytes tile spans with what it holds and count more of bytes.
The packet ids a device has already spoken for.
Shim endpoint lifetimes, including calls to self-contained runtime sequences.
static std::optional< End > endOf(DeviceOp device, mlir::StringAttr symbol)
The end a runtime sequence of device transfers through when it names symbol: a shim DMA route end,...
static mlir::StringAttr keyOf(RouteEndpointOp endpoint)
How ends and gates name a shim route end: by its objectFIFO, else by its own symbol.
static Gates provenGates(DeviceOp device, llvm::function_ref< mlir::StringAttr(RouteEndpointOp)> keyOf)
Each receiving end's gates, keyed by keyOf: the shim inputs whose consumption its progress proves,...
bool namesFifo(Operation *op, StringRef fifo, SymbolTableCollection &symbols)
void sortLargestBufferFirst(Range &&buffers, BytesFn bytes)
Buffers are laid out, and given a tile, largest buffer first: by the address layout below,...
llvm::SmallVector< ObjectFifoDmaEndpointOp > turnEndpoints(ObjectFifoDmaEndpointOp end)
llvm::SmallVector< unsigned > demandFirstOrder(llvm::ArrayRef< SpillPool > pools)
aie-objectfifo-allocate's demand-first packing order of pools, given in its size-first order,...
std::unique_ptr< mlir::OperationPass< DeviceOp > > createAIEObjectFifoAllocatePass()
mlir::Operation * lookupNamedOpIn(mlir::Operation *symbolTableOp, mlir::StringAttr name)
llvm::SmallVector< TileID, 2 > memTileSpillNeighbours(const AIETargetModel &target, TileID home)
The tiles a mem tile buffer homed at home may spill to: those in its row home shares memory with,...
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
int64_t turnPasses(llvm::ArrayRef< std::pair< int64_t, int64_t > > ends)
mlir::Operation * lookupNamedOp(mlir::Operation *from, mlir::StringAttr name)
constexpr llvm::StringLiteral kTurnWalkedNote
The note on it naming, as its symbol arguments, the mem tile pools channel turns walked whole: one bu...
constexpr llvm::StringLiteral kNoBufferRoom
How --aie-objectfifo-allocate says a pool's buffers fit no memory its users reach; the diagnostic's s...
llvm::SmallVector< unsigned > memTileSpillComponents(llvm::ArrayRef< TileID > homes, llvm::function_ref< llvm::SmallVector< TileID, 2 >(TileID)> neighboursOf)
For each of homes, the index of its component: homes whose buffers may spill to a tile in common,...
llvm::SmallVector< BDUser > users
walkSetsThatFit's result; channelShort when the ends do not fit the tile's channels even taking no BD...
llvm::SmallVector< int64_t > bytes
The bytes each set walks whole.
llvm::SmallVector< llvm::SmallVector< unsigned > > sets
One walkSetsThatFit set per mem tile of a spill component (memTileSpillComponents),...
std::optional< size_t > failed
The first group no assignment finds room for: first fit's miss, or, after packing or matching run,...
llvm::SmallVector< std::optional< unsigned > > tiles
bool stopped
The exact packing ran out of kPackBudget steps before it decided.
bool reachable
Some candidate every user reaches.
std::optional< unsigned > full
The last such candidate, when all were full.
How one shim tile's unpinned ends in one direction share channels, as objectFIFO allocation shares th...
llvm::SmallVector< llvm::SmallVector< unsigned > > groups
The other ends, in groups taking one channel each.
llvm::SmallVector< std::optional< unsigned > > sharedChannel
Per end, the index of the shared channel it takes, if any.
void link(mlir::Operation *from, mlir::Operation *to, llvm::StringRef label)
Link from to to under label, and to back to from.
llvm::SmallVector< mlir::Operation * > nodes
std::string & add(mlir::Operation *op)
Add op as a node whose features are its name and attributes, symbol names and references left out.
llvm::DenseMap< mlir::Operation *, unsigned > rank() const
Rank the nodes by their features and then, a round at a time until no class splits,...
llvm::DenseMap< mlir::Operation *, std::string > features
What each node is, before anything it links to is considered.