MLIR-AIE 1.4.6.dev
AIEObjectFifoAllocate.cpp
Go to the documentation of this file.
1//===- AIEObjectFifoAllocate.cpp --------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
20
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"
29
30#include <map>
31#include <memory>
32#include <set>
33
34#define DEBUG_TYPE "aie-objectfifo-allocate"
35
36using namespace mlir;
37using namespace xilinx;
38using namespace xilinx::AIE;
39
40namespace xilinx::AIE {
41#define GEN_PASS_DEF_AIEOBJECTFIFOALLOCATE
42#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
43} // namespace xilinx::AIE
44
45namespace {
46
47struct AIEObjectFifoAllocatePass
48 : public xilinx::AIE::impl::AIEObjectFifoAllocateBase<
49 AIEObjectFifoAllocatePass> {
50 using Base::Base;
51
52 DeviceOp device;
53 OpBuilder builder{static_cast<MLIRContext *>(nullptr)};
54 /// The last buffer or lock this pass placed on each tile.
55 DenseMap<Value, Operation *> lastPlaced;
56 /// Which pools get locks, and the resets re-arming each fifo.
57 std::shared_ptr<PoolLocks> poolLocks;
58 /// Flows already lowered. A route endpoint reads its direction off the
59 /// flow naming it, so these outlive the walk that replaces them.
60 SmallVector<Operation *> loweredFlows;
61 /// The flows each route endpoint is the source of, by its symbol name,
62 /// gathered before any flow is lowered.
63 DenseMap<StringAttr, SmallVector<RouteOp>> sourcedFlows;
64 llvm::MapVector<ObjectFifoDmaEndpointOp, llvm::StringMap<PacketInfoAttr>>
65 dispatchHeaders;
66 /// Ends that take another end's channel, by the end they take it from:
67 /// shim ends never in flight together, and ends taking turns.
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;
76 /// What runs on each channel the design programs itself, by the
77 /// `aie.route_endpoint` naming it: dma_starts in its tile's DMA program and
78 /// tasks the runtime sequence configures for it.
79 DenseMap<Operation *, SmallVector<DMAStartOp>> endpointStarts;
80 DenseMap<Operation *, SmallVector<AIEX::DMAConfigureTaskForOp>> endpointTasks;
81 /// BD ids DMA programs and pinned runtime ids hold before objectFIFOs take
82 /// theirs. Channels are chosen from these and the endpoints' own chains
83 /// alone, so an image built for one runtime sequence serves another's
84 /// instruction stream.
85 DMAChannelAnalysis::TakenBDs takenBDs;
86 /// BDs by placed (col, row, direction, channel).
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};
91 }
92 /// The most unpinned BDs one task the runtime sequence configures on each
93 /// channel by index holds.
94 BDDemand taskBDs;
95 /// The BDs every channel the last assignment handed out needs at once,
96 /// runtime tasks included.
97 BDDemand channelDemand;
98 /// Where each tile, pool, endpoint and route falls in an order taken from
99 /// the design's structure alone, which settles the choices op order would.
100 DenseMap<Operation *, unsigned> structuralRank;
101 RouteEndpoint channelFailure;
102 /// Whether channelFailure's channel has too few BD ids left, rather than no
103 /// channel being free.
104 bool bdShortfall = false;
105 /// Mem tiles once short of BD ids, whose ends since take their channels
106 /// from planBDChannels.
107 llvm::SetVector<Operation *> bdPlanned;
108 /// Pools planTurnSharing walked whole (some walks are undone later).
109 llvm::SetVector<Operation *> turnWalked;
110 /// hostMovesFirst's answer, by fifo: the runtime sequences it walks never
111 /// change once this pass starts.
112 DenseMap<StringAttr, bool> hostMovesFirstCache;
113 /// The pool the buffer search could not place with the fewest left
114 /// unplaced, i.e. where it got furthest.
115 ObjectFifoPoolOp bufferFailure;
116 /// Neighbours made for a spill planBuffers weighed. The ones no buffer ends
117 /// up on are erased once allocation is done.
118 SmallVector<TileOp> spillTiles;
119 Value lockFailure;
120 Operation *lockAccessFailure = nullptr;
121 /// The pool whose lock group the packing search was stopped on.
122 ObjectFifoPoolOp lockSearchStoppedOn;
123 /// See LockPlan::groupCounts for what this changes.
124 bool semaphoreLocks = false;
125 bool walkSearchStopped = false;
126 bool lockSearchStopped = false;
127
128 bool sameTile(Value a, Value b) {
129 if (a == b)
130 return true;
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;
136 }
137
138 /// The mem tiles a buffer search weighs, as MemTileSpillSearch indices: one
139 /// per placed position, however many ops name it, with the positions a
140 /// placed TileOp may spill to, and one per unplaced tile.
141 DenseMap<TileID, unsigned> memTilePositions;
142 DenseMap<Operation *, unsigned> unplacedMemTiles;
143 SmallVector<std::optional<TileID>> memTileAt;
144
145 std::optional<unsigned> memTileIndex(Value tile) {
146 auto like = cast<TileLike>(tile.getDefiningOp());
147 if (!like.isMemTile())
148 return std::nullopt;
149 auto col = like.tryGetCol(), row = like.tryGetRow();
150 if (col && row)
151 return memTilePositions.lookup({*col, *row});
152 return unplacedMemTiles.lookup(like);
153 }
154
155 /// The search over the device's mem tiles, holding their existing buffers.
156 MemTileSpillSearch memTileSearch() {
157 const auto &target = device.getTargetModel();
158 memTilePositions.clear();
159 unplacedMemTiles.clear();
160 memTileAt.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);
166 };
167 for (auto tile : device.getOps<TileLike>()) {
168 if (!tile.isMemTile())
169 continue;
170 auto col = tile.tryGetCol(), row = tile.tryGetRow();
171 if (!col || !row) {
172 unplacedMemTiles[tile] = add(std::nullopt);
173 continue;
174 }
175 TileID at{*col, *row};
176 if (!memTilePositions.count(at))
177 memTilePositions[at] = add(at);
178 if (isa<TileOp>(tile.getOperation()))
179 for (TileID neighbour : memTileSpillNeighbours(target, at))
180 if (!memTilePositions.count(neighbour))
181 memTilePositions[neighbour] = add(neighbour);
182 }
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);
190 }
191
192 LogicalResult collectFixedMemory() {
193 MemTileSpillSearch search = memTileSearch();
194 for (auto tile : device.getOps<TileLike>()) {
195 std::optional<unsigned> index = memTileIndex(tile->getResult(0));
196 if (!index)
197 continue;
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
203 << " bytes";
204 }
205 return success();
206 }
207
208 /// Coordinates `tile` may take: its own once placed, else every position
209 /// of its type in the rows and columns it is pinned to.
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)
216 continue;
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});
221 }
222 }
223 return compatible;
224 }
225
226 bool canAccess(Value user, Value memory, bool localOnly = false) {
227 if (user == memory)
228 return true;
229 auto memoryTile = dyn_cast<TileLike>(memory.getDefiningOp());
230 return memoryTile &&
231 canAccess(user, compatiblePositions(memoryTile), localOnly);
232 }
233
234 /// Before placement, defer only accesses that some compatible physical
235 /// positions could satisfy. Known coordinates can already disprove affinity.
236 bool canAccess(Value user, ArrayRef<TileID> memoryPositions,
237 bool localOnly = false) {
238 auto userTile = dyn_cast<TileLike>(user.getDefiningOp());
239 return userTile && LockPlan::reaches(device.getTargetModel(),
240 compatiblePositions(userTile),
241 memoryPositions, localOnly);
242 }
243
244 Value lockPlacement(ObjectFifoPoolOp pool, Operation *group) {
245 if (Value placed = lockPlacements.lookup(group))
246 return placed;
247 Value local = localPools.lookup(pool);
248 return local ? local : pool.getTile();
249 }
250
251 /// A contiguous pool's objects are one buffer; others have one per object.
252 static int bufferCount(ObjectFifoPoolOp pool) {
253 return pool.getContiguous() ? 1 : pool.getDepth();
254 }
255 static int64_t bufferBytes(ObjectFifoPoolOp pool) {
256 return pool.getObjectSizeInBytes() * pool.getObjectsPerBuffer();
257 }
258
259 /// FIXME: choosing which tile a buffer lives on is the buffer allocator's
260 /// job, not this pass's; --aie-assign-buffer-addresses should instead be
261 /// free to move buffers between tiles that share a memory module.
262 ///
263 /// Reserve mandatory-local objects before any other pool can spill into
264 /// their memory. Existing buffers are fixed and counted by identity, not by
265 /// how many pools or endpoints reference them. The others' mem tile buffers
266 /// go where MemTileSpillSearch puts them, in pool order.
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); });
274 };
275 for (auto pool : pools) {
276 if (!localPools.contains(pool))
277 continue;
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;
285 return failure();
286 }
287 if (index)
288 search.reserve(*index, size, count);
289 }
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;
301 return failure();
302 }
303 bufferPlacements[pool].push_back(tile);
304 }
305 continue;
306 }
307 if (pool.getTileLike().isShimTile())
308 continue;
309 if (localPools.contains(pool)) {
310 bufferPlacements[pool].append(bufferCount(pool),
311 localPools.lookup(pool));
312 continue;
313 }
314 Value home = pool.getTile();
315 bool atHome = reachable(pool, home);
316 std::optional<unsigned> index = memTileIndex(home);
317 if (!index) {
318 if (!atHome) {
319 bufferFailure = pool;
320 return failure();
321 }
322 bufferPlacements[pool].append(bufferCount(pool), home);
323 continue;
324 }
325 // Which tiles neighbor an unplaced one is not yet known, so its buffers
326 // stay at home.
327 SmallVector<unsigned, 2> neighbours;
328 if (auto homeOp = dyn_cast<TileOp>(home.getDefiningOp()))
329 for (TileID at :
330 memTileSpillNeighbours(target, {homeOp.getCol(), homeOp.getRow()}))
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);
336 }
337 }
338 bool placed = search.place(buffers);
339 // A spill weighed from a placed home makes its neighbors' tile ops; the
340 // ones no buffer ends up on are erased once allocation is done.
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])
344 continue;
345 for (int col : {homeOp.getCol() - 1, homeOp.getCol() + 1})
346 if (col >= 0 && col < target.columns())
347 spillTile(col, homeOp.getRow(), pool.getLoc());
348 }
349 if (!placed) {
350 bufferFailure = owners[search.failed];
351 return failure();
352 }
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())
358 .getResult());
359 return success();
360 }
361
362 /// The tile op at (`col`, `row`), made if the device has none.
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;
366 });
367 TileOp tile = TileOp::getOrCreate(builder, device, col, row, loc);
368 if (!declared)
369 spillTiles.push_back(tile);
370 return tile;
371 }
372
373 /// Buffers and locks sit directly below the tile whose memory holds them,
374 /// after whatever this pass has already put there.
375 void setInsertionPointOn(Value tile) {
376 Operation *after = lastPlaced.lookup(tile);
377 if (!after) {
378 after = tile.getDefiningOp();
379 }
380 if (after) {
381 builder.setInsertionPointAfter(after);
382 } else {
383 builder.setInsertionPointToStart(device.getBody());
384 }
385 }
386
387 void allocateBuffers(ObjectFifoPoolOp pool) {
388 if (pool.getBuffers()) {
389 return;
390 }
391 TileLike home = pool.getTileLike();
392 if (home.isShimTile()) {
393 return;
394 }
395
396 ArrayRef<Attribute> initValues;
397 if (auto initAttr = pool.getInitValues()) {
398 initValues = initAttr->getValue();
399 }
400 int filled = initValues.size();
401 StringRef base = pool.getBaseName();
402
403 SmallVector<Attribute> names;
404 MemRefType type = pool.getElemType();
405 ElementsAttr zeros;
406 if (pool.getContiguous()) {
407 int64_t objectElements = type.getNumElements();
408 type = MemRefType::get({pool.getObjectsPerBuffer() * objectElements},
409 type.getElementType());
410 auto tensor =
411 RankedTensorType::get(type.getShape(), type.getElementType());
412 Attribute zero = builder.getZeroAttr(type.getElementType());
413 if (filled) {
414 // The one buffer starts as its objects do, in order, between its zero
415 // objects; objects with no initial contents start zero.
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++) {
420 if (i < filled)
421 llvm::append_range(
422 values,
423 cast<DenseElementsAttr>(initValues[i]).getValues<Attribute>());
424 else
425 values.append(objectElements, zero);
426 }
427 values.append((zeroObjects ? (*zeroObjects)[1] : 0) * objectElements,
428 zero);
429 zeros = DenseElementsAttr::get(tensor, values);
430 } else if (pool.getZeroObjects()) {
431 zeros = DenseElementsAttr::get(tensor, zero);
432 }
433 }
434 // Initial contents may fill only the first objects of a deeper pool.
435 for (int i = 0; i < bufferCount(pool); i++) {
436 ElementsAttr init = !pool.getContiguous() && i < filled
437 ? cast<ElementsAttr>(initValues[i])
438 : zeros;
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),
444 /*address=*/nullptr, init,
445 /*mem_bank=*/nullptr, /*core_data=*/false);
446 names.push_back(FlatSymbolRefAttr::get(builder.getContext(), name));
447 }
448 pool.setBuffersAttr(builder.getArrayAttr(names));
449 }
450
451 LockOp createLock(ObjectFifoPoolOp pool, Value tile, StringRef name,
452 int value) {
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));
458 return lock;
459 }
460
461 LogicalResult planLocks(ArrayRef<ObjectFifoPoolOp> pools) {
462 lockFailure = {};
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());
471 if (fresh) {
472 auto like = cast<TileLike>(tile.getDefiningOp());
473 auto col = like.tryGetCol(), row = like.tryGetRow();
474 plan.addTile(
475 {compatiblePositions(like),
476 col && row ? std::optional<TileID>({*col, *row}) : std::nullopt});
477 tileValues.push_back(tile);
478 }
479 return at->second;
480 };
481 for (auto lock : device.getOps<LockOp>())
482 if (!plan.reserve(indexOf(lock.getTile()), 1)) {
483 lockFailure = lock.getTile();
484 return failure();
485 }
486 // Neighbours created to weigh a spill take no locks: the placers count
487 // locks only on the tiles that exist before allocation.
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;
494 });
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);
510 users.push_back(
511 {indexOf(tile),
512 isa<ObjectFifoDmaEndpointOp>(user) &&
514 cast<TileLike>(tile.getDefiningOp()).getTileType())});
515 }
516 groups.push_back(
517 LockPlan::group(count, indexOf(lockPlacement(pool, group)),
518 localPools.contains(pool), buffers, users, ranked));
519 groupOps.push_back(group);
520 groupPools.push_back(pool);
521 };
522 for (auto pool : pools) {
523 if (!poolLocks->needsLocks(pool))
524 continue;
525 SmallVector<Operation *> owners =
526 LockPlan::lockOwners(device.getTargetModel(), pool);
527 for (auto [owner, count] : llvm::zip_equal(
528 owners, LockPlan::groupCounts(device.getTargetModel(),
529 pool.getDepth(), owners.size())))
530 add(pool, owner, count);
531 }
532 LockPlan::Assignment assignment = plan.assign(groups);
533 if (assignment.failed) {
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();
541 return failure();
542 }
543 for (auto [group, tile] : llvm::zip(groupOps, assignment.tiles))
544 if (tile)
545 lockPlacements[group] = tileValues[*tile];
546 auto check = [&](auto endpoint) {
547 for (Value tile : endpointLockTiles(endpoint)) {
548 if (!canAccessLocks(endpoint, tile)) {
549 lockAccessFailure = endpoint;
550 return failure();
551 }
552 }
553 return success();
554 };
555 for (auto endpoint : device.getOps<ObjectFifoCoreEndpointOp>())
556 if (failed(check(endpoint)))
557 return failure();
558 for (auto endpoint : device.getOps<ObjectFifoDmaEndpointOp>())
559 if (failed(check(endpoint)))
560 return failure();
561 return success();
562 }
563
564 void allocateLocks(ObjectFifoPoolOp pool) {
565 if (!poolLocks->needsLocks(pool))
566 return;
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);
572
573 if (!semaphoreLocks) {
574 if (pool.getLocks()) {
575 return;
576 }
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));
582 }
583 pool.setLocksAttr(builder.getArrayAttr(names));
584 return;
585 }
586
587 for (auto [index, segment] : llvm::enumerate(pool.getSegmentOps())) {
588 if (segment.getProduceLock() && segment.getConsumeLock()) {
589 continue;
590 }
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));
600 }
601 }
602
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, /*localOnly=*/true);
609 return canAccess(user, tile);
610 }
611
612 template <typename EndpointOp>
613 void collectLockUsers(EndpointOp endpoint) {
614 auto pool = endpoint.getPoolOp();
615 if (!semaphoreLocks) {
616 lockUsers[pool].push_back(endpoint);
617 return;
618 }
619 for (auto segment : endpoint.getSelectedSegments())
620 lockUsers[segment].push_back(endpoint);
621 }
622
623 /// Predict the locks core and DMA lowering will use, including hand-written
624 /// locks and those allocation will create. Only selected segments matter.
625 template <typename EndpointOp>
626 SmallVector<Value> endpointLockTiles(EndpointOp endpoint) {
627 SmallVector<Value> tiles;
628 auto pool = endpoint.getPoolOp();
629 if (pool.getDepth() == 0)
630 return tiles;
631 if (!semaphoreLocks) {
632 if (poolLocks->needsLocks(pool) && !pool.getLocks())
633 tiles.push_back(lockPlacement(pool, pool));
634 else
635 for (auto lock : pool.getLockOps())
636 tiles.push_back(lock.getTile());
637 return tiles;
638 }
639 for (auto segment : endpoint.getSelectedSegments()) {
640 if (poolLocks->needsLocks(pool) &&
641 !(segment.getProduceLock() && segment.getConsumeLock())) {
642 tiles.push_back(lockPlacement(pool, segment));
643 continue;
644 }
645 for (auto name :
646 {segment.getProduceLockAttr(), segment.getConsumeLockAttr()})
647 if (name)
648 if (auto lock = lookupNamedOp<LockOp>(device, name.getAttr()))
649 tiles.push_back(lock.getTile());
650 }
651 return tiles;
652 }
653
654 /// Both buffers and locks must be local to use the local-only channels.
655 /// Distinct unresolved tiles may be neighbors after placement, so they
656 /// cannot be assumed local when assigning a placed endpoint's channels.
657 /// An end whose channel others take turns on reaches what they reach too.
658 bool reachesAdjacentTile(RouteEndpoint endpoint) {
659 if (ownReachesAdjacentTile(endpoint))
660 return true;
661 for (auto [sharer, owner] : channelSharers)
662 if (owner == endpoint.getOperation() &&
663 ownReachesAdjacentTile(cast<RouteEndpoint>(sharer)))
664 return true;
665 return false;
666 }
667
668 /// Whether `endpoint`'s own pool, locks or DMA program reach another tile,
669 /// whatever ends take turns on its channel.
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()) {
675 return false;
676 }
677 ObjectFifoPoolOp pool = dma.getPoolOp();
678 auto remote = [&](Value tile) {
679 return tile && !sameTile(tile, endpoint.getTile());
680 };
681 return pool && (llvm::any_of(bufferPlacements[pool], remote) ||
682 llvm::any_of(endpointLockTiles(dma), remote));
683 }
684
685 TileLike tileOf(RouteEndpoint endpoint) {
686 return dyn_cast<TileLike>(endpoint.getTile().getDefiningOp());
687 }
688
689 /// A DMA channel the design programs itself, by naming this endpoint from a
690 /// dma_start or a runtime task, rather than one an objectFIFO lowers to.
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();
695 }
696
697 static int64_t countBDs(Region &taskBody) {
698 int64_t bds = 0;
699 taskBody.walk([&](DMABDOp) { bds++; });
700 return bds;
701 }
702
703 /// BDs a program-owned endpoint's static chains hold; they stay configured.
704 int64_t endpointBDs(Operation *endpoint) {
705 int64_t bds = 0;
706 for (DMAStartOp start : endpointStarts.lookup(endpoint))
707 bds += DMAChannelAnalysis::countBDs(start);
708 return bds;
709 }
710
711 /// BDs `endpoint` needs: an objectFIFO's DMA count, a program-owned
712 /// endpoint's static chains, or none.
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());
718 return 0;
719 }
720
721 /// BDs the largest runtime task on a program-owned endpoint needs.
722 int64_t endpointTaskBDs(Operation *endpoint) {
723 int64_t largest = 0;
724 for (auto task : endpointTasks.lookup(endpoint))
725 largest = std::max(largest, countBDs(task.getBody()));
726 return largest;
727 }
728
729 /// Whether a program-owned MemTile channel's BDs touch a neighbor's buffers
730 /// or locks, which only the lower channels can.
731 bool programReachesAdjacentTile(RouteEndpointOp endpoint) {
732 if (!endpoint.getTileLike().isMemTile())
733 return false;
734 auto remote = [&](Operation *op) {
735 Value tile;
736 if (auto bd = dyn_cast<DMABDOp>(op)) {
737 if (auto buffer =
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();
743 }
744 return tile && !sameTile(tile, endpoint.getTile());
745 };
746 for (DMAStartOp start : endpointStarts.lookup(endpoint))
747 for (Block *block : DMAChannelAnalysis::chainOf(start))
748 if (llvm::any_of(block->getOperations(),
749 [&](Operation &op) { return remote(&op); }))
750 return true;
751 for (auto task : endpointTasks.lookup(endpoint)) {
752 bool reaches = false;
753 task.getBody().walk([&](Operation *op) { reaches |= remote(op); });
754 if (reaches)
755 return true;
756 }
757 return false;
758 }
759
760 /// Find what programs each endpoint-named channel, and the BDs already spoken
761 /// for on channels named by index.
762 void collectChannelPrograms() {
763 endpointStarts.clear();
764 endpointTasks.clear();
765 taskBDs.clear();
766 takenBDs = DMAChannelAnalysis::TakenBDs(device);
767 const AIETargetModel &target = device.getTargetModel();
768 // Channels whose directions share a BD pool (pre-AIE4) use one key.
769 auto key =
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();
774 if (!col || !row)
775 return std::nullopt;
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);
781 };
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)) {
794 if (auto at =
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);
800 }
801 }
802 });
803 }
804
805 /// Rank tiles, pools, endpoints and routes by their attributes and then, a
806 /// round at a time until no class splits, by the ranks of what they connect
807 /// to. Symbol names and op order play no part, so a permuted or renamed
808 /// design ranks alike, and ops still tied cannot be told apart.
809 void rankStructurally() {
810 StructuralGraph graph;
811 // A placed tile is one node however many ops name it.
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();
816 if (!col || !row) {
817 graph.add(tileNode[tile] = tile);
818 continue;
819 }
820 auto [it, first] = placed.try_emplace({*col, *row}, tile);
821 tileNode[tile] = it->second;
822 if (first) {
823 graph.nodes.push_back(tile);
824 llvm::raw_string_ostream(graph.features[tile])
825 << "tile " << *col << ' ' << *row << ' '
826 << stringifyAIETileType(tile.getTileType());
827 }
828 }
829 auto link = [&](Operation *from, Operation *to, StringRef label) {
830 if (Operation *tile = tileNode.lookup(to))
831 to = tile;
832 graph.link(from, to, label);
833 };
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");
839 }
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");
848 }
849 for (auto endpoint : device.getOps<RouteEndpoint>()) {
850 llvm::raw_string_ostream os(graph.add(endpoint));
851 if (auto dma =
852 dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation())) {
853 for (auto segment : dma.getSelectedSegments())
854 os << " @" << segment.getOffset();
855 link(endpoint, dma.getPoolOp(), "pool");
856 }
857 link(endpoint, endpoint.getTile().getDefiningOp(), "tile");
858 }
859 for (auto route : device.getOps<RouteOp>()) {
860 graph.add(route);
861 for (StringRef source : route.getSourceNames())
862 link(route, lookupEndpoint(source), "source");
863 for (StringRef dest : route.getDestinationNames())
864 link(route, lookupEndpoint(dest), "dest");
865 }
866 DenseMap<Operation *, unsigned> rank = graph.rank();
867 // Ops still tied fall to the order each core first acquires its ends in,
868 // the core's program order: ranking again from the ranks found, with the
869 // cores linked in, splits only ties.
870 for (Operation *node : graph.nodes)
871 graph.features[node] = llvm::formatv("{0,10}", rank[node]).str();
872 for (auto core : device.getOps<CoreOp>()) {
873 graph.add(core);
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());
881 });
882 }
883 rank = graph.rank();
884 for (auto [tile, node] : tileNode)
885 rank[tile] = rank[node];
886 structuralRank = std::move(rank);
887 }
888
889 /// BDs left for `channel` in `dir` after `demand`, over its whole BD pool.
890 /// Negative when overcommitted; 0 for a channel the tile lacks.
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 =
897 DMAChannelAnalysis::bdGroups(target, col, row, numChannels);
898 DMAChannelAnalysis::BDUser user{dir, channel};
899 auto *group =
900 llvm::find_if(groups, [&](const DMAChannelAnalysis::BDGroup &g) {
901 return llvm::is_contained(g.users, user);
902 });
903 if (group == groups.end())
904 return 0;
905 int64_t room = group->size;
906 for (auto [otherDir, other] : group->users)
907 if (auto it = demand.find(demandKey(col, row, otherDir, other));
908 it != demand.end())
909 room -= it->second;
910 return room;
911 }
912
913 /// `endpoint`'s BD plan: its direction, BD count, channel limit (with
914 /// `adjacent` access, where its tile allows it), and its pinned channel,
915 /// kept only when `keepPin`.
916 DMAChannelAnalysis::BDPlanEnd planEnd(RouteEndpoint endpoint, bool adjacent,
917 bool keepPin) {
918 DMAChannelDir dir = endpoint.getRouteDirection();
919 return {
920 dir, bdsOf(endpoint),
921 DMAChannelAnalysis::getDMAChannelLimit(tileOf(endpoint), dir, adjacent),
922 keepPin ? endpoint.getRouteChannel() : std::nullopt};
923 }
924
925 /// On a tile whose BD ids are split between channels, the free channel whose
926 /// BDs have the most room left once every channel sharing them has its
927 /// demand; ties, and tiles without such a split, go to the lowest index.
928 /// Falls back to first-free where coordinates are unknown.
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();
934 if (!col || !row)
935 return channels.getDMAChannelIndex(tile, dir, adjacent,
936 endpoint.getOperation());
937 int best = -1;
938 int64_t bestRoom = 0;
939 int limit = DMAChannelAnalysis::getDMAChannelLimit(tile, dir, adjacent);
940 for (int channel = 0; channel < limit; ++channel) {
941 if (!channels.isChannelFree(tile, dir, channel))
942 continue;
943 int64_t room = bdRoom(tile, *col, *row, dir, channel, demand);
944 if (best < 0 || room > bestRoom) {
945 best = channel;
946 bestRoom = room;
947 }
948 }
949 if (best < 0)
950 return -1;
951 return channels.reservePinnedChannel(tile, dir, best,
952 endpoint.getOperation());
953 }
954
955 void noteChannelOwner(InFlightDiagnostic &diag, Operation *owner,
956 std::optional<int> channel = std::nullopt) {
957 auto &note = 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";
964 if (channel)
965 note << "; occupies channel " << *channel;
966 } else if (channel) {
967 note << "pre-existing " << owner->getName() << " reserves DMA channel "
968 << *channel;
969 }
970 }
971
972 // The endpoints of the routes that switch packets.
973 DenseSet<Operation *> packetEndpoints() {
974 DenseSet<Operation *> endpoints;
975 for (auto flow : device.getOps<RouteOp>()) {
976 if (!flow.getPacket())
977 continue;
978 for (StringRef source : flow.getSourceNames())
979 endpoints.insert(lookupEndpoint(source).getOperation());
980 for (StringRef dest : flow.getDestinationNames())
981 endpoints.insert(lookupEndpoint(dest).getOperation());
982 }
983 return endpoints;
984 }
985
986 // No allocation can move a stream port the design names, so a clash fails
987 // the pass before the search rather than surfacing inside it.
988 LogicalResult checkStreamPorts() {
989 DMAChannelAnalysis channels(device);
990 DenseSet<Operation *> packetEndpoints = this->packetEndpoints();
991 bool clash = false;
992 for (auto endpoint : device.getOps<RouteEndpoint>()) {
993 if (endpoint.getRouteBundle() != WireBundle::Core)
994 continue;
995 std::optional<int> channel = endpoint.getRouteChannel();
996 if (!channel)
997 return endpoint->emitOpError("a stream port names its own channel");
998 clash |= failed(channels.checkAIEStreamIndex(
999 tileOf(endpoint), {endpoint.getRouteDirection(), *channel},
1000 endpoint.getOperation(),
1001 packetEndpoints.contains(endpoint.getOperation())));
1002 }
1003 return failure(clash);
1004 }
1005
1006 /// Whether `endpoint` draws a DMA channel of its own, rather than being a
1007 /// core's stream port or sharing another end's channel.
1008 bool drawsOwnChannel(RouteEndpoint endpoint) {
1009 return endpoint.getRouteBundle() != WireBundle::Core &&
1010 !channelSharers.contains(endpoint.getOperation()) &&
1011 !allocationSharers.contains(endpoint.getOperation());
1012 }
1013
1014 /// Whether this endpoint can share its pinned channel without a cyclic
1015 /// DMA program monopolizing it.
1016 bool sharesPinnedChannel(RouteEndpoint endpoint, DMAChannelDir dir) {
1017 // An out-of-order receiver takes each object into the buffer its header
1018 // names, so its channel keeps no order its fifos would have to agree on.
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))
1025 return false;
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();
1031 }))
1032 continue;
1033 if (!flow.getPacket())
1034 return false;
1035 hasPacketRoute = true;
1036 }
1037 return hasPacketRoute;
1038 }
1039
1040 LogicalResult assignChannels(DMAChannelAnalysis &channels,
1041 bool diagnose = true) {
1042 channelAssignments.clear();
1043 channelFailure = nullptr;
1044 bdShortfall = false;
1045 SmallVector<RouteEndpoint> pending;
1046 // BDs per placed (col, row, channel) as channels are handed out, for
1047 // choosing among a tile's channels by the BD ids they can use.
1048 BDDemand demand;
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();
1055 if (col && row)
1056 demand[demandKey(*col, *row, endpoint.getRouteDirection(), channel)] +=
1057 bdsOf(endpoint);
1058 };
1059 for (auto endpoint : device.getOps<RouteEndpoint>()) {
1060 DMAChannelDir dir = endpoint.getRouteDirection();
1061 std::optional<int> channel = endpoint.getRouteChannel();
1062 if (!drawsOwnChannel(endpoint))
1063 continue;
1064
1065 if (channel) {
1066 if (reachesAdjacentTile(endpoint) &&
1067 *channel >= DMAChannelAnalysis::getDMAChannelLimit(tileOf(endpoint),
1068 dir, true)) {
1069 channelFailure = endpoint;
1070 if (!diagnose)
1071 return failure();
1072 return endpoint->emitOpError("pinned ")
1073 << stringifyDMAChannelDir(dir) << " DMA channel " << *channel
1074 << " cannot access adjacent MemTile buffers or locks";
1075 }
1076 if (channels.reservePinnedChannel(
1077 tileOf(endpoint), dir, *channel, endpoint.getOperation(),
1078 sharesPinnedChannel(endpoint, dir)) < 0) {
1079 if (!diagnose)
1080 return failure();
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 =
1085 channels.getDMAChannelOwner(tileOf(endpoint), dir, *channel))
1086 noteChannelOwner(diag, owner, channel);
1087 return failure();
1088 }
1089 noteDemand(endpoint, *channel);
1090 continue;
1091 }
1092 pending.push_back(endpoint);
1093 }
1094
1095 // A mem tile's pinned ends must fit the BD ids of the channels they pin,
1096 // as a plan of the tile's BD ids weighs every end.
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);
1104 }
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, /*adjacent=*/false, /*keepPin=*/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;
1118 }))
1119 continue;
1120 int pinnedCol = col, pinnedRow = row;
1121 auto roomOf = [&](RouteEndpoint endpoint) {
1122 return bdRoom(tileOf(endpoint), pinnedCol, pinnedRow,
1123 endpoint.getRouteDirection(), *endpoint.getRouteChannel(),
1124 demand);
1125 };
1126 // The ends short of BD ids, the most demanding first.
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));
1136 });
1137 RouteEndpoint deepest = starved.front();
1138 channelFailure = deepest;
1139 bdShortfall = true;
1140 if (!diagnose)
1141 return failure();
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";
1155 return diag;
1156 }
1157
1158 // Endpoints reaching a spilled buffer draw from a restricted channel
1159 // range, so they are served before the unrestricted ones. Channels the
1160 // design programs itself come after the objectFIFOs', whose BDs they are
1161 // then chosen around, the most demanding first. The structural rank
1162 // settles the rest, so the order ops were written in never does.
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)
1172 return aAdjacent;
1173 bool aProgram = isProgramOwned(a), bProgram = isProgramOwned(b);
1174 if (aProgram != bProgram)
1175 return bProgram;
1176 int64_t aBDs = programBDs.lookup(a.getOperation());
1177 int64_t bBDs = programBDs.lookup(b.getOperation());
1178 if (aBDs != bBDs)
1179 return aBDs > bBDs;
1180 return structuralRank.lookup(a.getOperation()) <
1181 structuralRank.lookup(b.getOperation());
1182 });
1183
1184 // On a mem tile once short of BD ids, every end gets the channel a plan of
1185 // the tile's BD ids gives it, before any pool there is walked whole.
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();
1190 if (!col || !row)
1191 continue;
1192 SmallVector<RouteEndpoint> onTile;
1193 SmallVector<DMAChannelAnalysis::BDPlanEnd> ends, unweighted;
1194 for (RouteEndpoint endpoint : pending) {
1195 if (tileOf(endpoint).getOperation() != tileOp)
1196 continue;
1197 onTile.push_back(endpoint);
1198 ends.push_back(planEnd(endpoint, reachesAdjacentTile(endpoint),
1199 /*keepPin=*/false));
1200 DMAChannelAnalysis::BDPlanEnd &zeroed =
1201 unweighted.emplace_back(ends.back());
1202 zeroed.bds = 0;
1203 }
1204 auto free = [&](DMAChannelDir dir, int channel) {
1205 return channels.isChannelFree(tile, dir, channel);
1206 };
1207 const AIETargetModel &target = device.getTargetModel();
1208 std::optional<SmallVector<int>> plan = DMAChannelAnalysis::planBDChannels(
1209 target, *col, *row, ends, free, [&](DMAChannelDir dir, int channel) {
1210 return demand.lookup(demandKey(*col, *row, dir, channel));
1211 });
1212 if (plan) {
1213 for (auto [endpoint, channel] : llvm::zip_equal(onTile, *plan))
1214 planned[endpoint.getOperation()] = channel;
1215 continue;
1216 }
1217 // Fails even with zero BDs: a channel shortage, handled below.
1219 target, *col, *row, unweighted, free,
1220 [](DMAChannelDir, int) -> int64_t { return 0; }))
1221 continue;
1222 RouteEndpoint deepest =
1223 *llvm::max_element(onTile, [&](RouteEndpoint a, RouteEndpoint b) {
1224 return bdsOf(a) < bdsOf(b);
1225 });
1226 channelFailure = deepest;
1227 bdShortfall = true;
1228 if (!diagnose)
1229 return failure();
1230 int64_t total = 0;
1231 for (const DMAChannelAnalysis::BDPlanEnd &end : ends)
1232 total += end.bds;
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";
1237 }
1238
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()] =
1246 channels.reservePinnedChannel(tile, dir, it->second,
1247 endpoint.getOperation());
1248 noteDemand(endpoint, it->second);
1249 continue;
1250 }
1251 // An objectFIFO end takes the first free channel, unless that channel's
1252 // BD ids have too few left for it: then the one with the most left.
1253 bool roomy = true;
1254 auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation());
1255 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
1256 if (dma && col && row) {
1257 int limit = DMAChannelAnalysis::getDMAChannelLimit(tile, dir, adjacent);
1258 for (int free = 0; free < limit; ++free) {
1259 if (!channels.isChannelFree(tile, dir, free))
1260 continue;
1261 roomy =
1262 bdRoom(tile, *col, *row, dir, free, demand) >= dma.getNumBDs();
1263 break;
1264 }
1265 }
1266 int channel = isProgramOwned(endpoint) || !roomy
1267 ? chooseChannel(channels, endpoint, demand, adjacent)
1268 : channels.getDMAChannelIndex(tile, dir, 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;
1273 bdShortfall = true;
1274 if (!diagnose)
1275 return failure();
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";
1281 }
1282 if (channel < 0) {
1283 channelFailure = endpoint;
1284 if (!diagnose)
1285 return failure();
1286 int capacity =
1287 DMAChannelAnalysis::getDMAChannelLimit(tile, dir, adjacent);
1288 auto diag =
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 "
1294 << capacity;
1295 if (adjacent) {
1296 diag << " for adjacent MemTile access";
1297 }
1298 for (int i = 0; i < capacity; ++i)
1299 if (Operation *owner = channels.getDMAChannelOwner(tile, dir, i))
1300 noteChannelOwner(diag, owner, i);
1301 noteChannelOwner(diag, endpoint.getOperation());
1302 return failure();
1303 }
1304 channelAssignments[endpoint.getOperation()] = channel;
1305 noteDemand(endpoint, channel);
1306 }
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 &&
1312 channels.reservePinnedChannel(tileOf(end), alloc.getChannelDir(),
1313 channel, endpoint, true) < 0) {
1314 channelFailure = end;
1315 if (!diagnose)
1316 return failure();
1317 auto diag = endpoint->emitOpError("cannot share ");
1318 diag << stringifyDMAChannelDir(alloc.getChannelDir()) << " DMA channel "
1319 << channel << ": already in use or unavailable";
1320 if (Operation *owner = channels.getDMAChannelOwner(
1321 tileOf(end), alloc.getChannelDir(), channel))
1322 noteChannelOwner(diag, owner, channel);
1323 return failure();
1324 }
1325 channelAssignments[endpoint] = channel;
1326 noteDemand(end, channel);
1327 }
1328 for (auto [sharer, owner] : channelSharers)
1329 channelAssignments[sharer] = channelAssignments.lookup(owner);
1330 // Unpinned runtime BDs did not steer the choice, so the image serves any
1331 // runtime sequence pinning the same ids, but they hold BDs while they
1332 // run, which the overcommit warning counts.
1333 for (auto &[at, bds] : taskBDs)
1334 demand[at] += bds;
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());
1345 }
1346 channelDemand = std::move(demand);
1347 return success();
1348 }
1349
1350 /// Gives one more shim end of `exhausted` the channel of ends it is never in
1351 /// flight with, in the order ShimTransferSpans groups them, so only as many
1352 /// ends share as the tile needs. Packet headers tell a shared channel's ends
1353 /// apart.
1354 bool planShimSharing(TileLike exhausted, DMAChannelDir dir) {
1355 // Receiving ends share by the #aie.consumed_by proofs
1356 // aie-objectfifo-verify leaves; without them, by explicit permission only.
1357 ShimTransferSpans spans(
1358 device,
1359 [&](StringAttr symbol) {
1360 return ShimTransferSpans::endOf(device, symbol);
1361 },
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)
1370 continue;
1371 candidates.push_back(endpoint);
1372 fifos.push_back(ShimTransferSpans::keyOf(endpoint));
1373 names.push_back(endpoint.getSymNameAttr());
1374 }
1375 SmallVector<ShimDMAAllocationOp> allocations;
1376 SmallVector<ShimTransferSpans::SharedChannel> shared;
1377 for (auto alloc : device.getOps<ShimDMAAllocationOp>()) {
1378 auto allowed = AIEDialect::ShareableWithAttrHelper(alloc->getContext())
1379 .getAttr(alloc);
1380 if (!allowed || alloc.getTile() != exhausted->getResult(0) ||
1381 alloc.getChannelDir() != dir)
1382 continue;
1383 SmallVector<StringAttr> listed;
1384 for (Attribute attr : allowed)
1385 if (auto symbol = dyn_cast<FlatSymbolRefAttr>(attr))
1386 listed.push_back(symbol.getAttr());
1387 bool pinned =
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();
1393 });
1394 allocations.push_back(alloc);
1395 shared.emplace_back(std::move(listed), pinned);
1396 }
1397 ShimTransferSpans::Plan plan = spans.plan(fifos, names, shared);
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])
1402 .second)
1403 return true;
1404 for (auto &members : plan.groups)
1405 for (unsigned sharer : llvm::drop_begin(members))
1406 if (channelSharers
1407 .insert({candidates[sharer], candidates[members.front()]})
1408 .second)
1409 return true;
1410 return false;
1411 }
1412
1413 /// Whether `pool` can be walked whole (ObjectFifoPoolOp::canWalkWhole),
1414 /// its ends taking no turns but those in `regrouped`, whose turns are being
1415 /// chosen again.
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);
1423 });
1424 }
1425
1426 /// The DMA ends `dmas` of one mem tile that draw a channel of their own,
1427 /// and their pools in structural order, as a plan of the tile's BD ids
1428 /// weighs them with every buffer at home.
1429 struct HomeBDPlan {
1430 SmallVector<ObjectFifoPoolOp> pools;
1431 SmallVector<DMAChannelAnalysis::BDWalkPool> walkable;
1432 SmallVector<DMAChannelAnalysis::BDPlanEnd> ends;
1433 SmallVector<unsigned> poolOf;
1434 };
1435 HomeBDPlan homeBDPlan(ArrayRef<ObjectFifoDmaEndpointOp> dmas) {
1436 HomeBDPlan plan;
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);
1442 });
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))
1449 continue;
1450 plan.ends.push_back(planEnd(endpoint, /*adjacent=*/false,
1451 /*keepPin=*/true));
1452 plan.poolOf.push_back(llvm::find(plan.pools, dma.getPoolOp()) -
1453 plan.pools.begin());
1454 }
1455 return plan;
1456 }
1457
1458 /// Walks whichever pools need it: first walkHomeBDPools' plan for `tile`'s
1459 /// BD ids at home; once that needs none, the one pool
1460 /// DMAChannelAnalysis::nextPoolToWalk picks for what only the tile's real
1461 /// channels are short of. False once none is left to walk.
1462 bool walkForBDShortfall(TileLike tile,
1463 MutableArrayRef<ObjectFifoPoolOp> pools) {
1464 if (walkHomeBDPools(pools))
1465 return true;
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);
1471 std::optional<unsigned> next = DMAChannelAnalysis::nextPoolToWalk(
1472 plan.ends, plan.poolOf, plan.walkable,
1473 SmallVector<bool>(plan.pools.size(), false));
1474 if (next)
1475 plan.pools[*next].setContiguous(true);
1476 return next.has_value();
1477 }
1478
1479 /// Walks whole, on each placed mem tile, a set of
1480 /// DMAChannelAnalysis::walkSetsThatFit's, chosen by placing `pools` as the
1481 /// SA placer does; every walkable pool when none fits. Those tiles then take
1482 /// their channels from that plan. False when nothing is left to walk.
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);
1490 }
1491 struct Tile {
1492 TileID at;
1493 HomeBDPlan home;
1494 DMAChannelAnalysis::BDWalkSets found;
1495 SmallVector<ObjectFifoDmaEndpointOp> dmas;
1496 unsigned applied = 0;
1497 };
1498 SmallVector<Tile, 0> tiles;
1499 // The tile's own programs and runtime tasks keep their channels and BD
1500 // ids, as the SA placer's plan of the tile does.
1501 DMAChannelAnalysis channels(device);
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);
1513 },
1514 [&](DMAChannelDir dir, int channel) {
1515 auto it = taken.find({dir, channel});
1516 return it == taken.end() ? 0 : it->second;
1517 });
1518 if (found.sets.empty() && !found.fits && !found.channelShort) {
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;
1525 }
1526 }
1527 if (!found.sets.empty())
1528 tiles.push_back(
1529 {{at.first, at.second}, std::move(home), std::move(found), dmas});
1530 }
1531 auto setWalked = [&](Tile &tile, bool walked) {
1532 for (unsigned pool : tile.found.sets[tile.applied])
1533 tile.home.pools[pool].setContiguous(walked);
1534 };
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};
1541 };
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 =
1552 memTileSpillComponents(device.getTargetModel(), homes);
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;
1556
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)
1562 continue;
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);
1580 }
1581 };
1584 bytes,
1585 [&](ArrayRef<unsigned> choice) {
1586 apply(choice);
1587 SmallVector<ObjectFifoPoolOp> trial(componentPools);
1588 sizeOrder(trial);
1589 localPools.clear();
1590 return succeeded(planBuffers(trial));
1591 },
1593 apply(choice.sets);
1594 walkSearchStopped |= choice.stopped;
1595 for (Tile *tile : members) {
1596 if (tile->found.sets[tile->applied].empty())
1597 continue;
1598 walkedAny = true;
1599 for (auto dma : tile->dmas)
1600 bdPlanned.insert(
1601 tileOf(cast<RouteEndpoint>(dma.getOperation())).getOperation());
1602 }
1603 }
1604 return walkedAny;
1605 }
1606
1607 /// Whether, in every runtime sequence, the host issues each transfer
1608 /// through `fifo` before any wait: a turn chain waiting on that fifo's
1609 /// objects then waits on nothing the host does after the array has moved.
1610 bool hostMovesFirst(StringAttr fifo) {
1611 if (auto it = hostMovesFirstCache.find(fifo);
1612 it != hostMovesFirstCache.end())
1613 return it->second;
1614 bool result = hostMovesFirstUncached(fifo);
1615 hostMovesFirstCache[fifo] = result;
1616 return result;
1617 }
1618 bool hostMovesFirstUncached(StringAttr fifo) {
1619 SymbolTableCollection symbols;
1620 for (auto seq : device.getOps<RuntimeSequenceOp>()) {
1621 auto names = [&](Operation *op) {
1622 return fifo && AIEX::namesFifo(op, fifo.getValue(), symbols);
1623 };
1624 auto waits = [](Operation *op) {
1625 return isa<AIEX::NpuDmaWaitOp, AIEX::DMAAwaitTaskOp, AIEX::NpuSyncOp,
1626 AIEX::NpuMaskPollOp>(op);
1627 };
1628 bool waited = false;
1629 WalkResult walk = seq.walk<WalkOrder::PreOrder>([&](Operation *op) {
1630 if (waits(op)) {
1631 waited = true;
1632 return WalkResult::advance();
1633 }
1634 Operation *transfer = op;
1635 if (auto start = dyn_cast<AIEX::DMAStartTaskOp>(op))
1636 transfer = start.getTask().getDefiningOp();
1637 if (!transfer ||
1638 !isa<AIEX::NpuDmaMemcpyNdOp, AIEX::DMAConfigureTaskForOp,
1639 AIEX::DMAStartBdChainForOp>(transfer) ||
1640 isa<AIEX::DMAConfigureTaskForOp>(op) || !names(transfer))
1641 return WalkResult::advance();
1642 if (waited)
1643 return WalkResult::interrupt();
1644 for (Operation *parent = op->getParentOp(); parent != seq;
1645 parent = parent->getParentOp())
1646 if (parent
1647 ->walk([&](Operation *inner) {
1648 return waits(inner) ? WalkResult::interrupt()
1649 : WalkResult::advance();
1650 })
1651 .wasInterrupted())
1652 return WalkResult::interrupt();
1653 return WalkResult::advance();
1654 });
1655 if (walk.wasInterrupted())
1656 return false;
1657 }
1658 return true;
1659 }
1660
1661 /// The other end of the one route naming `endpoint`, when that route is a
1662 /// circuit between two objectFIFO DMA endpoints.
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))
1672 continue;
1673 if (peer || route.getPacket() || sources.size() != 1 || dests.size() != 1)
1674 return {};
1675 RouteEndpoint other = lookupEndpoint(source ? dests[0] : sources[0]);
1676 peer = other ? dyn_cast<ObjectFifoDmaEndpointOp>(other.getOperation())
1677 : ObjectFifoDmaEndpointOp();
1678 if (!peer)
1679 return {};
1680 }
1681 return peer;
1682 }
1683
1684 /// The one core endpoint working through `endpoint`'s pool from the other
1685 /// side.
1686 ObjectFifoCoreEndpointOp coreEndOf(ObjectFifoDmaEndpointOp endpoint) {
1687 ObjectFifoCoreEndpointOp found;
1688 for (auto core : device.getOps<ObjectFifoCoreEndpointOp>()) {
1689 if (core.getPool() != endpoint.getPool())
1690 continue;
1691 if (found || core.drains() == endpoint.drains())
1692 return {};
1693 found = core;
1694 }
1695 return found;
1696 }
1697
1698 /// How many turns in `turns` land on each of `ends`, and the descriptors
1699 /// each unrolled pass over it takes (0 for a pool already walked whole):
1700 /// the pairs turnPasses takes.
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()
1707 ? 0
1708 : end.getNumDescriptors()});
1709 }
1710 return counts;
1711 }
1712
1713 /// Whether a chain moving `turns` over `ends` can walk each contiguous pool
1714 /// with one descriptor per turn of its unrolled passes, each stepping over
1715 /// the others' objects: they must divide the pool's objects.
1716 static bool contiguousWalkersFit(ArrayRef<ObjectFifoDmaEndpointOp> ends,
1717 ArrayRef<unsigned> turns) {
1718 SmallVector<std::pair<int64_t, int64_t>> counts = turnCounts(ends, turns);
1719 int64_t passes = turnPasses(counts);
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)))
1725 return false;
1726 }
1727 return true;
1728 }
1729
1730 /// Gives `ends` one channel, the k-th object belonging to `ends[order[k]]`.
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);
1741 if (end != owner)
1742 channelSharers[end] = owner;
1743 }
1744 }
1745
1746 /// Gives one more end of `exhausted` the channel of others whose objects
1747 /// the same core needs in a fixed order, read off its program, so only as
1748 /// many ends share as the tile needs. A circuit carries one stream, so the
1749 /// ends at the routes' other ends take the same turns.
1750 bool planTurnSharing(TileLike exhausted, DMAChannelDir dir) {
1751 // `coreEndOf`/`circuitPeer` each rescan the whole device; neither's
1752 // domain (core endpoints, routes) changes within this function (only
1753 // pool `contiguous` flags and endpoints' `turns` attrs do), so caching
1754 // them once here turns every lookup below from O(device size) into O(1).
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);
1762 }
1763 auto endsOf = [&](Operation *pool) -> ArrayRef<ObjectFifoDmaEndpointOp> {
1764 auto it = poolEnds.find(pool);
1765 return it == poolEnds.end() ? ArrayRef<ObjectFifoDmaEndpointOp>()
1766 : it->second;
1767 };
1768 // Each circuit destination's one sender, a broadcast's included, and the
1769 // ends a circuit joins to the shim alone, which wait on the host only.
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();
1775 };
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])
1780 : RouteEndpoint();
1781 if (!source)
1782 continue;
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) {
1788 if (end && sender)
1789 senderOf[end.getOperation()] = sender;
1790 if (end && onShim(source))
1791 byShim.insert(end.getOperation());
1792 }
1793 if (llvm::all_of(dests,
1794 [&](RouteEndpoint end) { return end && onShim(end); }))
1795 byShim.insert(source.getOperation());
1796 }
1797 auto cachedCoreEnd = [&](ObjectFifoDmaEndpointOp dma) {
1798 return coreEndCache.lookup(dma);
1799 };
1800 auto cachedCircuitPeer = [&](ObjectFifoDmaEndpointOp dma) {
1801 return circuitPeerCache.lookup(dma);
1802 };
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);
1813 });
1814 LLVM_DEBUG({
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())
1825 << "\n";
1826 });
1827 auto groupOf = [](ObjectFifoDmaEndpointOp end) {
1828 SmallVector<ObjectFifoDmaEndpointOp> group = turnEndpoints(end);
1829 return group.empty() ? SmallVector<ObjectFifoDmaEndpointOp>{end} : group;
1830 };
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))
1835 continue;
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());
1844 }
1845 if (llvm::any_of(peers, [&](ObjectFifoDmaEndpointOp peer) {
1846 return !sameTile(peer.getTile(), peers.front().getTile()) ||
1847 llvm::any_of(turnEndpoints(peer), [&](auto other) {
1848 return !llvm::is_contained(peers, other);
1849 });
1850 })) {
1851 LLVM_DEBUG(llvm::dbgs()
1852 << " " << a.getSymName() << " + " << b.getSymName()
1853 << ": senders on different tiles\n");
1854 continue;
1855 }
1856 CoreTurns turns;
1857 std::string reason;
1858 if (succeeded(turns.read(cores, reason)) && !turns.keepsUp(depths))
1859 reason = "would stall";
1860 // The peers' chain moves the same turns, so a core working through
1861 // their pools, or through the pools that feed them circuit by circuit,
1862 // must keep up with that order too, through all those pools' depths.
1863 // A peer reached from the shim waits on the host, so the host must
1864 // move it before it waits on anything; one whose feeding core the walk
1865 // cannot find refuses the turns. Peers that split one pool between
1866 // them, draining it or filling it, each carry a part of what the core
1867 // at the pool's other end moves in one piece, so they count as one peer
1868 // of that core's when every segment on their side takes these turns.
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);
1880 });
1881 };
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;
1887 continue;
1888 }
1889 }
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) {
1899 lost = true;
1900 break;
1901 }
1902 if (byShim.contains(across.front())) {
1903 hostWaits |= !hostMovesFirst(across.front().getFifoNameAttr());
1904 break;
1905 }
1906 at = across.front().drains() ? cachedCircuitPeer(across.front())
1907 : senderOf.lookup(across.front());
1908 if (!at) {
1909 lost = true;
1910 break;
1911 }
1912 depth += at.getPoolOp().getDepth();
1913 core = cachedCoreEnd(at);
1914 }
1915 if (!core)
1916 continue;
1917 if (llvm::is_contained(peerCores, core)) {
1918 lost = true;
1919 continue;
1920 }
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);
1926 }
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";
1931 // A turn on a segment past every object its pool's segments have
1932 // reached asks the core for the next one; the objects the segments
1933 // hold open at once must fit the pool, and every segment takes one
1934 // part of each object.
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)
1940 continue;
1941 int64_t part = ++taken[turn];
1942 if (part > asked[fed[turn]]) {
1943 asked[fed[turn]] = part;
1944 peerOrder.push_back(fed[turn]);
1945 }
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";
1953 }
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()) {
1960 CoreTurns peerTurns;
1961 if (llvm::any_of(peerCores, [&](ObjectFifoCoreEndpointOp c) {
1962 return !sameTile(c.getTile(), peerCores.front().getTile());
1963 }))
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";
1968 }
1969 // Over plain pools the chain unrolls to whole passes over each; past
1970 // the peers' channel BDs, walking them whole takes one a turn.
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();
1977 overflows =
1978 col && row &&
1979 turnPasses(counts) * static_cast<int64_t>(turns.turns().size()) >
1980 device.getTargetModel().getNumBDsForChannel(*col, *row, 0);
1981 }
1982 // Beside a pool walked whole, the others' descriptors must come round
1983 // each pass, which walking them whole as well lines up.
1984 // A pool whose other end already takes turns may be walked whole too,
1985 // where those turns still line up.
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");
2001 continue;
2002 }
2003 pool.setContiguous(true);
2004 bool linedUp =
2005 llvm::all_of(others, [&](ObjectFifoDmaEndpointOp end) {
2006 SmallVector<ObjectFifoDmaEndpointOp> ends =
2007 turnEndpoints(end);
2008 SmallVector<unsigned> order;
2009 for (auto name :
2010 end.getTurnsAttr().getAsRange<FlatSymbolRefAttr>())
2011 order.push_back(
2012 llvm::find_if(ends,
2013 [&](ObjectFifoDmaEndpointOp e) {
2014 return e.getSymNameAttr() ==
2015 name.getAttr();
2016 }) -
2017 ends.begin());
2018 return contiguousWalkersFit(ends, order);
2019 });
2020 LLVM_DEBUG(
2021 llvm::dbgs()
2022 << " " << pool.getSymName() << " walked whole"
2023 << (linedUp ? "" : ", but its other turns would not line up")
2024 << "\n");
2025 if (linedUp) {
2026 walked.push_back(pool);
2027 turnWalked.insert(pool);
2028 } else
2029 pool.setContiguous(false);
2030 }
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);
2036 }
2037 if (!reason.empty()) {
2038 LLVM_DEBUG(llvm::dbgs() << " " << a.getSymName() << " + "
2039 << b.getSymName() << ": " << reason << "\n");
2040 continue;
2041 }
2042 takeTurns(group, turns.turns());
2043 takeTurns(peers, turns.turns());
2044 return true;
2045 }
2046 }
2047 return false;
2048 }
2049
2050 /// A route reaching or leaving a shared shim channel carries a packet
2051 /// header, its id distinct from those of the routes it shares the channel
2052 /// with. Other shared channels reuse the same ids: the router keeps flows
2053 /// with one id apart wherever their destinations differ.
2054 LogicalResult headShimSharingRoutes() {
2055 DenseMap<Operation *, Operation *> channelOf;
2056 for (auto [sharer, owner] : channelSharers) {
2057 if (!tileOf(cast<RouteEndpoint>(owner)).isShimTile())
2058 continue;
2059 channelOf[sharer] = owner;
2060 channelOf[owner] = owner;
2061 }
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()));
2070 };
2071 llvm::for_each(route.getSourceNames(), note);
2072 llvm::for_each(route.getDestinationNames(), note);
2073 return channels;
2074 };
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());
2081 PacketIdSpace ids(device);
2082 SmallVector<int> reused;
2083 for (auto route : device.getOps<RouteOp>()) {
2084 SmallVector<Operation *> channels = channelsOf(route);
2085 if (route.getPacket() || channels.empty())
2086 continue;
2087 auto freeOnAll = [&](int id) {
2088 return llvm::none_of(channels, [&](Operation *channel) {
2089 return idsOn[channel].contains(id);
2090 });
2091 };
2092 std::optional<int> id;
2093 if (auto *it = llvm::find_if(reused, freeOnAll); it != reused.end())
2094 id = *it;
2095 else if ((id = ids.takeLowestFrom()))
2096 reused.push_back(*id);
2097 else
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)));
2104 }
2105 return success();
2106 }
2107
2108 /// Channels are chosen by BD room but never refused for lack of it: a task
2109 /// that frees its BDs before the next starts lets demand exceed the BDs.
2110 /// Otherwise BD id assignment fails, so say where.
2111 void warnOvercommittedBDs() {
2112 const AIETargetModel &target = device.getTargetModel();
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 ||
2118 !row)
2119 continue;
2120 int channel = it->second;
2121 DMAChannelDir dir = endpoint.getRouteDirection();
2122 int64_t room = bdRoom(tile, *col, *row, dir, channel, channelDemand);
2123 if (room >= 0)
2124 continue;
2125 int64_t numBDs = target.getNumBDsForChannel(*col, *row, channel, dir);
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";
2132 }
2133 }
2134
2135 /// Keep a successful largest-first allocation unchanged. On channel
2136 /// exhaustion, try keeping an affected pool's resources local, cheapest
2137 /// first. Existing buffers and locks never move. Each DMA accesses every
2138 /// object in its pool, even when it selects only one segment. Reserving that
2139 /// pool once can therefore free several restricted channels. This is a
2140 /// bounded repair of the greedy buffer placement, not an exhaustive solver
2141 /// for tile placement or memory packing.
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);
2153 }
2154 }
2155 if (tried.size() >= 64 || !tried.insert(key).second ||
2156 failed(planBuffers(pools)) || failed(planLocks(pools)))
2157 return failure();
2158 DMAChannelAnalysis channels(device);
2159 if (succeeded(assignChannels(channels, /*diagnose=*/false)))
2160 return success();
2161 if (!channelFailure || !tileOf(channelFailure).isMemTile() ||
2162 !tileOf(channelFailure).tryGetCol() ||
2163 !tileOf(channelFailure).tryGetRow())
2164 return failure();
2165
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))
2178 continue;
2179 candidates.push_back(pool);
2180 }
2181 llvm::stable_sort(candidates, [&](ObjectFifoPoolOp a, ObjectFifoPoolOp b) {
2182 int64_t aBytes =
2183 a.getBuffers() ? 0 : a.getObjectSizeInBytes() * a.getDepth();
2184 int64_t bBytes =
2185 b.getBuffers() ? 0 : b.getObjectSizeInBytes() * b.getDepth();
2186 if (aBytes != bBytes)
2187 return aBytes < bBytes;
2188 return structuralRank.lookup(a) < structuralRank.lookup(b);
2189 });
2190 for (auto pool : candidates) {
2191 localPools[pool] = localTile;
2192 if (succeeded(planAllocation(pools, tried)))
2193 return success();
2194 localPools.erase(pool);
2195 }
2196 return failure();
2197 }
2198
2199 /// A packet-switched flow shares the stream with others, so every buffer
2200 /// descriptor the source emits has to carry the packet header.
2201 /// One packet flow carries every source of the route: each stamps the same
2202 /// header, and their packets share the destination channels.
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;
2209 // Written out in turn order after the last route.
2210 if (auto dma = dyn_cast<ObjectFifoDmaEndpointOp>(*source);
2211 dma && dma.getDispatch()) {
2212 dispatchHeaders[dma][*flow.getDestinationNames().begin()] = header;
2213 continue;
2214 }
2215 if (sourcedFlows.at(name.getAttr()).size() == 1)
2216 source.setRoutePacket(header);
2217 }
2218
2219 // An out-of-order receiver reads the buffer it should fill out of the
2220 // header, so the header has to reach its DMA.
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();
2226
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());
2236
2237 builder.setInsertionPointToStart(&ports);
2238 for (RouteEndpoint source : sources) {
2239 PacketSourceOp::create(builder, flow.getLoc(), source.getTile(),
2240 source.getRouteBundle(), channelOf(source));
2241 }
2242 for (StringRef destName : flow.getDestinationNames()) {
2243 auto dest = lookupEndpoint(destName);
2244 // An out-of-order receiver matches on the header rather than walking a
2245 // chain, so its descriptors carry the id too.
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));
2251 }
2252 return success();
2253 }
2254
2255 /// Assigned before flows are lowered, so every endpoint has one by now.
2256 int channelOf(RouteEndpoint endpoint) {
2257 std::optional<int> channel = endpoint.getRouteChannel();
2258 assert(channel && "channels are assigned before flows are lowered");
2259 return *channel;
2260 }
2261
2262 RouteEndpoint lookupEndpoint(StringRef name) {
2263 return dyn_cast_or_null<RouteEndpoint>(SymbolTable::lookupNearestSymbolFrom(
2264 device, StringAttr::get(device.getContext(), name)));
2265 }
2266
2267 LogicalResult lowerFlows() {
2268 // Independent core-pushed senders need different routing IDs even when
2269 // their descriptors are submitted at different times.
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())
2274 continue;
2275 for (StringRef name : flow.getSourceNames()) {
2276 auto source = dyn_cast<ObjectFifoDmaEndpointOp>(
2277 lookupEndpoint(name).getOperation());
2278 if (!source ||
2279 source.getReleaseStrategy() != ObjectFifoRelease::PushQueue)
2280 continue;
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 "
2288 "packet IDs");
2289 diag.attachNote(it->second->getLoc()) << "other sender is here";
2290 return failure();
2291 }
2292 }
2293 }
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));
2302 }
2303 loweredFlows.push_back(flow);
2304
2305 // Which switching a route gets was settled upstream of this pass: the
2306 // header is on the route, and --aie-assign-packet-ids gave it its id.
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");
2311 }
2312 if (failed(lowerPacketFlow(flow, sources, *packet))) {
2313 return failure();
2314 }
2315 continue;
2316 }
2317
2318 // The verifier keeps a circuit route to one source.
2319 RouteEndpoint source = sources.front();
2320
2321 int sourceChannel = channelOf(source);
2322 builder.setInsertionPoint(flow);
2323 for (StringRef destName : flow.getDestinationNames()) {
2324 auto dest = lookupEndpoint(destName);
2325 // Ends taking turns share one circuit for all their routes.
2326 if (!circuits
2327 .insert({source.getTile(), sourceChannel, dest.getTile(),
2328 channelOf(dest)})
2329 .second)
2330 continue;
2331 FlowOp::create(builder, flow.getLoc(), source.getTile(),
2332 source.getRouteBundle(), sourceChannel, dest.getTile(),
2333 dest.getRouteBundle(), channelOf(dest));
2334 }
2335 }
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));
2342 }
2343 return success();
2344 }
2345
2346 /// An `aiex.dma_channel_reset_for` outlives the fifo it names, so record the
2347 /// channels and locks it has to re-arm and point it at that record. Shim
2348 /// endpoints are left out: the host re-pushes those itself.
2349 LogicalResult bindRearmTargets() {
2350 if (poolLocks->rearms().empty()) {
2351 return success();
2352 }
2353
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;
2358 // The record stands for these endpoints and pools: located at each.
2359 SmallVector<Location> locs;
2360
2361 for (auto endpoint : device.getOps<RouteEndpoint>()) {
2362 std::optional<int> channel = endpoint.getRouteChannel();
2363 if (endpoint.getFifoName() != fifoName ||
2364 tileOf(endpoint).isShimTile() || !channel) {
2365 continue;
2366 }
2367 if (auto dma =
2368 dyn_cast<ObjectFifoDmaEndpointOp>(endpoint.getOperation());
2369 dma && dma.getReleaseStrategy() == ObjectFifoRelease::PushQueue) {
2370 for (AIEX::DmaChannelResetForOp user : users)
2371 user.emitOpError(
2372 "does not support core-pushed DMA channels; reset requires "
2373 "coordination with the issuing core and all shared senders");
2374 return failure();
2375 }
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());
2381 }
2382 for (auto pool : device.getOps<ObjectFifoPoolOp>()) {
2383 if (pool.getFifoName() != fifoName || pool.getTileLike().isShimTile()) {
2384 continue;
2385 }
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));
2390 }
2391 }
2392
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 "
2397 "locks to re-arm";
2398 }
2399 return failure();
2400 }
2401
2402 std::string name = (fifoName + "__rearm").str();
2403 for (unsigned suffix = 0; lookupNamedOpIn(device, StringRef(name));
2404 suffix++) {
2405 name = (fifoName + "__rearm" + std::to_string(suffix + 1)).str();
2406 }
2407
2408 // head_bd_ids and repeat_counts are filled in by --aie-assign-bd-ids.
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 /*head_bd_ids=*/DenseI32ArrayAttr(),
2416 /*repeat_counts=*/DenseI32ArrayAttr());
2417 auto target = FlatSymbolRefAttr::get(builder.getContext(), name);
2418 for (AIEX::DmaChannelResetForOp user : users) {
2419 user.setObjfifoAttr(target);
2420 }
2421 }
2422 return success();
2423 }
2424
2425 /// Give each dma_start naming an endpoint the channel it was assigned.
2426 LogicalResult resolveStart(DMAStartOp start, RouteEndpointOp endpoint,
2427 ArrayRef<RouteOp> flows, ArrayRef<int> ids,
2428 int channel) {
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);
2435 // Only a runtime task's BDs are given the packet header, so a DMA
2436 // program states it in each BD; --aie-assign-packet-ids made it pin one.
2437 bool packet = !flows.empty() && RouteOp(flows.front()).getPacket();
2438 if (packet) {
2439 SmallVector<DMABDOp> bds;
2440 for (Block *block : DMAChannelAnalysis::chainOf(start))
2441 llvm::append_range(bds, block->getOps<DMABDOp>());
2442 if (failed(checkHeaders(endpoint, ids, bds)))
2443 return failure();
2444 }
2445 start.setChannelAttr(builder.getI32IntegerAttr(channel));
2446 return success();
2447 }
2448
2449 /// A packet source that no one header is stamped on needs each of `bds` to
2450 /// state the header of one of its flows, whose pinned ids are `ids`.
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))
2460 continue;
2461 return bd.emitOpError("sends on @")
2462 << endpoint.getSymName()
2463 << " without the packet header of one of its flows, ids " << ids;
2464 }
2465 return success();
2466 }
2467
2468 /// Each runtime task or transfer that sends on a shared source must state
2469 /// one of its flows' headers; a DMA program's start is resolveStart's, and
2470 /// other users send nothing.
2471 LogicalResult checkSharedSourceUsers(RouteEndpointOp endpoint,
2472 ArrayRef<int> ids) {
2473 auto uses = SymbolTable::getSymbolUses(endpoint, device);
2474 if (!uses)
2475 return success();
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)))
2482 return failure();
2483 continue;
2484 }
2485 if (auto start = dyn_cast<AIEX::DMAStartBdChainForOp>(user)) {
2486 auto chain = device.lookupSymbol<BDChainOp>(start.getSymbol());
2487 if (!chain)
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)))
2492 return failure();
2493 continue;
2494 }
2495 auto memcpy = dyn_cast<AIEX::NpuDmaMemcpyNdOp>(user);
2496 if (!memcpy)
2497 continue;
2498 std::optional<PacketInfoAttr> packet = memcpy.getPacket();
2499 if (packet && llvm::is_contained(ids, packet->getPktId()))
2500 continue;
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 "
2505 "ids "
2506 << ids;
2507 }
2508 return success();
2509 }
2510
2511 /// A runtime task naming an endpoint is configured on the endpoint's tile
2512 /// and channel directly.
2513 void resolveTask(AIEX::DMAConfigureTaskForOp task, RouteEndpointOp endpoint,
2514 int channel) {
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 /*out_of_order=*/UnitAttr(), /*alloc=*/FlatSymbolRefAttr());
2525 task.getResult().replaceAllUsesWith(configured.getResult());
2526 configured.getBody().takeBody(task.getBody());
2527 task.erase();
2528 }
2529
2530 /// Rewrite the programs and tasks naming an endpoint to its channel while
2531 /// the route giving its direction is still there. A shim end with a fifo
2532 /// name keeps its tasks, which emitShimAllocations points at the allocation.
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)))
2548 return failure();
2549 if (starts.empty() && tasks.empty())
2550 continue;
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)))
2555 return failure();
2556 if (endpoint.getTileLike().isShimTile() && endpoint.getFifoName())
2557 continue;
2558 for (auto task : tasks)
2559 resolveTask(task, endpoint, *channel);
2560 }
2561 return success();
2562 }
2563
2564 /// A shim endpoint has no memory of its own, so the runtime needs its channel
2565 /// spelled out under the name the sequence refers to.
2566 void emitShimAllocations() {
2567 builder.setInsertionPoint(device.getBody()->getTerminator());
2568 // A fifo's first shim end takes the name the runtime sequence was pointed
2569 // at. Any further shim end of the same fifo, as when a core broadcasts to
2570 // two shim tiles, is a different tile and channel and needs a record of
2571 // its own; sharing the first would send the runtime to the wrong tile.
2572 llvm::StringMap<unsigned> shimEndsSeen;
2573 for (auto endpoint : device.getOps<RouteEndpoint>()) {
2574 std::optional<StringRef> fifoName = endpoint.getFifoName();
2575 if (!fifoName)
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) {
2580 continue;
2581 }
2582 std::string name = (*fifoName + "__shim_alloc").str();
2583 unsigned ordinal = shimEndsSeen[*fifoName]++;
2584 bool create = true;
2585 if (ordinal == 0) {
2586 // A record under this name may already be there, declared by hand.
2587 create = !SymbolTable::lookupNearestSymbolFrom<ShimDMAAllocationOp>(
2588 device, builder.getStringAttr(name));
2589 } else {
2590 for (unsigned suffix = ordinal - 1; device.lookupSymbol(name);
2591 suffix++) {
2592 name =
2593 (*fifoName + "__shim_alloc" + std::to_string(suffix + 1)).str();
2594 }
2595 }
2596 if (create) {
2597 // The proof names other shim endpoints, which replaceAllSymbolUses
2598 // renames to their allocations as each is reached.
2599 auto routeEndpoint = dyn_cast<RouteEndpointOp>(endpoint.getOperation());
2600 ShimDMAAllocationOp::create(
2601 builder, endpoint.getLoc(), builder.getStringAttr(name),
2602 endpoint.getTile(),
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());
2609 }
2610 // The runtime sequence reaches the fifo through this record.
2611 (void)SymbolTable::replaceAllSymbolUses(
2612 endpoint, builder.getStringAttr(name), device);
2613 }
2614 }
2615
2616 /// Size-first packing order: mem tile pools largest buffer first, equal
2617 /// ones by home coordinates, unplaced last, as the SA placer orders them, in
2618 /// the slots mem tile pools hold, the others left in place. A pool walked
2619 /// whole becomes one large buffer, so this is chosen again after every walk.
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);
2627 }
2628 }
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));
2634 };
2635 return home(a) < home(b);
2636 });
2637 sortLargestBufferFirst(memTilePools, bufferBytes);
2638 for (auto [slot, pool] : llvm::zip(memTileSlots, memTilePools))
2639 pools[slot] = pool;
2640 }
2641
2642 /// Alternative packing order (demandFirstOrder). The same buffer, lock and
2643 /// channel planner validates both orders.
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()))
2650 continue;
2651 auto &demand = poolChannelDemand[pool];
2652 if (endpoint.getRouteDirection() == DMAChannelDir::S2MM)
2653 ++demand.first;
2654 else
2655 ++demand.second;
2656 }
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())
2663 continue;
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());
2670 }
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)});
2675 }
2676 SmallVector<ObjectFifoPoolOp> ordered(pools);
2677 for (auto [slot, index] :
2678 llvm::zip(memTileSlots, demandFirstOrder(records)))
2679 ordered[slot] = pools[memTileSlots[index]];
2680 return ordered;
2681 }
2682
2683 void runOnOperation() override {
2684 device = getOperation();
2685 builder = OpBuilder(device.getContext());
2686 semaphoreLocks =
2687 device.getTargetModel().hasProperty(AIETargetModel::UsesSemaphoreLocks);
2688 // One pass instance serves every device in the module, and none of this
2689 // state means anything outside the device it was gathered from.
2690 channelSharers.clear();
2691 allocationSharers.clear();
2692 lastPlaced.clear();
2693 loweredFlows.clear();
2694 sourcedFlows.clear();
2695 localPools.clear();
2696 poolUsers.clear();
2697 lockUsers.clear();
2698 lockPlacements.clear();
2699 spillTiles.clear();
2700 dispatchHeaders.clear();
2701 channelSharers.clear();
2702 bdPlanned.clear();
2703 turnWalked.clear();
2704 hostMovesFirstCache.clear();
2705 bufferPlacements.clear();
2706 channelAssignments.clear();
2707 endpointStarts.clear();
2708 endpointTasks.clear();
2709 takenBDs = {};
2710 taskBDs.clear();
2711 channelDemand.clear();
2712 structuralRank.clear();
2713 channelFailure = nullptr;
2714 bufferFailure = nullptr;
2715 lockFailure = nullptr;
2716 lockAccessFailure = nullptr;
2717 walkSearchStopped = false;
2718
2719 if (failed(collectFixedMemory()) || failed(checkStreamPorts()))
2720 return signalPassFailure();
2721 collectChannelPrograms();
2722 rankStructurally();
2723
2724 // Preserve successful largest-first allocations, including their locality
2725 // repairs. Only try demand ordering when that search fails.
2726 SmallVector<ObjectFifoPoolOp> pools(device.getOps<ObjectFifoPoolOp>());
2727 llvm::stable_sort(pools, [&](ObjectFifoPoolOp a, ObjectFifoPoolOp b) {
2728 return structuralRank.lookup(a) < structuralRank.lookup(b);
2729 });
2730 sizeOrder(pools);
2731
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);
2736 }
2737 for (auto endpoint : device.getOps<ObjectFifoDmaEndpointOp>()) {
2738 poolUsers[endpoint.getPoolOp()].push_back(endpoint.getTile());
2739 collectLockUsers(endpoint);
2740 }
2741 for (auto &[group, users] : lockUsers)
2742 llvm::stable_sort(users, [&](Operation *a, Operation *b) {
2743 return structuralRank.lookup(a) < structuralRank.lookup(b);
2744 });
2745
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)) {
2751 // Memoized locality sets are specific to a packing order.
2752 localPools.clear();
2753 tried.clear();
2754 allocated = planAllocation(demandOrdered, tried);
2755 }
2756 }
2757 // Out of channels, ends that never need theirs at once take turns on one,
2758 // a tile and direction at a time: on a shim tile, ends never in flight
2759 // together; elsewhere, ends whose objects one core needs in a fixed order.
2760 // Short of BD ids on a mem tile channel, its deepest pool walked whole
2761 // takes one a side. Buffers that fit nowhere as split are placed again
2762 // with the pools walked whole that the tiles' BD ids need anyway.
2763 auto repair = [&] {
2764 if (channelFailure) {
2765 TileLike tile = tileOf(channelFailure);
2766 DMAChannelDir dir = channelFailure.getRouteDirection();
2767 if (bdShortfall) {
2768 if (bdPlanned.insert(tile.getOperation()) ||
2769 walkForBDShortfall(tile, pools))
2770 return true;
2771 } else if (tile.isShimTile() ? planShimSharing(tile, dir)
2772 : planTurnSharing(tile, dir)) {
2773 return true;
2774 }
2775 }
2776 localPools.clear();
2777 return failed(planBuffers(pools)) && walkHomeBDPools(pools);
2778 };
2779 while (failed(allocated) && repair()) {
2780 localPools.clear();
2781 tried.clear();
2782 sizeOrder(pools);
2783 allocated = planAllocation(pools, tried);
2784 }
2785 if (succeeded(allocated) &&
2786 (!channelSharers.empty() || !allocationSharers.empty()) &&
2787 failed(headShimSharingRoutes()))
2788 return signalPassFailure();
2789 if (failed(allocated)) {
2790 localPools.clear();
2791 if (failed(planBuffers(pools))) {
2792 InFlightDiagnostic error =
2793 walkSearchStopped
2794 ? bufferFailure.emitOpError(
2795 "could not place buffers: the search for which pools "
2796 "to make contiguous (one buffer, one BD per side) "
2797 "stopped after ")
2799 << " placements tried in one group of neighbouring "
2800 "mem tiles"
2801 : bufferFailure.emitOpError(kNoBufferRoom);
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)}));
2816 }
2817 if (!walked.empty()) {
2818 Diagnostic &note = error.attachNote();
2819 note << kTurnWalkedNote;
2820 llvm::interleaveComma(walked, note);
2821 }
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 ")
2828 << LockPlan::kPackBudget << " steps";
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");
2836 else
2837 lockFailure.getDefiningOp()->emitOpError(
2838 "could not place locks within tile lock capacity");
2839 } else {
2840 DMAChannelAnalysis channels(device);
2841 (void)assignChannels(channels);
2842 device.emitRemark(
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");
2846 }
2847 return signalPassFailure();
2848 }
2849 for (ObjectFifoPoolOp pool : pools) {
2850 allocateBuffers(pool);
2851 allocateLocks(pool);
2852 }
2853 for (TileOp tile : spillTiles)
2854 if (tile->use_empty())
2855 tile->erase();
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();
2861
2862 // Routes still identify each sender's receiving buffers here, but hardware
2863 // BD IDs are assigned later. Preserve that pairing with temporary tags
2864 // before lowering erases the routes.
2865 llvm::EquivalenceClasses<Operation *> matchingPools;
2866 DenseMap<Operation *, int64_t> descriptorCounts;
2867 for (auto flow : device.getOps<RouteOp>()) {
2868 if (flow.getSources().size() != 1)
2869 continue;
2870 ObjectFifoPoolOp first;
2871 for (auto destName : flow.getDestinationNames()) {
2872 RouteEndpoint receiver = lookupEndpoint(destName);
2873 auto dst =
2874 receiver
2875 ? dyn_cast<ObjectFifoDmaEndpointOp>(receiver.getOperation())
2876 : nullptr;
2877 if (!dst || !dst.getOutOfOrder())
2878 continue;
2879 ObjectFifoPoolOp pool = dst.getPoolOp();
2880 if (!first)
2881 first = pool;
2882 matchingPools.unionSets(first.getOperation(), pool.getOperation());
2883 descriptorCounts[pool] = dst.getNumDescriptors();
2884 }
2885 }
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())
2891 continue;
2892 Operation *leader = *member;
2893 auto &tags = tagsOfGroup[leader];
2894 if (!tags) {
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);
2899 }
2900 pool.setOutOfOrderTagsAttr(tags);
2901 }
2902
2903 // A sender references the next hop's receiving slots, independently of
2904 // any receiving descriptors that fill its own pool.
2905 for (auto flow : device.getOps<RouteOp>()) {
2906 if (flow.getSources().size() != 1)
2907 continue;
2908 RouteEndpoint sender = lookupEndpoint(*flow.getSourceNames().begin());
2909 auto src = sender
2910 ? dyn_cast<ObjectFifoDmaEndpointOp>(sender.getOperation())
2911 : nullptr;
2912 if (!src || !src.getOutOfOrder())
2913 continue;
2914 for (auto destName : flow.getDestinationNames()) {
2915 RouteEndpoint receiver = lookupEndpoint(destName);
2916 auto dst =
2917 receiver
2918 ? dyn_cast<ObjectFifoDmaEndpointOp>(receiver.getOperation())
2919 : nullptr;
2920 if (dst && dst.getOutOfOrder()) {
2921 src.setOutOfOrderTagsAttr(dst.getPoolOp().getOutOfOrderTagsAttr());
2922 break;
2923 }
2924 }
2925 }
2926
2927 if (failed(bindRearmTargets())) {
2928 return signalPassFailure();
2929 }
2930 if (failed(lowerFlows()) || failed(resolveEndpointUses())) {
2931 return signalPassFailure();
2932 }
2933 emitShimAllocations();
2934 for (Operation *flow : loweredFlows) {
2935 flow->erase();
2936 }
2937 }
2938};
2939
2940} // namespace
2941
2942std::unique_ptr<OperationPass<DeviceOp>>
2944 return std::make_unique<AIEObjectFifoAllocatePass>();
2945}
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.
Definition AIELockPlan.h:79
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.
Definition AIELockPlan.h:90
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)
Definition AIEUtils.cpp:386
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...
Definition AIEPasses.h:46
constexpr llvm::StringLiteral kNoBufferRoom
How --aie-objectfifo-allocate says a pool's buffers fit no memory its users reach; the diagnostic's s...
Definition AIEPasses.h:42
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,...
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.
Definition AIELockPlan.h:52
std::optional< unsigned > full
The last such candidate, when all were full.
Definition AIELockPlan.h:54
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.