MLIR-AIE 1.4.6.dev
AIEDMAChannelAnalysis.cpp
Go to the documentation of this file.
1//===- AIEDMAChannelAnalysis.cpp --------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2021-2022 Xilinx, Inc.
4// Copyright (C) 2022-2026 Advanced Micro Devices, Inc.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12
13#include "llvm/ADT/BitVector.h"
14#include "llvm/ADT/DenseSet.h"
15
16#include <functional>
17#include <map>
18#include <numeric>
19#include <set>
20#include <vector>
21
22using namespace mlir;
23using namespace xilinx;
24using namespace xilinx::AIE;
25
26Value DMAChannelAnalysis::getTileKey(Value tile) {
27 auto tileOp = cast<TileLike>(tile.getDefiningOp());
28 auto col = tileOp.tryGetCol();
29 auto row = tileOp.tryGetRow();
30 if (!col || !row)
31 return tile;
32 return tilesByCoordinate.try_emplace({*col, *row}, tile).first->second;
33}
34
35void DMAChannelAnalysis::claim(Value tile, DMAChannelDir dir, int channel,
36 Operation *owner) {
37 if (usedChannels.try_emplace({getTileKey(tile), dir, channel}, owner).second)
38 claims.emplace_back(tile, dir, channel, owner);
39}
40
42 for (auto program : device.getOps<DmaBody>()) {
43 for (Block &block : program.getDmaBody()) {
44 for (auto start : block.getOps<DMAStartOp>()) {
45 // The route endpoint it names claims the channel; see assignChannels.
46 if (start.getEndpoint())
47 continue;
48 claim(program.getTile(), start.getChannelDir(), start.getChannelIndex(),
49 start);
50 }
51 }
52 }
53
54 // A flow ending at a tile's DMA claims that channel's stream even when no
55 // DMA body here starts it: its BDs may come from the runtime sequence alone.
56 // First-free assignment must skip it, but a pinned request may name it --
57 // that is the DMA feeding or draining the flow, as when allocation reruns
58 // over flows it lowered itself.
59 auto streamDMA = [&](Value tile, DMAChannelDir dir, int channel,
60 Operation *owner) {
61 streamedChannels.try_emplace(
62 std::make_tuple(getTileKey(tile), dir, channel), owner);
63 };
64 for (auto flowOp : device.getOps<FlowOp>()) {
65 if (flowOp.getSourceBundle() == WireBundle::Core) {
66 usedStreams.try_emplace({getTileKey(flowOp.getSource()),
67 DMAChannelDir::MM2S, flowOp.getSourceChannel()},
68 StreamClaim{flowOp, false});
69 }
70 if (flowOp.getDestBundle() == WireBundle::Core) {
71 usedStreams.try_emplace({getTileKey(flowOp.getDest()),
72 DMAChannelDir::S2MM, flowOp.getDestChannel()},
73 StreamClaim{flowOp, false});
74 }
75 if (flowOp.getSourceBundle() == WireBundle::DMA)
76 streamDMA(flowOp.getSource(), DMAChannelDir::MM2S,
77 flowOp.getSourceChannel(), flowOp);
78 if (flowOp.getDestBundle() == WireBundle::DMA)
79 streamDMA(flowOp.getDest(), DMAChannelDir::S2MM, flowOp.getDestChannel(),
80 flowOp);
81 }
82 for (auto packetFlow : device.getOps<PacketFlowOp>()) {
83 for (auto source : packetFlow.getOps<PacketSourceOp>())
84 if (source.getBundle() == WireBundle::DMA)
85 streamDMA(source.getTile(), DMAChannelDir::MM2S, source.getChannel(),
86 packetFlow);
87 for (auto dest : packetFlow.getOps<PacketDestOp>())
88 if (dest.getBundle() == WireBundle::DMA)
89 streamDMA(dest.getTile(), DMAChannelDir::S2MM, dest.getChannel(),
90 packetFlow);
91 }
92
93 // A task the runtime sequence configures on a channel by index programs that
94 // channel, as a DMA body would.
95 device.walk([&](AIEX::DMAConfigureTaskOp task) {
96 claim(task.getTile(), task.getDirection(), (int)task.getChannel(), task);
97 });
98
99 for (auto flow : device.getOps<PacketFlowOp>()) {
100 Block &ports = flow.getPorts().front();
101 for (auto source : ports.getOps<PacketSourceOp>())
102 if (source.getBundle() == WireBundle::Core)
103 usedStreams.try_emplace({getTileKey(source.getTile()),
104 DMAChannelDir::MM2S, source.channelIndex()},
105 StreamClaim{source, true});
106 for (auto dest : ports.getOps<PacketDestOp>())
107 if (dest.getBundle() == WireBundle::Core)
108 usedStreams.try_emplace({getTileKey(dest.getTile()),
109 DMAChannelDir::S2MM, dest.channelIndex()},
110 StreamClaim{dest, true});
111 }
112
113 // Shim allocations reserve channels outside the DMA bodies above. A
114 // shareable allocation still holds its channel against unlisted ends, so
115 // it is a claim too; skip the control overlay's, which the placers count
116 // as the planned overlay channel.
117 for (auto allocOp : device.getOps<ShimDMAAllocationOp>()) {
118 MLIRContext *context = allocOp->getContext();
119 if (!AIEDialect::ShareableWithAttrHelper(context).isAttrPresent(allocOp)) {
120 claim(allocOp.getTile(), allocOp.getChannelDir(),
121 (int)allocOp.getChannelIndex(), allocOp);
122 continue;
123 }
124 shareableChannels.try_emplace(
125 std::make_tuple(getTileKey(allocOp.getTile()), allocOp.getChannelDir(),
126 (int)allocOp.getChannelIndex()),
127 allocOp.getOperation());
128 if (!AIEDialect::IsCtrlPktOverlayAttrHelper(context).isAttrPresent(allocOp))
129 claims.emplace_back(allocOp.getTile(), allocOp.getChannelDir(),
130 (int)allocOp.getChannelIndex(), allocOp);
131 }
132}
133
135 TileLike tile, DMAChannelDir dir, bool requiresAdjacentTileAccessChannels) {
136 std::optional<int> col = tile.tryGetCol();
137 std::optional<int> row = tile.tryGetRow();
138 const auto &targetModel = getTargetModel(tile);
139 // A tile that is not fully placed stands for any tile of its type.
140 TileID id =
141 col && row
142 ? TileID{*col, *row}
143 : cast<LogicalTileOp>(tile.getOperation()).getCanonicalTileID();
144 int maxChannelNum = targetModel.getNumDMAChannels(id.col, id.row, dir);
145
146 if (!requiresAdjacentTileAccessChannels)
147 return maxChannelNum;
148
149 if (col && row)
150 return std::min<int>(
151 maxChannelNum,
152 targetModel.getMaxChannelNumForAdjacentMemTile(*col, *row));
153
154 // Assignment before placement must be safe at every compatible position,
155 // not assume that unresolved coordinates remove neighbor restrictions.
156 bool foundPosition = false;
157 for (int c = 0; c < targetModel.columns(); ++c) {
158 if (col && c != *col)
159 continue;
160 for (int r = 0; r < targetModel.rows(); ++r) {
161 if ((row && r != *row) ||
162 targetModel.getTileType(c, r) != tile.getTileType())
163 continue;
164 foundPosition = true;
165 maxChannelNum = std::min<int>(
166 maxChannelNum, targetModel.getMaxChannelNumForAdjacentMemTile(c, r));
167 }
168 }
169
170 return foundPosition ? maxChannelNum : 0;
171}
172
174 TileLike tile, DMAChannelDir dir, bool requiresAdjacentTileAccessChannels,
175 Operation *owner) {
176 int limit = getDMAChannelLimit(tile, dir, requiresAdjacentTileAccessChannels);
177 for (int i = 0; i < limit; i++) {
178 if (isChannelFree(tile, dir, i) &&
179 reservePinnedChannel(tile, dir, i, owner) >= 0) {
180 return i;
181 }
182 }
183 return -1;
184}
185
186bool DMAChannelAnalysis::isChannelFree(TileLike tile, DMAChannelDir dir,
187 int channel) {
188 auto key = std::make_tuple(getTileKey(tile->getResult(0)), dir, channel);
189 return !usedChannels.contains(key) && !streamedChannels.contains(key) &&
190 !shareableChannels.contains(key);
191}
192
193int DMAChannelAnalysis::reservePinnedChannel(TileLike tile, DMAChannelDir dir,
194 int channel, Operation *owner,
195 bool shareable) {
196 int maxChannelNum = getDMAChannelLimit(tile, dir, false);
197 if (channel < 0 || channel >= maxChannelNum) {
198 return -1;
199 }
200 auto key = std::make_tuple(getTileKey(tile->getResult(0)), dir, channel);
201 if (auto *reservation = shareableChannels.lookup(key)) {
202 if (!shareable)
203 return -1;
204 auto allowed =
205 AIEDialect::ShareableWithAttrHelper(reservation->getContext())
206 .getAttr(reservation);
207 auto name =
208 owner ? owner->getAttrOfType<StringAttr>("sym_name") : StringAttr();
209 if (!allowed || !name || llvm::none_of(allowed, [&](Attribute attr) {
210 auto symbol = dyn_cast<FlatSymbolRefAttr>(attr);
211 return symbol && symbol.getAttr() == name;
212 }))
213 return -1;
214 }
215 if (usedChannels.try_emplace(key, owner).second) {
216 if (shareable)
217 sharedChannels.insert(key);
218 return channel;
219 }
220 // Packet-switched sources share a channel: the runtime writes its
221 // descriptors one transfer at a time, each under its own header.
222 if (shareable && sharedChannels.contains(key))
223 return channel;
224 return -1;
225}
226
228 DMAChannelDir dir,
229 int channel) {
230 auto key = std::make_tuple(getTileKey(tile->getResult(0)), dir, channel);
231 if (Operation *owner = usedChannels.lookup(key))
232 return owner;
233 if (Operation *owner = streamedChannels.lookup(key))
234 return owner;
235 return shareableChannels.lookup(key);
236}
237
238LogicalResult DMAChannelAnalysis::checkAIEStreamIndex(TileLike tile,
239 DMAChannel chan,
240 Operation *user,
241 bool packet) {
242 auto [it, inserted] = usedStreams.try_emplace(
243 {getTileKey(tile->getResult(0)), chan.direction, chan.channel},
244 StreamClaim{user, packet});
245 if (inserted || (packet && it->second.packet)) {
246 return success();
247 }
248 auto diag = user->emitOpError("Core ")
249 << (chan.direction == DMAChannelDir::MM2S ? "output " : "input ")
250 << chan.channel
251 << " is already in use on this tile; a core stream port carries "
252 "one circuit or only packet flows";
253 diag.attachNote(it->second.owner->getLoc()) << "the other stream is here";
254 return diag;
255}
256
257SmallVector<Block *> DMAChannelAnalysis::chainOf(DMAStartOp start) {
258 SmallVector<Block *> chain;
259 SmallPtrSet<Block *, 8> seen;
260 SmallVector<Block *> work{start.getDest()};
261 while (!work.empty()) {
262 Block *block = work.pop_back_val();
263 if (!seen.insert(block).second || block->getOps<DMABDOp>().empty())
264 continue;
265 chain.push_back(block);
266 if (auto next = dyn_cast<NextBDOp>(block->getTerminator()))
267 work.push_back(next.getDest());
268 }
269 return chain;
270}
271
272int64_t DMAChannelAnalysis::countBDs(DMAStartOp start) {
273 int64_t bds = 0;
274 for (Block *block : chainOf(start))
275 bds += llvm::range_size(block->getOps<DMABDOp>());
276 return bds;
277}
278
280 for (auto program : device.getOps<DmaBody>())
281 for (Block &block : program.getDmaBody())
282 for (auto start : block.getOps<DMAStartOp>())
283 if (!start.getEndpointOp())
284 if (Operation *tile = program.getTile().getDefiningOp())
285 fixed[tile][{start.getChannelDir(), start.getChannelIndex()}] +=
286 countBDs(start);
287 unsigned order = 0;
289 device, [&](Operation *, Operation *tile, std::optional<int> channel,
290 std::optional<DMAChannelDir> dir, int32_t id) {
291 pinned[tile].push_back(Pin{order++, id, channel, dir});
292 });
293}
294
295std::map<DMAChannelAnalysis::BDUser, int64_t>
296DMAChannelAnalysis::TakenBDs::at(const AIETargetModel &target, int col, int row,
297 ArrayRef<Operation *> tiles) const {
298 auto here = [&](Operation *tile) {
299 auto like = dyn_cast<TileLike>(tile);
300 return llvm::is_contained(tiles, tile) ||
301 (like && like.tryGetCol() == col && like.tryGetRow() == row);
302 };
303 std::map<BDUser, int64_t> taken;
304 for (auto &[tile, users] : fixed)
305 if (here(tile))
306 for (auto [user, bds] : users)
307 taken[user] += bds;
308 int numChannels = std::max(
309 target.getNumSourceSwitchboxConnections(col, row, WireBundle::DMA),
310 target.getNumDestSwitchboxConnections(col, row, WireBundle::DMA));
311 // (pool, id) -> charged channel and earliest pin; the private pools of an
312 // AIE4 mem tile reuse ids.
313 std::map<std::pair<uint32_t, int32_t>, std::pair<unsigned, BDUser>> charged;
314 for (auto &[tile, pins] : pinned) {
315 if (!here(tile))
316 continue;
317 for (const Pin &pin : pins) {
318 SmallVector<DMAChannelDir, 2> dirs;
319 if (pin.dir)
320 dirs.push_back(*pin.dir);
321 else
322 dirs.append({DMAChannelDir::S2MM, DMAChannelDir::MM2S});
323 std::optional<uint32_t> own;
324 if (pin.channel && pin.dir &&
325 target.isBdChannelAccessible(col, row, pin.id, *pin.channel,
326 *pin.dir))
327 own = target.getBdPoolId(col, row, *pin.channel, *pin.dir);
328 std::optional<BDUser> user;
329 for (int channel = 0, last = pin.channel.value_or(numChannels - 1);
330 channel <= last && !user; ++channel)
331 for (DMAChannelDir dir : dirs)
332 if (target.isBdChannelAccessible(col, row, pin.id, channel, dir) &&
333 (!own || target.getBdPoolId(col, row, channel, dir) == *own)) {
334 user = BDUser{dir, channel};
335 break;
336 }
337 if (!user)
338 continue;
339 uint32_t pool = target.getBdPoolId(col, row, user->second, user->first);
340 if (auto [it, added] =
341 charged.try_emplace({pool, pin.id}, pin.order, *user);
342 !added && pin.order < it->second.first)
343 it->second = {pin.order, *user};
344 }
345 }
346 for (auto &[key, entry] : charged)
347 ++taken[entry.second];
348 return taken;
349}
350
351SmallVector<std::pair<int, int>>
353 std::set<std::pair<int, int>> at;
354 auto add = [&](Operation *tile) {
355 auto like = dyn_cast<TileLike>(tile);
356 if (!like)
357 return;
358 if (auto col = like.tryGetCol(), row = like.tryGetRow(); col && row)
359 at.insert({*col, *row});
360 };
361 for (auto &entry : fixed)
362 add(entry.first);
363 for (auto &entry : pinned)
364 add(entry.first);
365 return {at.begin(), at.end()};
366}
367
368llvm::SmallVector<DMAChannelAnalysis::BDGroup>
369DMAChannelAnalysis::bdGroups(const AIETargetModel &target, int col, int row,
370 int numChannels) {
371 // Group channels by BD pool; a group moves to the back as it grows.
372 struct Pool {
373 uint32_t id;
374 BDGroup group;
375 };
376 SmallVector<Pool> pools;
377 for (int channel = 0; channel < numChannels; ++channel)
378 for (DMAChannelDir dir : {DMAChannelDir::S2MM, DMAChannelDir::MM2S}) {
379 if (channel >= static_cast<int>(target.getNumDMAChannels(col, row, dir)))
380 continue;
381 uint32_t poolId = target.getBdPoolId(col, row, channel, dir);
382 Pool merged{
383 poolId,
384 {static_cast<int64_t>(target.getNumBDsInPool(col, row, poolId)),
385 {{dir, channel}}}};
386 auto *it = llvm::find_if(
387 pools, [&](const Pool &pool) { return pool.id == poolId; });
388 if (it != pools.end()) {
389 llvm::append_range(merged.group.users, it->group.users);
390 pools.erase(it);
391 }
392 pools.push_back(std::move(merged));
393 }
394 SmallVector<BDGroup> groups;
395 for (Pool &pool : pools) {
396 llvm::sort(pool.group.users, [](const BDUser &a, const BDUser &b) {
397 return std::make_pair(a.second, a.first) <
398 std::make_pair(b.second, b.first);
399 });
400 groups.push_back(std::move(pool.group));
401 }
402 return groups;
403}
404
405static SmallVector<DMAChannelAnalysis::BDGroup>
406tileBDGroups(const AIETargetModel &target, int col, int row) {
407 int numChannels = std::max(
408 target.getNumSourceSwitchboxConnections(col, row, WireBundle::DMA),
409 target.getNumDestSwitchboxConnections(col, row, WireBundle::DMA));
410 return DMAChannelAnalysis::bdGroups(target, col, row, numChannels);
411}
412
413std::optional<SmallVector<int>> DMAChannelAnalysis::planBDChannels(
414 const AIETargetModel &target, int col, int row, ArrayRef<BDPlanEnd> allEnds,
415 function_ref<bool(DMAChannelDir, int)> free,
416 function_ref<int64_t(DMAChannelDir, int)> spent) {
417 return planBDChannels(tileBDGroups(target, col, row), allEnds, free, spent);
418}
419
420std::optional<SmallVector<int>> DMAChannelAnalysis::planBDChannels(
421 ArrayRef<BDGroup> tileGroups, ArrayRef<BDPlanEnd> allEnds,
422 function_ref<bool(DMAChannelDir, int)> free,
423 function_ref<int64_t(DMAChannelDir, int)> spent) {
424 // The channels drawing from one BD pool share its ids, as bdRoom in
425 // aie-objectfifo-allocate counts them.
426 struct Group {
427 SmallVector<BDUser> users;
428 int64_t room = 0;
429 };
430 SmallVector<Group> groups;
431 for (const BDGroup &group : tileGroups) {
432 Group &added = groups.emplace_back(Group{group.users, group.size});
433 for (auto [dir, channel] : group.users)
434 added.room -= spent(dir, channel);
435 }
436
437 // An end pinning a channel takes it, whatever `free` says, and shares it
438 // with every end pinning it too; the rest are planned around them.
439 SmallVector<BDPlanEnd> ends;
440 SmallVector<unsigned> looseOf;
441 llvm::DenseSet<std::pair<int, int>> pinned;
442 for (auto [index, end] : llvm::enumerate(allEnds)) {
443 if (!end.pinned) {
444 ends.push_back(end);
445 looseOf.push_back(index);
446 continue;
447 }
448 BDUser user{end.dir, *end.pinned};
449 auto *group = llvm::find_if(groups, [&](const Group &group) {
450 return llvm::is_contained(group.users, user);
451 });
452 if (group == groups.end())
453 return std::nullopt;
454 group->room -= end.bds;
455 pinned.insert({static_cast<int>(end.dir), *end.pinned});
456 }
457 if (llvm::any_of(groups, [](const Group &group) { return group.room < 0; }))
458 return std::nullopt;
459 auto open = [&](DMAChannelDir dir, int channel) {
460 return free(dir, channel) &&
461 !pinned.contains({static_cast<int>(dir), channel});
462 };
463
464 // Each end goes to a group, the most demanding first; a choice stands when
465 // every group's ends fit its ids and, within a direction, take distinct free
466 // channels below their bounds: the tightest bound first, each the lowest
467 // channel left, which finds a matching whenever one exists since the
468 // allowed channels of any two ends nest.
469 SmallVector<unsigned> order(ends.size());
470 std::iota(order.begin(), order.end(), 0);
471 auto shape = [&](unsigned end) {
472 return std::make_tuple(-ends[end].bds, static_cast<int>(ends[end].dir),
473 ends[end].limit);
474 };
475 llvm::stable_sort(
476 order, [&](unsigned a, unsigned b) { return shape(a) < shape(b); });
477 SmallVector<unsigned> groupOf(ends.size());
478 SmallVector<int> channelOf(ends.size(), -1);
479 auto match = [&]() {
480 SmallVector<unsigned> byBound(ends.size());
481 std::iota(byBound.begin(), byBound.end(), 0);
482 llvm::stable_sort(byBound, [&](unsigned a, unsigned b) {
483 return ends[a].limit < ends[b].limit;
484 });
485 llvm::DenseSet<std::pair<int, int>> taken;
486 for (unsigned end : byBound) {
487 channelOf[end] = -1;
488 for (auto [userDir, channel] : groups[groupOf[end]].users) {
489 int dir = static_cast<int>(ends[end].dir);
490 if (userDir == ends[end].dir && channel < ends[end].limit &&
491 open(ends[end].dir, channel) &&
492 taken.insert({dir, channel}).second) {
493 channelOf[end] = channel;
494 break;
495 }
496 }
497 if (channelOf[end] < 0)
498 return false;
499 }
500 return true;
501 };
502 // The same nesting (bounds above) means a group's ends fit a direction
503 // exactly when, for every bound, no more of them have that bound or a
504 // tighter one than free channels lie below it. Checked as ends are placed:
505 // every completed choice matches, since no group ever holds more ends than
506 // it has channels.
507 SmallVector<int> bounds;
508 for (const BDPlanEnd &end : ends)
509 bounds.push_back(end.limit);
510 llvm::sort(bounds);
511 bounds.erase(llvm::unique(bounds), bounds.end());
512 size_t slots = 2 * bounds.size();
513 SmallVector<int64_t> below(groups.size() * slots, 0);
514 for (auto [g, group] : llvm::enumerate(groups))
515 for (DMAChannelDir dir : {DMAChannelDir::S2MM, DMAChannelDir::MM2S})
516 for (auto [i, bound] : llvm::enumerate(bounds))
517 for (auto [userDir, channel] : group.users)
518 below[g * slots + static_cast<int>(dir) * bounds.size() + i] +=
519 userDir == dir && channel < bound && open(dir, channel);
520 SmallVector<int64_t> held(groups.size() * slots, 0);
521 auto fits = [&](unsigned g, DMAChannelDir dir) {
522 size_t base = g * slots + static_cast<int>(dir) * bounds.size();
523 int64_t tighter = 0;
524 for (size_t i = 0; i < bounds.size(); ++i) {
525 tighter += held[base + i];
526 if (tighter > below[base + i])
527 return false;
528 }
529 return true;
530 };
531 // Over every group at once, too many ends of a direction and bound fail
532 // before any is placed.
533 for (DMAChannelDir dir : {DMAChannelDir::S2MM, DMAChannelDir::MM2S}) {
534 int64_t tighter = 0;
535 for (size_t i = 0; i < bounds.size(); ++i) {
536 int64_t room = 0;
537 for (size_t g = 0; g < groups.size(); ++g)
538 room += below[g * slots + static_cast<int>(dir) * bounds.size() + i];
539 tighter += llvm::count_if(ends, [&](const BDPlanEnd &end) {
540 return end.dir == dir && end.limit == bounds[i];
541 });
542 if (tighter > room)
543 return std::nullopt;
544 }
545 }
546 // Ends of one shape are interchangeable, so each takes a group no lower
547 // than the one before it of its shape.
548 std::function<bool(size_t)> place = [&](size_t next) {
549 if (next == order.size())
550 return match();
551 unsigned end = order[next];
552 size_t slot = static_cast<int>(ends[end].dir) * bounds.size() +
553 (llvm::lower_bound(bounds, ends[end].limit) - bounds.begin());
554 unsigned first = next > 0 && shape(order[next - 1]) == shape(end)
555 ? groupOf[order[next - 1]]
556 : 0;
557 for (unsigned g = first; g < groups.size(); ++g) {
558 if (groups[g].room < ends[end].bds)
559 continue;
560 ++held[g * slots + slot];
561 if (fits(g, ends[end].dir)) {
562 groupOf[end] = g;
563 groups[g].room -= ends[end].bds;
564 bool placed = place(next + 1);
565 groups[g].room += ends[end].bds;
566 if (placed) {
567 --held[g * slots + slot];
568 return true;
569 }
570 }
571 --held[g * slots + slot];
572 }
573 return false;
574 };
575 if (!place(0))
576 return std::nullopt;
577 SmallVector<int> result;
578 for (const BDPlanEnd &end : allEnds)
579 result.push_back(end.pinned ? *end.pinned : -1);
580 for (auto [loose, index] : llvm::enumerate(looseOf))
581 result[index] = channelOf[loose];
582 return result;
583}
584
586 ArrayRef<BDPlanEnd> ends, ArrayRef<unsigned> poolOf,
587 ArrayRef<BDWalkPool> pools, ArrayRef<bool> whole) {
588 SmallVector<int64_t> bds(pools.size(), 0);
589 for (auto [end, pool] : llvm::zip_equal(ends, poolOf))
590 bds[pool] += end.bds;
591 auto key = [&](unsigned pool) {
592 return std::make_tuple(pools[pool].depth, -pools[pool].objectBytes,
593 bds[pool]);
594 };
595 std::optional<unsigned> next;
596 for (unsigned pool = 0, e = pools.size(); pool < e; ++pool)
597 if (pools[pool].walkable && !whole[pool] &&
598 (!next || key(pool) > key(*next)))
599 next = pool;
600 return next;
601}
602
604 const AIETargetModel &target, int col, int row, ArrayRef<BDPlanEnd> ends,
605 ArrayRef<unsigned> poolOf, ArrayRef<BDWalkPool> pools,
606 function_ref<bool(DMAChannelDir, int)> free,
607 function_ref<int64_t(DMAChannelDir, int)> spent, unsigned maxSets) {
608 BDWalkSets result;
609 SmallVector<BDGroup> tileGroups = tileBDGroups(target, col, row);
610 auto none = [](DMAChannelDir, int) -> int64_t { return 0; };
611 auto fitsWalking = [&](ArrayRef<bool> whole, bool weighted) {
612 SmallVector<BDPlanEnd> planned;
613 for (auto [end, pool] : llvm::zip_equal(ends, poolOf))
614 planned.push_back({end.dir,
615 !weighted ? 0
616 : whole[pool] ? 1
617 : end.bds,
618 end.limit, end.pinned});
619 return planBDChannels(tileGroups, planned, free,
620 weighted
621 ? spent
622 : function_ref<int64_t(DMAChannelDir, int)>(none))
623 .has_value();
624 };
625 SmallVector<bool> whole(pools.size(), false);
626 if (!fitsWalking(whole, /*weighted=*/false)) {
627 result.channelShort = true;
628 return result;
629 }
630 if (fitsWalking(whole, /*weighted=*/true))
631 return result;
632
633 SmallVector<unsigned> ranked;
634 while (std::optional<unsigned> next =
635 nextPoolToWalk(ends, poolOf, pools, whole)) {
636 ranked.push_back(*next);
637 whole[*next] = true;
638 }
639 if (!fitsWalking(whole, /*weighted=*/true)) {
640 result.fits = false;
641 return result;
642 }
643 // Walking a pool only lowers its ends' BD ids, so a set holding one that
644 // fits fits too, without asking planBDChannels.
645 unsigned n = ranked.size();
646 assert(n < 32 && "each walkable pool draws a channel the plan above fit");
647 SmallVector<int64_t> maskBytes(uint32_t(1) << n, 0);
648 for (uint32_t mask = 1; mask < (uint32_t(1) << n); ++mask) {
649 const BDWalkPool &pool = pools[ranked[llvm::countr_zero(mask)]];
650 maskBytes[mask] =
651 maskBytes[mask & (mask - 1)] + pool.depth * pool.objectBytes;
652 }
653 auto bytes = [&](uint32_t mask) { return maskBytes[mask]; };
654 // The final order needs no plan, so masks are sorted into it before any
655 // are tested: a subset always has fewer or equal bytes and a lower
656 // popcount than its supersets, so it still sorts before them, and the
657 // fitsMask shortcut below still only ever looks back at masks already
658 // tested.
659 SmallVector<uint32_t> order;
660 for (uint32_t mask = 1; mask < (uint32_t(1) << n); ++mask)
661 order.push_back(mask);
662 llvm::stable_sort(order, [&](uint32_t a, uint32_t b) {
663 int64_t aBytes = bytes(a), bBytes = bytes(b);
664 if (aBytes != bBytes)
665 return aBytes < bBytes;
666 if (llvm::popcount(a) != llvm::popcount(b))
667 return llvm::popcount(a) < llvm::popcount(b);
668 // Of two sets alike in size, the one holding the first-ranked pool that
669 // only one holds.
670 uint32_t differ = a ^ b;
671 return differ && (a & differ & -differ);
672 });
673 llvm::BitVector fitsMask(uint32_t(1) << n);
674 for (uint32_t mask : order) {
675 if (result.sets.size() >= maxSets)
676 break;
677 bool fits = llvm::any_of(llvm::seq<unsigned>(0, n), [&](unsigned bit) {
678 return (mask >> bit & 1) && fitsMask.test(mask & ~(uint32_t(1) << bit));
679 });
680 if (!fits) {
681 llvm::fill(whole, false);
682 for (unsigned bit = 0; bit < n; ++bit)
683 if (mask >> bit & 1)
684 whole[ranked[bit]] = true;
685 fits = fitsWalking(whole, /*weighted=*/true);
686 }
687 if (fits) {
688 fitsMask.set(mask);
689 SmallVector<unsigned> set;
690 for (unsigned bit = 0; bit < n; ++bit)
691 if (mask >> bit & 1)
692 set.push_back(ranked[bit]);
693 result.sets.push_back(std::move(set));
694 result.bytes.push_back(bytes(mask));
695 }
696 }
697 return result;
698}
699
701 ArrayRef<SmallVector<int64_t>> bytes,
702 function_ref<bool(ArrayRef<unsigned>)> places, unsigned maxTries) {
703 using Choice = std::vector<unsigned>;
704 auto total = [&](const Choice &choice) {
705 int64_t sum = 0;
706 for (auto [tile, set] : llvm::enumerate(choice))
707 sum += bytes[tile][set];
708 return sum;
709 };
710 // Each tile's sets come cheapest first, so a choice's successors (one tile
711 // a set further) never cost less: popped in order, the first that places
712 // is the cheapest that does.
713 std::set<std::pair<int64_t, Choice>> frontier;
714 std::set<Choice> seen;
715 Choice first(bytes.size(), 0);
716 frontier.insert({total(first), first});
717 seen.insert(first);
718 WalkChoice result;
719 result.sets.assign(first.begin(), first.end());
720 for (unsigned tries = 0; !frontier.empty(); ++tries) {
721 if (tries == maxTries) {
722 result.stopped = true;
723 return result;
724 }
725 Choice choice = frontier.begin()->second;
726 frontier.erase(frontier.begin());
727 if (places(choice)) {
728 result.sets.assign(choice.begin(), choice.end());
729 result.placed = true;
730 return result;
731 }
732 for (unsigned tile = 0; tile < choice.size(); ++tile) {
733 if (choice[tile] + 1 >= bytes[tile].size())
734 continue;
735 Choice next = choice;
736 ++next[tile];
737 if (seen.insert(next).second)
738 frontier.insert({total(next), next});
739 }
740 }
741 return result;
742}
virtual uint32_t getBdPoolId(int col, int row, int channel, DMAChannelDir dir) const
Return the pool channel in direction dir draws its BDs from.
bool isBdChannelAccessible(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
uint32_t getNumDMAChannels(int col, int row, AIE::DMAChannelDir dir) const
Return the number of DMA channels a tile has in one direction.
virtual uint32_t getNumBDsInPool(int col, int row, uint32_t poolId) const
virtual uint32_t getNumDestSwitchboxConnections(int col, int row, WireBundle bundle) const =0
Return the number of destinations of connections inside a switchbox.
virtual uint32_t getNumSourceSwitchboxConnections(int col, int row, WireBundle bundle) const =0
Return the number of sources of connections inside a switchbox.
llvm::SmallVector< std::pair< int, int > > positions() const
Coordinates of the placed tiles that hold BD ids.
std::map< BDUser, int64_t > at(const AIETargetModel &target, int col, int row, llvm::ArrayRef< mlir::Operation * > tiles={}) const
By channel and direction, the ids held at (col, row) by tiles and by every tile with those coordinate...
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 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.
void forEachRuntimePinnedBdId(AIE::DeviceOp device, llvm::function_ref< void(Operation *op, Operation *tile, std::optional< int > channel, std::optional< AIE::DMAChannelDir > dir, int32_t id)> pinned)
Definition AIEUtils.cpp:599
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
const AIETargetModel & getTargetModel(mlir::Operation *op)
struct DMAChannel { DMAChannelDir direction; int channel; bool operator==(const DMAChannel &rhs) const { return std::tie(direction, channel)==std::tie(rhs.direction, rhs.channel); } } DMAChannel
Definition AIEDialect.h:320
The channels among 0..numChannels-1 at (col, row), per direction, grouped by BD pool; size is the poo...
A DMA end of one tile: its direction, the BD ids it takes, the exclusive upper bound on the channels ...
A pool whose ends a BD plan weighs: how many objects it holds, the bytes of one, and whether it can b...
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),...