MLIR-AIE 1.4.6.dev
AIECreatePathFindFlows.cpp
Go to the documentation of this file.
1//===- AIECreatePathfindFlows.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
14
15#include "mlir/IR/PatternMatch.h"
16#include "mlir/Pass/Pass.h"
17#include "mlir/Transforms/DialectConversion.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/EquivalenceClasses.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/SmallBitVector.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/MathExtras.h"
25
26#include <algorithm>
27#include <cstdint>
28#include <deque>
29#include <numeric>
30#include <optional>
31#include <set>
32
33using namespace mlir;
34using namespace xilinx;
35using namespace xilinx::AIE;
36
37#define DEBUG_TYPE "aie-create-pathfinder-flows"
38
39namespace xilinx::AIE {
40#define GEN_PASS_DEF_AIEROUTEPATHFINDERFLOWS
41#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
42} // namespace xilinx::AIE
43
44using PhysPort = std::pair<TileID, Port>;
45
46/// (mask, value, amsel) by slave port, in slot order.
48 std::map<PhysPort, SmallVector<std::tuple<int, int, int>, 2>>;
49
52 // The packet ids each tree carries.
53 std::map<PathEndPoint, std::set<int>> ids;
55};
56
57static PriorityRules priorityRules(DeviceOp d) {
58 const int numArbiters = d.getTargetModel().getNumArbiters();
59 AIEDialect::PriorityRouteAttrHelper priority(d.getContext());
60 PriorityRules rules;
61 for (SwitchboxOp box : d.getOps<SwitchboxOp>())
62 for (PacketRulesOp port : box.getOps<PacketRulesOp>())
63 for (PacketRuleOp rule : port.getRules().front().getOps<PacketRuleOp>())
64 if (priority.isAttrPresent(port) || priority.isAttrPresent(rule)) {
65 auto amsel = cast<AMSelOp>(rule.getAmsel().getDefiningOp());
66 rules[{box.getTileOp().getTileID(),
67 {port.getSourceBundle(), port.sourceIndex()}}]
68 .push_back(
69 {rule.maskInt(), rule.valueInt(),
70 amsel.arbiterIndex() + amsel.getMselValue() * numArbiters});
71 }
72 return rules;
73}
74
75// The backtracking searches for an arbiter plan and for a set of streams that
76// cannot share an arbiter are exact up to this many steps.
77constexpr int maxSearchSteps = 100000;
78// The hold-cycle search replans a tile at most this many times.
79constexpr int maxHoldCycleReplans = 256;
80
81static constexpr llvm::StringLiteral sharedReceiverCycleReason =
82 "Packet flows into receivers they share can deadlock holding arbiters "
83 "across switchboxes, and no routing found avoids it: ";
84static constexpr llvm::StringLiteral allowDeadlockProneHint =
85 " Set allow-deadlock-prone (aiecc --allow-deadlock-prone-routing) to "
86 "route them anyway.";
87
88namespace {
89struct PacketPlan;
90
91/// \brief Routes flows in a device by lowering them to stream-switch
92/// configurations.
93///
94/// Overall flow:
95/// 1. Report flows that can deadlock however they are routed.
96/// 2. Route the prioritized packet flows alone and pin their trees.
97/// 3. Route every flow with Pathfinder, planning the arbiters and packet rules
98/// on each routing found and steering off those that cannot be used,
99/// relaxing the packet constraints if no routing is found.
100/// 4. Lower the circuit flows to connects, and the packet flows as planned.
101/// 5. Add the wires between switchboxes and tiles.
102struct AIEPathfinderPass
103 : xilinx::AIE::impl::AIERoutePathfinderFlowsBase<AIEPathfinderPass> {
104 using Base =
105 xilinx::AIE::impl::AIERoutePathfinderFlowsBase<AIEPathfinderPass>;
106 AIEPathfinderPass() = default;
107 AIEPathfinderPass(const AIERoutePathfinderFlowsOptions &options)
108 : Base(options) {}
109 std::vector<std::pair<TileID, Port>> avoidedPorts;
110 void runOnOperation() override;
111 LogicalResult runOnFlow(DeviceOp d, DynamicTileAnalysis &analyzer);
112 /// Lowers the packet flows as `plan` says, on the routing `analyzer` found,
113 /// warning of a hold cycle left through receivers flows share if `warn`.
114 LogicalResult runOnPacketFlow(DeviceOp d, OpBuilder &builder,
115 DynamicTileAnalysis &analyzer,
116 const StreamConflicts &conflicts,
117 const PacketPlan &plan, bool warn);
118 llvm::Expected<PacketPlan> route(DeviceOp d, DynamicTileAnalysis &analyzer,
119 const StreamConflicts &conflicts,
120 const PinnedRoutes &pinned,
121 bool circuitSwitchHops,
122 bool prioritize = true);
123};
124
125// allocates channels between switchboxes ( but does not assign them)
126// instantiates shim-muxes AND allocates channels ( no need to rip these up in )
127struct ConvertFlowsToInterconnect : OpConversionPattern<FlowOp> {
128 using OpConversionPattern::OpConversionPattern;
129 DeviceOp &device;
130 DynamicTileAnalysis &analyzer;
131 ConvertFlowsToInterconnect(MLIRContext *context, DeviceOp &d,
132 DynamicTileAnalysis &a, PatternBenefit benefit = 1)
133 : OpConversionPattern(context, benefit), device(d), analyzer(a) {}
134
135 void addConnection(ConversionPatternRewriter &rewriter,
136 // could be a shim-mux or a switchbox.
137 Interconnect op, FlowOp flowOp, WireBundle inBundle,
138 int inIndex, WireBundle outBundle, int outIndex) const {
139
140 Region &r = op.getConnections();
141 Block &b = r.front();
142 auto point = rewriter.saveInsertionPoint();
143 rewriter.setInsertionPoint(b.getTerminator());
144
145 ConnectOp::create(rewriter, flowOp.getLoc(), inBundle, inIndex, outBundle,
146 outIndex);
147
148 rewriter.restoreInsertionPoint(point);
149
150 LLVM_DEBUG(llvm::dbgs()
151 << "\t\taddConnection() (" << op.colIndex() << ","
152 << op.rowIndex() << ") " << stringifyWireBundle(inBundle)
153 << inIndex << " -> " << stringifyWireBundle(outBundle)
154 << outIndex << "\n");
155 }
156
157 mlir::LogicalResult
158 matchAndRewrite(FlowOp flowOp, OpAdaptor adaptor,
159 ConversionPatternRewriter &rewriter) const override {
160 Operation *Op = flowOp.getOperation();
161 DeviceOp d = flowOp->getParentOfType<DeviceOp>();
162 if (!d) {
163 flowOp->emitOpError("This operation must be contained within a device");
164 return failure();
165 }
166 rewriter.setInsertionPoint(d.getBody()->getTerminator());
167
168 auto srcTile = cast<TileOp>(flowOp.getSource().getDefiningOp());
169 TileID srcCoords = {srcTile.colIndex(), srcTile.rowIndex()};
170 auto srcBundle = flowOp.getSourceBundle();
171 auto srcChannel = flowOp.getSourceChannel();
172 Port srcPort = {srcBundle, srcChannel};
173
174 LLVM_DEBUG({
175 auto dstTile = cast<TileOp>(flowOp.getDest().getDefiningOp());
176 llvm::dbgs() << "\n\t---Begin rewrite() for flowOp: (" << srcCoords.col
177 << ", " << srcCoords.row << ")"
178 << stringifyWireBundle(srcBundle) << srcChannel << " -> ("
179 << dstTile.colIndex() << ", " << dstTile.rowIndex() << ")"
180 << stringifyWireBundle(flowOp.getDestBundle())
181 << flowOp.getDestChannel() << "\n\t";
182 });
183
184 // if the flow (aka "net") for this FlowOp hasn't been processed yet,
185 // add all switchbox connections to implement the flow
186 TileID srcSbId = {srcCoords.col, srcCoords.row};
187 PathEndPoint srcPoint = {srcSbId, srcPort};
188 if (analyzer.processedFlows.count(srcPoint)) {
189 // This FlowOp is a broadcast sibling of a flow whose route was already
190 // materialized (the analyzer merges all destinations sharing a source
191 // into one net, so the first sibling emitted connections for every
192 // destination). Erase it and report success so the erase is committed.
193 LLVM_DEBUG(llvm::dbgs() << "Flow already processed!\n");
194 rewriter.eraseOp(Op);
195 return success();
196 }
197 const SwitchSettings &settings = analyzer.routing.settings.at(srcPoint);
198 // add connections for all the Switchboxes in SwitchSettings
199 for (const auto &[tileId, setting] : settings) {
200 int col = tileId.col;
201 int row = tileId.row;
202 SwitchboxOp swOp = analyzer.getSwitchbox(rewriter, col, row);
203 int shimCh = srcChannel;
204 TileOp tileOp = analyzer.getTile(rewriter, tileId);
205 bool viaShimMux = getTargetModel(tileOp).hasShimMux(col, row);
206
207 // TODO: must reserve N3, N7, S2, S3 for DMA connections
208 bool srcUsesShimMux = srcBundle == WireBundle::DMA ||
209 srcBundle == WireBundle::PLIO ||
210 srcBundle == WireBundle::NOC;
211 if (viaShimMux && tileId == srcSbId && srcUsesShimMux) {
212
213 shimCh = shimMuxChannelFrom(srcPort);
214 ShimMuxOp shimMuxOp = analyzer.getShimMux(rewriter, col);
215 addConnection(rewriter, cast<Interconnect>(shimMuxOp.getOperation()),
216 flowOp, srcBundle, srcChannel, WireBundle::North, shimCh);
217 }
218 assert(setting.srcs.size() == setting.dsts.size());
219 for (size_t i = 0; i < setting.srcs.size(); i++) {
220 Port src = setting.srcs[i];
221 Port dest = setting.dsts[i];
222
223 // A flow can start and end at one shim (see shimMuxChannelFrom).
224 if (viaShimMux && tileId == srcSbId && srcUsesShimMux && src == srcPort)
225 src = {WireBundle::South, shimCh};
226 if (viaShimMux && (dest.bundle == WireBundle::DMA ||
227 dest.bundle == WireBundle::PLIO ||
228 dest.bundle == WireBundle::NOC)) {
229 int destCh = shimMuxChannelTo(dest);
230
231 ShimMuxOp shimMuxOp = analyzer.getShimMux(rewriter, col);
232 addConnection(rewriter, cast<Interconnect>(shimMuxOp.getOperation()),
233 flowOp, WireBundle::North, destCh, dest.bundle,
234 dest.channel);
235 dest = {WireBundle::South, destCh};
236 }
237 addConnection(rewriter, cast<Interconnect>(swOp.getOperation()), flowOp,
238 src.bundle, src.channel, dest.bundle, dest.channel);
239 }
240
241 LLVM_DEBUG(llvm::dbgs() << tileId << ": " << setting << " | " << "\n");
242 }
243
244 LLVM_DEBUG(llvm::dbgs()
245 << "\n\t\tFinished adding ConnectOps to implement flowOp.\n");
246
247 analyzer.processedFlows.insert(srcPoint);
248 rewriter.eraseOp(Op);
249 return success();
250 }
251};
252
253} // namespace
254
255LogicalResult AIEPathfinderPass::runOnFlow(DeviceOp d,
256 DynamicTileAnalysis &analyzer) {
257 // Apply rewrite rule to switchboxes to add assignments to every 'connect'
258 // operation inside
259 ConversionTarget target(getContext());
260 target.addLegalOp<TileOp>();
261 target.addLegalOp<ConnectOp>();
262 target.addLegalOp<SwitchboxOp>();
263 target.addLegalOp<ShimMuxOp>();
264 target.addLegalOp<EndOp>();
265
266 RewritePatternSet patterns(&getContext());
267 patterns.insert<ConvertFlowsToInterconnect>(d.getContext(), d, analyzer);
268 if (failed(applyPartialConversion(d, target, std::move(patterns))))
269 return failure();
270 return success();
271}
272
273/// Whether the connection out of `out` at `tile` leads, through `settings`, to
274/// `finalPort` at `finalTile`.
275static bool findPathToDest(const SwitchSettings &settings, TileID tile,
276 Port out, TileID finalTile, Port finalPort) {
277 if (tile == finalTile && out == finalPort)
278 return true;
279 std::optional<std::pair<TileID, Port>> next = getLinkedInput(tile, out);
280 if (!next)
281 return false;
282 TileID neighbour = next->first;
283 Port in = next->second;
284 auto setting = settings.find(neighbour);
285 if (setting == settings.end())
286 return false;
287 return llvm::any_of(
288 llvm::zip(setting->second.srcs, setting->second.dsts), [&](auto link) {
289 auto [src, dest] = link;
290 return src == in &&
291 findPathToDest(settings, neighbour, dest, finalTile, finalPort);
292 });
293}
294
295/// Every node `successors` reaches from `start`, with the node a breadth-first
296/// search first reaches it from; `start` maps to itself. Stops once `goal` is
297/// reached, if given.
298template <typename Node, typename Successors>
299static std::map<Node, Node>
300breadthFirstParents(Node start, Successors successors,
301 std::optional<Node> goal = std::nullopt) {
302 std::map<Node, Node> parent{{start, start}};
303 std::deque<Node> work{start};
304 while (!work.empty() && !(goal && parent.count(*goal))) {
305 Node u = work.front();
306 work.pop_front();
307 for (Node v : successors(u))
308 if (parent.try_emplace(v, u).second)
309 work.push_back(v);
310 }
311 return parent;
312}
313
314namespace {
315struct CoverCube {
316 int mask;
317 int value;
318 // cov[i] is set iff this cube matches match id i.
319 llvm::SmallBitVector cov;
320};
321} // namespace
322
323// Minimum set cover by branch-and-bound: find the fewest `cubes` whose coverage
324// (cube.cov) unions to every match id still set in `uncovered`. `sel` is the
325// current partial pick; `bestSel`/`bestSize` hold the smallest full cover so
326// far and are updated in place.
327static void bnbMinCover(ArrayRef<CoverCube> cubes,
328 const llvm::SmallBitVector &uncovered,
329 SmallVectorImpl<int> &sel, int &bestSize,
330 SmallVectorImpl<int> &bestSel) {
331
332 // base case
333 if (uncovered.none()) {
334 if (static_cast<int>(sel.size()) < bestSize) {
335 bestSize = static_cast<int>(sel.size());
336 bestSel.assign(sel.begin(), sel.end());
337 }
338 return;
339 }
340
341 // bound: adding a cube would only tie the best
342 if (static_cast<int>(sel.size()) + 1 >= bestSize) {
343 return;
344 }
345
346 // most constrained variable: find the least-covered, uncovered matchId
347 int pick = -1;
348 int pickCount = static_cast<int>(cubes.size()) + 1;
349
350 for (int id = uncovered.find_first(); id != -1;
351 id = uncovered.find_next(id)) {
352 int c = 0;
353
354 for (const CoverCube &cb : cubes) {
355 if (cb.cov.test(id)) {
356 c++;
357 }
358 }
359
360 if (c < pickCount) {
361 pickCount = c;
362 pick = id;
363 }
364 }
365
366 // branch: try each cube that covers the chosen id, recursing on the rest.
367 for (int i = 0; i < static_cast<int>(cubes.size()); ++i) {
368 if (!cubes[i].cov.test(pick)) {
369 continue;
370 }
371
372 sel.push_back(i);
373 llvm::SmallBitVector next = uncovered;
374 next.reset(cubes[i].cov); // next &= ~cov
375 bnbMinCover(cubes, next, sel, bestSize, bestSel);
376 sel.pop_back();
377 }
378}
379
380static bool cubesIntersect(std::pair<int, int> a, std::pair<int, int> b) {
381 return ((a.second ^ b.second) & a.first & b.first) == 0;
382}
383
384// Cover `matchIds` (a group's packet ids) with the fewest (mask, value) rules
385// that match every specified id and no cube in `avoidCubes` (what the other
386// groups on the same slave port claim). A rule matches id x iff
387// (x & mask) == value; ids no cube claims are don't-cares, free to over-claim.
388//
389// Based on Quine-McCluskey:
390// 1. Enumerate prime implicants: maximal cubes (a cube is one (mask, value))
391// that match >=1 matchIds and no avoid cube.
392// 2. Pick the fewest of those cubes that cover all match ids (bnbMinCover).
393// 3. Tighten each chosen cube to the smallest enclosing cube of the ids it
394// took, so it claims no more don't-cares than necessary; the one-cube case
395// reduces to the old common-bits mask.
396static SmallVector<std::pair<int, int>>
397computeSubcubeCover(const SmallVector<int, 4> &matchIds,
398 ArrayRef<std::pair<int, int>> avoidCubes, int idBits) {
399
400 // id space and full mask, sized from the target's packet-id width.
401 const int numIds = 1 << idBits;
402 const int idMask = numIds - 1;
403
404 auto hitsAvoid = [&](int mask, int value) {
405 return llvm::any_of(avoidCubes, [&](std::pair<int, int> c) {
406 return cubesIntersect({mask, value}, c);
407 });
408 };
409
410 llvm::SmallBitVector matchMask(numIds);
411 for (int id : matchIds) {
412 matchMask.set(id);
413 }
414
415 // phase 1: enumerate prime implicants. small (3^idBits), so brute force.
416 SmallVector<CoverCube> primes;
417 for (int mask = 0; mask < numIds; ++mask) {
418 for (int value = 0; value < numIds; ++value) {
419 // valid cube := value covered by mask, avoids properly
420 if ((value & mask) != value) {
421 continue;
422 }
423 if (hitsAvoid(mask, value)) {
424 continue;
425 }
426
427 // record covering
428 llvm::SmallBitVector cov(numIds);
429 for (int id : matchIds) {
430 if ((id & mask) == value) {
431 cov.set(id);
432 }
433 }
434
435 if (cov.none()) {
436 continue;
437 }
438
439 // prime = maximal, i.e., no checked mask bit can be dropped without
440 // covering an avoidId.
441 bool isPrime = true;
442 for (int b = 0; b < idBits; ++b) {
443 if (!((mask >> b) & 1)) {
444 continue;
445 }
446
447 if (!hitsAvoid(mask & ~(1 << b), value & ~(1 << b))) {
448 isPrime = false;
449 break;
450 }
451 }
452
453 if (isPrime) {
454 primes.push_back({mask, value, std::move(cov)});
455 }
456 }
457 }
458
459 // phase 2: pick the fewest primes that cover every match id (bnb).
460 SmallVector<int> sel, bestSel;
461 int bestSize = static_cast<int>(matchIds.size()) + 1;
462
463 bnbMinCover(primes, matchMask, sel, bestSize, bestSel);
464
465 SmallVector<std::pair<int, int>> chosen;
466 for (int i : bestSel) {
467 chosen.push_back({primes[i].mask, primes[i].value});
468 }
469
470 if (chosen.empty()) {
471 // unreachable: a single-id cube always covers
472 for (int id : matchIds) {
473 chosen.push_back({idMask, id});
474 }
475 }
476
477 // phase 3: tighten each chosen cube to match only the ids it took.
478 // maximal -> over-claim don't-cares -> more mask bits narrow the cube.
479 //
480 // e.g., {2,4} avoid {0}:
481 // prime (mask 00010, value 00010): 2 & 00010 = 00010 == value -> hit
482 // 6 & 00010 = 00010 == value -> also hit
483 // tight (mask 11111, value 00010): 2 & 11111 = 00010 == value -> hit
484 // 6 & 11111 = 00110 != value -> dropped
485 // 0 & 11111 = 00000 != value -> avoided
486
487 SmallVector<SmallVector<int, 4>, 4> assigned(chosen.size());
488 for (int id : matchIds) {
489 for (int c = 0; c < static_cast<int>(chosen.size()); ++c) {
490 if ((id & chosen[c].first) == chosen[c].second) {
491 assigned[c].push_back(id);
492 break;
493 }
494 }
495 }
496
497 SmallVector<std::pair<int, int>> cover;
498 for (const SmallVector<int, 4> &ids : assigned) {
499 if (ids.empty()) {
500 continue;
501 }
502
503 int mask = idMask;
504 for (int i = 0; i < idBits; ++i) {
505 int bit = (ids.front() >> i) & 1;
506 for (int id : ids) {
507 if (((id >> i) & 1) != bit) {
508 mask &= ~(1 << i);
509 break;
510 }
511 }
512 }
513 cover.push_back({mask, ids.front() & mask});
514 }
515
516 return cover;
517}
518
519// A group's rules (see GroupClaims): the stated ones, then a cover of the
520// derived ids that avoids them and `avoid`, whatever else claims ids on the
521// port.
522static SmallVector<std::pair<int, int>>
523groupRules(ArrayRef<std::pair<int, int>> stated, ArrayRef<int> derived,
524 ArrayRef<std::pair<int, int>> avoid, int idBits) {
525 SmallVector<std::pair<int, int>> rules(stated);
526 if (derived.empty())
527 return rules;
528 SmallVector<std::pair<int, int>> derivedAvoid(avoid);
529 derivedAvoid.append(stated.begin(), stated.end());
530 llvm::append_range(rules, computeSubcubeCover(SmallVector<int, 4>(derived),
531 derivedAvoid, idBits));
532 return rules;
533}
534
535namespace {
536struct GroupClaims {
537 ArrayRef<std::pair<int, int>> stated;
538 ArrayRef<int> derived;
539 bool priority = false;
540};
541
542/// A packet rule of a slave port, and the group it selects.
543struct PortRule {
544 int mask;
545 int value;
546 size_t group;
547};
548} // namespace
549
550static uint64_t cubeIds(int mask, int value, int idBits) {
551 uint64_t ids = 0;
552 for (int id = 0; id < (1 << idBits); ++id)
553 if ((id & mask) == (value & mask))
554 ids |= uint64_t(1) << id;
555 return ids;
556}
557
558// The fewest rules, at most `budget`, that send every id a group claims to
559// that group, where a packet takes the first rule it matches. A rule may then
560// claim ids of another group that an earlier rule already takes.
561static std::optional<SmallVector<PortRule>>
562orderedRules(ArrayRef<GroupClaims> groups,
563 ArrayRef<std::pair<int, int>> existing, int idBits,
564 size_t budget) {
565 if (idBits > 6)
566 return std::nullopt;
567 const int idMask = (1 << idBits) - 1;
568 SmallVector<uint64_t> claims;
569 for (const GroupClaims &group : groups) {
570 uint64_t ids = 0;
571 for (auto [mask, value] : group.stated)
572 ids |= cubeIds(mask, value, idBits);
573 for (int id : group.derived)
574 ids |= uint64_t(1) << id;
575 claims.push_back(ids);
576 }
577 uint64_t claimed = 0;
578 for (uint64_t ids : claims)
579 claimed |= ids;
580 uint64_t taken = 0;
581 for (auto [mask, value] : existing)
582 taken |= cubeIds(mask, value, idBits);
583 if (taken & claimed)
584 return std::nullopt;
585 SmallVector<uint64_t> cubes;
586 for (int mask = 0; mask <= idMask; ++mask)
587 for (int value = 0; value <= idMask; ++value)
588 if ((value & mask) == value)
589 cubes.push_back(cubeIds(mask, value, idBits));
590
591 // A rule is worth only the claimed ids it newly takes, all of one group, so
592 // the tightest cube around them serves, and fewer ids of the same group
593 // never serve better.
594 SmallVector<PortRule> rules;
595 std::set<std::pair<uint64_t, size_t>> dead;
596 auto search = [&](auto &self, uint64_t taken, size_t left) -> bool {
597 uint64_t open = claimed & ~taken;
598 size_t openGroups =
599 llvm::count_if(claims, [&](uint64_t ids) { return ids & open; });
600 if (openGroups == 0)
601 return true;
602 if (openGroups > left || dead.count({taken, left}))
603 return false;
604 SmallVector<std::pair<uint64_t, size_t>> moves;
605 for (uint64_t cube : cubes)
606 for (auto [g, ids] : llvm::enumerate(claims))
607 if ((cube & open) && (cube & open & ~ids) == 0 &&
608 !llvm::is_contained(moves, std::pair{cube & open, g}))
609 moves.push_back({cube & open, g});
610 llvm::stable_sort(moves, [](auto a, auto b) {
611 return llvm::popcount(a.first) > llvm::popcount(b.first);
612 });
613 SmallVector<std::pair<uint64_t, size_t>> tried;
614 for (auto [own, g] : moves) {
615 if (llvm::any_of(tried, [&, own = own, g = g](auto t) {
616 return t.second == g && (t.first & own) == own;
617 }))
618 continue;
619 tried.push_back({own, g});
620 int all = idMask, any = 0;
621 for (int id = 0; id <= idMask; ++id)
622 if ((own >> id) & 1) {
623 all &= id;
624 any |= id;
625 }
626 int mask = idMask & ~(all ^ any);
627 rules.push_back({mask, all, g});
628 if (self(self, taken | own, left - 1))
629 return true;
630 rules.pop_back();
631 }
632 dead.insert({taken, left});
633 return false;
634 };
635 for (size_t length = 1; length <= budget; ++length)
636 if (search(search, taken, length))
637 return rules;
638 return std::nullopt;
639}
640
641// The rules of a slave port, in slot order after the `existing` ones. Each
642// group takes its own cover, which claims no id another group claims, unless
643// those outnumber the free slots and first-match order fits them.
644static SmallVector<PortRule> portRules(ArrayRef<GroupClaims> groups,
645 ArrayRef<std::pair<int, int>> existing,
646 int idBits, size_t slots) {
647 const int idMask = (1 << idBits) - 1;
648 SmallVector<PortRule> rules;
649 for (auto [g, group] : llvm::enumerate(groups)) {
650 SmallVector<std::pair<int, int>> avoid(existing);
651 for (auto [o, other] : llvm::enumerate(groups)) {
652 if (o == g)
653 continue;
654 avoid.append(other.stated.begin(), other.stated.end());
655 for (int id : other.derived)
656 avoid.push_back({idMask, id});
657 }
658 for (auto [mask, value] :
659 groupRules(group.stated, group.derived, avoid, idBits))
660 rules.push_back({mask, value, g});
661 }
662 if (existing.size() + rules.size() <= slots || existing.size() >= slots)
663 return rules;
664 if (std::optional<SmallVector<PortRule>> ordered =
665 orderedRules(groups, existing, idBits, slots - existing.size()))
666 return *ordered;
667 return rules;
668}
669
670static SmallVector<PortRule>
671slavePortRules(ArrayRef<GroupClaims> groups,
672 ArrayRef<std::pair<int, int>> existing, int idBits,
673 size_t slots) {
674 SmallVector<std::pair<int, int>> taken(existing);
675 SmallVector<PortRule> rules;
676 for (bool priority : {true, false}) {
677 SmallVector<size_t, 4> members;
678 SmallVector<GroupClaims> claims;
679 for (auto [g, group] : llvm::enumerate(groups))
680 if (group.priority == priority) {
681 members.push_back(g);
682 claims.push_back(group);
683 }
684 if (claims.empty())
685 continue;
686 for (const PortRule &r : portRules(claims, taken, idBits, slots))
687 rules.push_back({r.mask, r.value, members[r.group]});
688 for (const PortRule &r : rules)
689 if (groups[r.group].priority == priority)
690 taken.push_back({r.mask, r.value});
691 }
692 return rules;
693}
694
695namespace {
696/// Packets with one id entering a switchbox on one slave port, and the master
697/// ports they leave by.
698struct SlaveFlow {
699 Port slave;
700 int id;
701 SmallVector<Port, 4> masters;
702 bool isPriority;
703};
704
705/// The amsel each slave flow takes, and the master ports each amsel selects
706/// (see planArbiters).
707struct ArbiterPlan {
708 std::map<std::pair<Port, int>, int> slaveAmsels;
709 std::map<int, SmallVector<Port, 4>> amselMasters;
710};
711
712/// The master ports `flows` tie to one arbiter: a slave flow's arbiter takes
713/// every master port it leaves by (see planArbiters).
714template <typename SlaveFlows>
715llvm::EquivalenceClasses<Port> tiedMasters(SlaveFlows &&flows) {
716 llvm::EquivalenceClasses<Port> tied;
717 for (const SlaveFlow &f : flows)
718 for (Port m : f.masters)
719 tied.unionSets(f.masters.front(), m);
720 return tied;
721}
722
723/// Chooses arbiters for a switchbox's slave flows so that no two flows that
724/// can deadlock (`conflict`) and enter on different slave ports share one.
725/// A master port is tied to one arbiter, so every master port a slave flow
726/// leaves by takes that flow's arbiter; the master ports linked that way form
727/// a unit, and each master set in a unit takes an msel. A flow never takes
728/// an arbiter `excluded` rules out for it. Units are colored onto arbiters by
729/// backtracking, which is exact up to a step budget. On failure, fills
730/// `blocking` with the conflicting pairs that stood in the way; it stays empty
731/// when the master sets alone outnumber the free msels.
732std::optional<ArbiterPlan>
733planArbiters(const AIETargetModel &targetModel, ArrayRef<SlaveFlow> flows,
734 llvm::function_ref<bool(size_t, size_t)> conflict,
735 llvm::function_ref<bool(size_t, int)> excluded,
736 const std::set<int> &reservedAmsels,
737 SmallVectorImpl<std::pair<size_t, size_t>> &blocking) {
738 const int numArbiters = targetModel.getNumArbiters();
739 const int numMselsPerArbiter = targetModel.getNumMselsPerArbiter();
740 auto amselOf = [&](int arbiter, int msel) {
741 return arbiter + msel * numArbiters;
742 };
743
744 llvm::EquivalenceClasses<Port> tied = tiedMasters(flows);
745
746 struct Unit {
747 SmallVector<size_t, 4> flows;
748 SmallVector<SmallVector<Port, 4>, 2> masterSets;
749 bool isPriority = false;
750 };
751 std::vector<Unit> units;
752 std::map<Port, size_t> unitOf;
753 SmallVector<size_t, 8> flowUnit;
754 for (auto [i, f] : llvm::enumerate(flows)) {
755 auto [it, inserted] =
756 unitOf.try_emplace(tied.getLeaderValue(f.masters.front()), 0);
757 if (inserted) {
758 it->second = units.size();
759 units.emplace_back();
760 }
761 Unit &unit = units[it->second];
762 flowUnit.push_back(it->second);
763 unit.flows.push_back(i);
764 unit.isPriority |= f.isPriority;
765 if (!llvm::is_contained(unit.masterSets, f.masters))
766 unit.masterSets.push_back(f.masters);
767 }
768 for (Unit &unit : units) {
769 auto *priorityEnd = std::stable_partition(
770 unit.masterSets.begin(), unit.masterSets.end(),
771 [&](const SmallVector<Port, 4> &masters) {
772 return llvm::any_of(unit.flows, [&](size_t f) {
773 return flows[f].isPriority && flows[f].masters == masters;
774 });
775 });
776 std::sort(unit.masterSets.begin(), priorityEnd);
777 }
778
779 auto clash = [&](size_t a, size_t b) {
780 return flows[a].slave != flows[b].slave && conflict(a, b);
781 };
782 for (const Unit &unit : units)
783 for (auto [k, a] : llvm::enumerate(unit.flows))
784 for (size_t b : llvm::drop_begin(unit.flows, k + 1))
785 if (clash(a, b))
786 blocking.push_back({a, b});
787 if (!blocking.empty())
788 return std::nullopt;
789
790 std::vector<llvm::SmallDenseSet<size_t, 4>> neighbors(units.size());
791 SmallVector<std::pair<size_t, size_t>, 4> crossPairs;
792 for (size_t a = 0; a < flows.size(); a++)
793 for (size_t b = a + 1; b < flows.size(); b++)
794 if (flowUnit[a] != flowUnit[b] && clash(a, b)) {
795 neighbors[flowUnit[a]].insert(flowUnit[b]);
796 neighbors[flowUnit[b]].insert(flowUnit[a]);
797 crossPairs.push_back({a, b});
798 }
799
800 SmallVector<SmallVector<int, 4>, 6> freeMsels(numArbiters);
801 SmallVector<SmallVector<size_t, 4>, 6> excludedUnits(numArbiters);
802 for (int a = 0; a < numArbiters; a++) {
803 for (int m = 0; m < numMselsPerArbiter; m++)
804 if (!reservedAmsels.count(amselOf(a, m)))
805 freeMsels[a].push_back(m);
806 for (size_t f = 0; f < flows.size(); f++)
807 if (excluded(f, a) && !llvm::is_contained(excludedUnits[a], flowUnit[f]))
808 excludedUnits[a].push_back(flowUnit[f]);
809 }
810 size_t mostFree = 0;
811 for (const SmallVector<int, 4> &free : freeMsels)
812 mostFree = std::max(mostFree, free.size());
813 if (llvm::any_of(units, [&](const Unit &unit) {
814 return unit.masterSets.size() > mostFree;
815 }))
816 return std::nullopt;
817
818 // Most constrained first.
819 SmallVector<size_t, 8> order(units.size());
820 std::iota(order.begin(), order.end(), 0);
821 llvm::stable_sort(order, [&](size_t a, size_t b) {
822 return std::make_pair(neighbors[a].size(), units[a].masterSets.size()) >
823 std::make_pair(neighbors[b].size(), units[b].masterSets.size());
824 });
825
826 SmallVector<int, 8> arbiterOf(units.size(), -1);
827 SmallVector<size_t, 6> load(numArbiters, 0);
828 int steps = 0;
829 auto place = [&](auto &self, size_t depth) -> bool {
830 if (depth == order.size())
831 return true;
832 if (++steps > maxSearchSteps) {
833 LLVM_DEBUG(llvm::dbgs() << "Arbiter search gave up after "
834 << maxSearchSteps << " steps\n");
835 return false;
836 }
837 size_t u = order[depth];
838 SmallVector<int, 6> candidates(numArbiters);
839 std::iota(candidates.begin(), candidates.end(), 0);
840 if (units[u].isPriority)
841 std::reverse(candidates.begin(), candidates.end());
842 else
843 llvm::stable_sort(candidates, [&](int a, int b) {
844 return load[a] + numMselsPerArbiter - freeMsels[a].size() <
845 load[b] + numMselsPerArbiter - freeMsels[b].size();
846 });
847 std::set<std::pair<size_t, SmallVector<size_t, 4>>> triedEmpty;
848 for (int a : candidates) {
849 if (load[a] + units[u].masterSets.size() > freeMsels[a].size())
850 continue;
851 if (llvm::is_contained(excludedUnits[a], u) ||
852 llvm::any_of(neighbors[u],
853 [&](size_t v) { return arbiterOf[v] == a; }))
854 continue;
855 // Empty arbiters with as many free msels, ruled out for the same units,
856 // are interchangeable.
857 if (load[a] == 0 &&
858 !triedEmpty.insert({freeMsels[a].size(), excludedUnits[a]}).second)
859 continue;
860 arbiterOf[u] = a;
861 load[a] += units[u].masterSets.size();
862 if (self(self, depth + 1))
863 return true;
864 load[a] -= units[u].masterSets.size();
865 arbiterOf[u] = -1;
866 }
867 return false;
868 };
869 if (!place(place, 0)) {
870 blocking.append(crossPairs.begin(), crossPairs.end());
871 return std::nullopt;
872 }
873
874 SmallVector<size_t, 8> mselOrder(units.size());
875 std::iota(mselOrder.begin(), mselOrder.end(), 0);
876 llvm::stable_sort(mselOrder, [&](size_t a, size_t b) {
877 if (!units[a].isPriority || !units[b].isPriority)
878 return units[a].isPriority > units[b].isPriority;
879 return units[a].masterSets.front() < units[b].masterSets.front();
880 });
881 ArbiterPlan plan;
882 SmallVector<size_t, 6> low(numArbiters, 0), high(numArbiters, 0);
883 for (size_t u : mselOrder) {
884 const Unit &unit = units[u];
885 int a = arbiterOf[u];
886 std::map<SmallVector<Port, 4>, int> setAmsel;
887 for (const SmallVector<Port, 4> &masters : unit.masterSets) {
888 int msel = unit.isPriority
889 ? freeMsels[a][freeMsels[a].size() - 1 - high[a]++]
890 : freeMsels[a][low[a]++];
891 setAmsel[masters] = amselOf(a, msel);
892 plan.amselMasters[amselOf(a, msel)] = masters;
893 }
894 for (size_t f : unit.flows)
895 plan.slaveAmsels[{flows[f].slave, flows[f].id}] =
896 setAmsel.at(flows[f].masters);
897 }
898 return plan;
899}
900
901/// The tiles other than `src` and `dst` that every route between them passes.
902SmallVector<TileID> cutTiles(const AIETargetModel &targetModel, TileID src,
903 TileID dst) {
904 auto neighbors = [&](TileID t) {
905 SmallVector<TileID, 4> next;
906 for (auto [bundle, dc, dr] : {std::tuple{WireBundle::North, 0, 1},
907 {WireBundle::South, 0, -1},
908 {WireBundle::East, 1, 0},
909 {WireBundle::West, -1, 0}}) {
910 TileID n{t.col + dc, t.row + dr};
911 if (n.col >= 0 && n.col < targetModel.columns() && n.row >= 0 &&
912 n.row < targetModel.rows() &&
913 targetModel.getNumDestSwitchboxConnections(t.col, t.row, bundle) > 0)
914 next.push_back(n);
915 }
916 return next;
917 };
918 auto reach = [&](std::optional<TileID> avoid) {
919 return breadthFirstParents(
920 src,
921 [&](TileID t) {
922 SmallVector<TileID, 4> next = neighbors(t);
923 llvm::erase(next, avoid);
924 return next;
925 },
926 std::optional{dst});
927 };
928 std::map<TileID, TileID> via = reach(std::nullopt);
929 if (!via.count(dst))
930 return {};
931 SmallVector<TileID> interior;
932 for (TileID t = via.at(dst); t != src; t = via.at(t))
933 interior.push_back(t);
934 llvm::erase_if(interior, [&](TileID t) { return reach(t).count(dst) > 0; });
935 return interior;
936}
937
938/// The tile, port and id of each packet a prioritized flow (priority_route)
939/// sends.
940struct PrioritizedPackets {
941 std::set<std::tuple<TileID, Port, int>> packets;
942 bool contains(const RoutedStream &s) const {
943 return s.packetID && packets.count({s.src.tile, s.src.port, *s.packetID});
944 }
945};
946
947PrioritizedPackets prioritizedPackets(DeviceOp device) {
948 PrioritizedPackets prioritized;
949 for (PacketFlowOp flow : device.getOps<PacketFlowOp>())
950 if (flow.getPriorityRoute().value_or(false))
951 for (auto src : flow.getPorts().getOps<PacketSourceOp>())
952 prioritized.packets.insert(
953 {cast<TileOp>(src.getTile().getDefiningOp()).getTileID(),
954 src.port(), flow.IDInt()});
955 return prioritized;
956}
957
958/// The largest set of `candidates` that must be kept apart pairwise
959/// (StreamConflicts::mustSeparate). The search stops once it finds one larger
960/// than `limit` or runs out of steps.
961SmallVector<size_t, 8> largestApartSet(const StreamConflicts &conflicts,
962 ArrayRef<size_t> candidates,
963 size_t limit) {
964 SmallVector<size_t, 8> clique, best;
965 int steps = 0;
966 auto grow = [&](auto &self, ArrayRef<size_t> cands) -> void {
967 if (clique.size() > best.size())
968 best = clique;
969 for (auto [k, s] : llvm::enumerate(cands)) {
970 if (best.size() > limit || ++steps > maxSearchSteps ||
971 clique.size() + cands.size() - k <= best.size())
972 return;
973 SmallVector<size_t, 8> next;
974 for (size_t t : cands.drop_front(k + 1))
975 if (conflicts.mustSeparate(s, t))
976 next.push_back(t);
977 clique.push_back(s);
978 self(self, next);
979 clique.pop_back();
980 }
981 };
982 grow(grow, candidates);
983 return best;
984}
985
986/// The amsels, as arbiter + msel * arbiters, the input's switchboxes already
987/// configure, by tile. An amsel no master set uses still has rules steering
988/// packets to it.
989std::map<TileID, std::set<int>> configuredAmsels(DeviceOp device) {
990 const int numArbiters = device.getTargetModel().getNumArbiters();
991 std::map<TileID, std::set<int>> amsels;
992 for (auto swboxOp : device.getOps<SwitchboxOp>())
993 for (auto amselOp : swboxOp.getConnections().getOps<AMSelOp>())
994 amsels[swboxOp.getTileOp().getTileID()].insert(
995 amselOp.arbiterIndex() + amselOp.getMselValue() * numArbiters);
996 return amsels;
997}
998
999/// Packet streams take an arbiter at the tile they end at whatever the
1000/// routing, and where `pinsHops` says hops cannot be circuit switched, or the
1001/// stream is prioritized, at the tile they start at and every tile each of
1002/// their routes passes too. Two that must be kept apart pass any tile on
1003/// different slave ports -- sharing one means they merged, unsafely, upstream
1004/// -- so a set of them that must be kept apart pairwise needs an arbiter
1005/// apiece. Says why no routing can work if some tile has such a set larger
1006/// than its free arbiters.
1007std::optional<std::string>
1008tooFewArbiters(DeviceOp device, const StreamConflicts &conflicts,
1009 llvm::function_ref<bool(TileID)> pinsHops,
1010 const PrioritizedPackets &prioritized) {
1011 const AIETargetModel &targetModel = device.getTargetModel();
1012 const int numArbiters = targetModel.getNumArbiters();
1013 const int numMselsPerArbiter = targetModel.getNumMselsPerArbiter();
1014 std::map<TileID, SmallVector<size_t, 8>> pinned;
1015 for (auto [i, s] : llvm::enumerate(conflicts.getRequestedStreams())) {
1016 if (!s.packetID)
1017 continue;
1018 pinned[s.dst.tile].push_back(i);
1019 if (s.src.tile == s.dst.tile)
1020 continue;
1021 bool circuitless = prioritized.contains(s);
1022 if (circuitless || pinsHops(s.src.tile))
1023 pinned[s.src.tile].push_back(i);
1024 for (TileID t : cutTiles(targetModel, s.src.tile, s.dst.tile))
1025 if (circuitless || pinsHops(t))
1026 pinned[t].push_back(i);
1027 }
1028 std::map<TileID, std::set<int>> reserved = configuredAmsels(device);
1029
1030 ArrayRef<RoutedStream> streams = conflicts.getStreams();
1031 for (const auto &[tileId, candidates] : pinned) {
1032 const std::set<int> &taken = reserved[tileId];
1033 size_t free = 0;
1034 for (int a = 0; a < numArbiters; a++)
1035 free += llvm::any_of(llvm::seq(numMselsPerArbiter), [&](int m) {
1036 return !taken.count(a + m * numArbiters);
1037 });
1038 // Streams that must be kept apart have distinct sources and destinations.
1039 std::set<std::pair<TileID, Port>> srcs, dsts;
1040 for (size_t s : candidates) {
1041 srcs.insert({streams[s].src.tile, streams[s].src.port});
1042 dsts.insert({streams[s].dst.tile, streams[s].dst.port});
1043 }
1044 if (std::min(srcs.size(), dsts.size()) <= free)
1045 continue;
1046 SmallVector<size_t, 8> best = largestApartSet(conflicts, candidates, free);
1047 if (best.size() <= free)
1048 continue;
1049
1050 std::string reason;
1051 llvm::raw_string_ostream os(reason);
1052 if (best.size() == 1) {
1053 os << "at tile (" << tileId.col << ", " << tileId.row << "), "
1054 << describeStream(streams[best[0]])
1055 << " takes an arbiter whatever the routing, but the switchbox has "
1056 "none free";
1057 return reason;
1058 }
1059 os << "at tile (" << tileId.col << ", " << tileId.row << "), no two of ";
1060 llvm::interleave(
1061 best, os, [&](size_t s) { os << describeStream(streams[s]); }, ", ");
1062 os << " can share an arbiter, and each takes one there whatever the "
1063 "routing, but the switchbox has "
1064 << free << " free. For example, " << conflicts.explain(best[0], best[1]);
1065 return reason;
1066 }
1067 return std::nullopt;
1068}
1069
1070/// Where a stream leaves a tile it is known to pass: by which master port from
1071/// which slave port, if known.
1072struct Leaving {
1073 size_t stream;
1074 std::optional<Port> slave;
1075 Port master;
1076};
1077
1078/// Where each stream leaves each tile on the trees in `pinnedTrees`, and the
1079/// tiles those trees pass.
1080std::pair<std::map<TileID, SmallVector<Leaving, 8>>, std::set<TileID>>
1081leavingPinnedTrees(const StreamConflicts &conflicts,
1082 const PacketTrees &pinnedTrees,
1083 const PrioritizedPackets &prioritized) {
1084 // Each hop of a pinned tree by the hop before it, and whether it crosses a
1085 // switchbox, unset where two lead to it.
1086 std::map<PathEndPoint,
1087 std::map<PathEndPoint, std::optional<std::pair<PathEndPoint, bool>>>>
1088 preds;
1089 for (const auto &[src, hops] : pinnedTrees)
1090 for (const TreeHop &hop : hops) {
1091 std::pair<PathEndPoint, bool> pred{hop.from, hop.isCrossbar};
1092 auto [it, first] = preds[src].try_emplace(hop.to, pred);
1093 if (!first && it->second && !(*it->second == pred))
1094 it->second.reset();
1095 }
1096 std::map<TileID, SmallVector<Leaving, 8>> leaving;
1097 std::set<TileID> onTrees;
1098 for (auto [i, s] : llvm::enumerate(conflicts.getRequestedStreams())) {
1099 if (!s.packetID)
1100 continue;
1101 // Only the prioritized packets of a source take its tree.
1102 auto tree = prioritized.contains(s) ? preds.find({s.src.tile, s.src.port})
1103 : preds.end();
1104 SmallVector<std::pair<Port, PathEndPoint>, 8> hops;
1105 PathEndPoint at{s.dst.tile, s.dst.port}, src{s.src.tile, s.src.port};
1106 for (size_t n = 0;
1107 tree != preds.end() && !(at == src) && n <= tree->second.size(); n++) {
1108 auto pred = tree->second.find(at);
1109 if (pred == tree->second.end() || !pred->second)
1110 break;
1111 auto [from, isCrossbar] = *pred->second;
1112 if (isCrossbar)
1113 hops.push_back({from.port, at});
1114 at = from;
1115 }
1116 if (!(at == src)) {
1117 leaving[s.dst.tile].push_back({i, std::nullopt, s.dst.port});
1118 continue;
1119 }
1120 for (auto [slave, hop] : hops) {
1121 leaving[hop.coords].push_back({i, slave, hop.port});
1122 onTrees.insert(hop.coords);
1123 }
1124 }
1125 return {std::move(leaving), std::move(onTrees)};
1126}
1127
1128/// A visit of `here` on one arbiter with another: the other visit, and the
1129/// master port they leave by or the slave port they share a packet rule on.
1130struct ArbiterLink {
1131 size_t visit;
1132 Port port;
1133 bool rule;
1134};
1135
1136/// Says why `a` and `b`, which must be kept apart, end up on one arbiter at
1137/// `tileId` through the visits in `chain`.
1138std::string explainSharedArbiter(TileID tileId, size_t a, size_t b,
1139 ArrayRef<ArbiterLink> chain,
1140 ArrayRef<Leaving> here,
1141 const StreamConflicts &conflicts) {
1142 ArrayRef<RoutedStream> streams = conflicts.getStreams();
1143 std::string reason;
1144 llvm::raw_string_ostream os(reason);
1145 os << "at tile (" << tileId.col << ", " << tileId.row
1146 << "), the routes prioritized flows (priority_route) keep put "
1147 << describeStream(streams[a]) << " and " << describeStream(streams[b])
1148 << " on one arbiter: " << describeStream(streams[a]);
1149 for (auto [k, link] : llvm::enumerate(chain))
1150 os << (k == 0 ? "" : ", which")
1151 << (link.rule ? " takes one packet rule on " : " leaves by ")
1152 << describePort(link.port) << " with "
1153 << describeStream(streams[here[link.visit].stream]);
1154 os << ", and a master port or packet rule takes one arbiter. "
1155 << conflicts.explain(a, b);
1156 return reason;
1157}
1158
1159/// Says why no routing can work if two streams that must be kept apart leave
1160/// `tileId` by master ports that streams leaving by one each join, which puts
1161/// them on one arbiter.
1162std::optional<std::string> sharedArbiterAt(TileID tileId,
1163 ArrayRef<Leaving> here,
1164 const StreamConflicts &conflicts) {
1165 ArrayRef<RoutedStream> streams = conflicts.getStreams();
1166 // A stream packet switched at a master port takes its one arbiter, and
1167 // packets with one id on a slave port take one packet rule's arbiter.
1168 // The visits on one arbiter with each. A stream passing a tile twice takes
1169 // an arbiter on each visit, so the nodes are visits.
1170 std::map<size_t, SmallVector<ArbiterLink, 4>> with;
1171 for (auto [x, l] : llvm::enumerate(here))
1172 for (auto [y, m] : llvm::enumerate(here)) {
1173 if (x == y)
1174 continue;
1175 if (l.master == m.master)
1176 with[x].push_back({y, l.master, false});
1177 else if (l.slave && m.slave && *l.slave == *m.slave &&
1178 streams[l.stream].packetID == streams[m.stream].packetID)
1179 with[x].push_back({y, *l.slave, true});
1180 }
1181 for (size_t x : llvm::make_first_range(with)) {
1182 // The chain of visits that joins `x` to each visit it reaches.
1183 std::map<size_t, size_t> via = breadthFirstParents(x, [&](size_t u) {
1184 return llvm::map_range(
1185 with.at(u), [](const ArbiterLink &link) { return link.visit; });
1186 });
1187 size_t a = here[x].stream;
1188 for (size_t y : llvm::make_first_range(via)) {
1189 size_t b = here[y].stream;
1190 if (b <= a || !conflicts.mustSeparate(a, b))
1191 continue;
1192 SmallVector<ArbiterLink, 4> chain;
1193 for (size_t v = y; v != x; v = via.at(v))
1194 chain.push_back(
1195 *llvm::find_if(with.at(via.at(v)), [&](const ArbiterLink &link) {
1196 return link.visit == v;
1197 }));
1198 std::reverse(chain.begin(), chain.end());
1199 return explainSharedArbiter(tileId, a, b, chain, here, conflicts);
1200 }
1201 }
1202 return std::nullopt;
1203}
1204
1205/// A RoutingFailure if no routing can work because the arbiters packet streams
1206/// take whatever the routing do not fit: too few free ones at a tile, or, as a
1207/// PinnedRoutingFailure, two streams that must be kept apart put on one by the
1208/// trees in `pinnedTrees`, which prioritized sources keep.
1209llvm::Error unroutableArbiters(DeviceOp device,
1210 const StreamConflicts &conflicts,
1211 llvm::function_ref<bool(TileID)> pinsHops,
1212 const PacketTrees &pinnedTrees) {
1213 PrioritizedPackets prioritized = prioritizedPackets(device);
1214 if (std::optional<std::string> reason =
1215 tooFewArbiters(device, conflicts, pinsHops, prioritized))
1216 return llvm::make_error<RoutingFailure>(std::move(*reason));
1217 if (pinnedTrees.empty())
1218 return llvm::Error::success();
1219 auto [leaving, onTrees] =
1220 leavingPinnedTrees(conflicts, pinnedTrees, prioritized);
1221 for (TileID tileId : onTrees)
1222 if (std::optional<std::string> reason =
1223 sharedArbiterAt(tileId, leaving[tileId], conflicts))
1224 return llvm::make_error<PinnedRoutingFailure>(std::move(*reason));
1225 return llvm::Error::success();
1226}
1227} // namespace
1228
1229static void getOrCreateConnect(OpBuilder &builder, ShimMuxOp shimMux,
1230 Location loc, WireBundle srcBundle, int srcCh,
1231 WireBundle destBundle, int destCh) {
1232 for (auto connect : shimMux.getConnections().getOps<ConnectOp>())
1233 if (connect.getSourceBundle() == srcBundle &&
1234 connect.getSourceChannel() == srcCh &&
1235 connect.getDestBundle() == destBundle &&
1236 connect.getDestChannel() == destCh)
1237 return;
1238 ConnectOp::create(builder, loc, srcBundle, srcCh, destBundle, destCh);
1239}
1240
1241static PathEndPoint sourceOf(FlowOp flow) {
1242 auto tile = cast<TileOp>(flow.getSource().getDefiningOp());
1243 return PathEndPoint{tile.getTileID(),
1244 {flow.getSourceBundle(), flow.getSourceChannel()}};
1245}
1246
1247// The router names a shim DMA by its own port; move the rules and master sets
1248// that use one behind the shim mux, onto the South channel it reaches the
1249// switchbox by (see shimMuxChannelFrom).
1250static void lowerShimDMAPorts(DeviceOp device, OpBuilder &builder,
1251 DynamicTileAnalysis &analyzer) {
1252 const AIETargetModel &targetModel = device.getTargetModel();
1253 for (auto switchbox : device.getOps<SwitchboxOp>()) {
1254 TileOp tileOp = switchbox.getTileOp();
1255 if (!tileOp.isShimNOCTile() ||
1256 !targetModel.hasShimMux(tileOp.getCol(), tileOp.getRow()))
1257 continue;
1258 auto connectInMux = [&](Location loc, Port src, Port dst) {
1259 builder.setInsertionPointAfter(tileOp);
1260 ShimMuxOp shimMux = analyzer.getShimMux(builder, tileOp.colIndex());
1261 builder.setInsertionPointToStart(&shimMux.getConnections().front());
1262 getOrCreateConnect(builder, shimMux, loc, src.bundle, src.channel,
1263 dst.bundle, dst.channel);
1264 };
1265 for (Operation &op : switchbox.getConnections().front()) {
1266 if (auto rules = dyn_cast<PacketRulesOp>(op);
1267 rules && rules.getSourceBundle() == WireBundle::DMA) {
1268 int ch = shimMuxChannelFrom(rules.sourcePort());
1269 connectInMux(rules.getLoc(), rules.sourcePort(),
1270 {WireBundle::North, ch});
1271 rules.setSourceBundle(WireBundle::South);
1272 rules.setSourceChannel(ch);
1273 }
1274 if (auto masterSet = dyn_cast<MasterSetOp>(op);
1275 masterSet && masterSet.getDestBundle() == WireBundle::DMA) {
1276 int ch = shimMuxChannelTo(masterSet.destPort());
1277 connectInMux(masterSet.getLoc(), {WireBundle::North, ch},
1278 masterSet.destPort());
1279 masterSet.setDestBundle(WireBundle::South);
1280 masterSet.setDestChannel(ch);
1281 }
1282 }
1283 }
1284}
1285
1286namespace {
1287// How runOnPacketFlow lowers the packet flows on one routing: the connections
1288// the routing lays down and the arbiters planned for them.
1289struct PacketPlan {
1290 LogicalResult emit(DeviceOp device, OpBuilder &builder,
1291 DynamicTileAnalysis &analyzer) const;
1292 SmallVector<std::pair<int, int>, 2>
1293 statedCubes(const std::pair<PhysPort, int> &slaveFlow, int idMask) const;
1294
1295 // A hold cycle through waits at receivers the trees share that no arbiter
1296 // assignment found breaks.
1297 std::optional<HoldCycle> sharedReceiverCycle;
1298
1299 // The master ports packets with each flow ID leave by, keyed by the slave
1300 // port they enter.
1301 std::map<std::pair<PhysPort, int>, SmallVector<PhysPort, 4>> packetFlows;
1302 SmallVector<std::pair<PhysPort, int>, 4> slavePorts;
1303 // Where the packet flows entering each slave port with each ID were
1304 // written, so the routing they become points back at them.
1305 std::map<std::pair<PhysPort, int>, SmallVector<Location, 1>> slaveFlowLocs;
1306 // The packet flows' locations in the order the flows were written.
1307 DenseMap<Location, unsigned> flowLocOrder;
1308 // The flows behind `slaveFlows`, fused, or `fallback` if none.
1309 Location locOf(ArrayRef<std::pair<PhysPort, int>> slaveFlows,
1310 Location fallback) const;
1311 // Flag to keep packet header at packet flow destination
1312 DenseMap<PhysPort, BoolAttr> keepPktHeaderAttr;
1313 // The slave ports and IDs that carry prioritized packets. A switchbox routes
1314 // on the ID alone, so a flow sharing both with a priority flow is one too.
1315 DenseSet<std::pair<PhysPort, int>> prioritizedFlows;
1316 DenseSet<std::pair<PhysPort, int>> markedFlows;
1317 DenseSet<PhysPort> priorityMasterPorts;
1318
1319 // Packet-rule masks the flows state, keyed by the slave port the stream
1320 // enters and the flow ID. One ID may reach a port under two masks, so the
1321 // ID alone does not identify the claim, and flows sharing both may each
1322 // state a mask of their own, which the port then claims together.
1323 std::map<std::pair<PhysPort, int>, std::set<int>> pinnedMasks;
1324
1325 // A switchbox with more packet master ports than free arbiters has to put
1326 // two master ports on one arbiter, and an arbiter holds its grant until
1327 // tlast, so one stalled packet then holds up an unrelated flow. A hop that
1328 // alone uses both its ports needs no arbiter: a circuit connection passes the
1329 // header and tlast through, and the next switchbox routes the packet as
1330 // before. The last hop stays packet-switched, since it drops the header.
1331 // A circuit may broadcast, so a slave port qualifies with all the master
1332 // ports it reaches, provided it alone feeds them and every packet goes to
1333 // all of them.
1334 std::map<TileID, SmallVector<Connect, 4>> circuitHops;
1335 std::map<TileID, ArbiterPlan> plans;
1336};
1337
1338// Plans the packet flows on a routing, leaving the IR alone. Where no plan
1339// fits, the faults say which connections are in the way.
1340struct PacketFlowRouting : PacketPlan {
1341 using FlowKey = std::pair<Port, int>;
1342
1343 PacketFlowRouting(DeviceOp device, const Routing &routing,
1344 const StreamConflicts &conflicts,
1345 const PinnedRoutes &pinned, bool routeCircuit,
1346 bool circuitSwitchHops, bool prioritize)
1347 : device(device), routing(routing), conflicts(conflicts), pinned(pinned),
1348 prioritize(prioritize), routeCircuit(routeCircuit),
1349 circuitSwitchHops(circuitSwitchHops),
1350 targetModel(device.getTargetModel()),
1351 numArbiters(targetModel.getNumArbiters()),
1352 numMselsPerArbiter(targetModel.getNumMselsPerArbiter()),
1353 maxPacketId(targetModel.getMaxPacketId()),
1354 idBits(targetModel.getPacketIdBits()),
1355 idMask(targetModel.getPacketIdMask()) {}
1356
1357 llvm::Expected<PacketPlan> plan();
1358 void collectFlows();
1359 void findCircuitHops();
1360 void collectSlaveFlows();
1361 void checkRules();
1362 void planTiles();
1363 std::optional<std::string> breakHoldCycles();
1364 RoutingFaults faults() const;
1365
1366 const SwitchSettings &settingsOf(const PathEndPoint &src,
1367 std::optional<int> id = std::nullopt);
1368 std::optional<std::pair<size_t, size_t>>
1369 conflictingStreams(TileID tileId, const SlaveFlow &a, const SlaveFlow &b);
1370 std::optional<ArbiterPlan>
1371 planTile(TileID tileId, SmallVectorImpl<std::pair<size_t, size_t>> &blocking);
1372 void moveFlow(TileID tileId, FlowKey key, bool priority = false);
1373 void moveUnit(TileID tileId, FlowKey key);
1374 void splitFlow(TileID tileId, FlowKey key, ArrayRef<FlowKey> partners);
1375
1376 DeviceOp device;
1377 const Routing &routing;
1378 const StreamConflicts &conflicts;
1379 const PinnedRoutes &pinned;
1380 // Whether prioritized flows not pinned are prioritized here.
1381 bool prioritize;
1382 bool routeCircuit;
1383 bool circuitSwitchHops;
1384 const AIETargetModel &targetModel;
1385 const int numArbiters;
1386 const int numMselsPerArbiter;
1387 const uint32_t maxPacketId;
1388 const int idBits;
1389 const int idMask;
1390
1391 // The streams each slave flow carries, for asking whether two flows can
1392 // deadlock on an arbiter. Flows with one source, destination and id may
1393 // state different masks, so carry different ids, and each is a stream of
1394 // its own.
1395 struct StreamEnds {
1396 PathEndPoint src, dst;
1397 int id;
1398 bool operator<(const StreamEnds &rhs) const {
1399 return std::tie(src, dst, id) < std::tie(rhs.src, rhs.dst, rhs.id);
1400 }
1401 };
1402 std::map<StreamEnds, SmallVector<size_t, 1>> packetStreamIndex;
1403 DenseMap<std::pair<PhysPort, int>, SmallVector<size_t, 2>> slaveFlowStreams;
1404 // Each source's part of a SlaveFlow (see SlaveFlow). A switchbox routes on
1405 // the id alone, so sources sharing an id there go everywhere any of them
1406 // does.
1407 std::map<std::pair<PhysPort, int>, std::map<PathEndPoint, std::set<Port>>>
1408 slaveFlowSources;
1409 // Every stream's hops, source first; the requested ones as this routing
1410 // lays them, the rest as the design already does.
1411 std::vector<SmallVector<StreamHop, 8>> routes;
1412 // Sources routed as circuits, which runOnFlow lowers.
1413 std::set<PathEndPoint> circuitSources;
1414 const SwitchSettings noSettings;
1415
1416 // The logical model of all the switchboxes.
1417 std::map<TileID, SmallVector<std::pair<Connect, int>, 8>> switchboxes;
1418 // <arbiter, msel> slots (per tile) that packet-switch configuration in the
1419 // input IR already occupies. Kept apart from masterAMSels so the allocator
1420 // run does not re-emit those ops.
1421 std::map<TileID, std::set<int>> reservedAmsels;
1422 // The amsel of each TileControl master set of the control packet overlay.
1423 // Packets ending there take it.
1424 std::map<TileID, std::map<Port, int>> joinedAmsels;
1425 // Each switchbox has its arbiters planned as a whole (see planArbiters).
1426 // Where that is impossible the routing is unusable, and the connections of
1427 // the flows in the way are what the router has to move.
1428 std::map<TileID, std::map<FlowKey, SlaveFlow>> tileSlaveFlows;
1429 std::map<TileID, SmallVector<SlaveFlow, 8>> tileFlows;
1430 // What the search below learns: flows to keep on different arbiters, and
1431 // flows to keep off an arbiter that flows already in the design take.
1432 std::set<std::tuple<TileID, FlowKey, FlowKey>> apart;
1433 std::set<std::tuple<TileID, FlowKey, int>> offArbiter;
1434 std::set<std::pair<TileID, Connect>> hazardConnections;
1435 std::set<std::pair<TileID, Connect>> priorityConnections;
1436 // The TreeSplits (see TreeSplit) the routing check asks for. `key` branches
1437 // from the flows of its source that tie it to one of `partners`, where
1438 // nothing else does. The next routing may reach the tile by another slave
1439 // port, so the split holds for the tile.
1440 std::set<TreeSplit> hazardSplits;
1441 std::set<std::pair<PathEndPoint, PathEndPoint>> hazardApart;
1442 std::set<std::pair<PathEndPoint, PathEndPoint>> hazardTogether;
1443 std::set<PathEndPoint> hazardUntrunk;
1444 std::set<TileID> crowdedTiles;
1445 std::optional<std::string> planFailure;
1446 std::optional<std::pair<Location, std::string>> incomplete;
1447};
1448} // namespace
1449
1450void PacketFlowRouting::collectFlows() {
1451 for (auto [i, s] : llvm::enumerate(conflicts.getStreams()))
1452 if (s.packetID)
1453 packetStreamIndex[{{s.src.tile, s.src.port},
1454 {s.dst.tile, s.dst.port},
1455 *s.packetID}]
1456 .push_back(i);
1457 for (const RoutedStream &s : conflicts.getStreams())
1458 routes.push_back(s.hops);
1459
1460 if (routeCircuit)
1461 for (FlowOp flow : device.getOps<FlowOp>())
1462 circuitSources.insert(sourceOf(flow));
1463
1464 for (PacketFlowOp pktFlowOp : device.getOps<PacketFlowOp>()) {
1465 Region &r = pktFlowOp.getPorts();
1466 Block &b = r.front();
1467 int flowID = pktFlowOp.IDInt();
1468 SmallVector<std::pair<TileID, Port>, 4> sources;
1469
1470 // Pass 1: collect all sources (order-independent; supports fan-in).
1471 for (Operation &Op : b.getOperations()) {
1472 if (auto pktSource = dyn_cast<PacketSourceOp>(Op)) {
1473 auto srcTile = cast<TileOp>(pktSource.getTile().getDefiningOp());
1474 sources.push_back(
1475 {{srcTile.colIndex(), srcTile.rowIndex()}, pktSource.port()});
1476 }
1477 }
1478 // Pass 2: lower each (source, destination) pair so fan-in flows lay
1479 // down switchbox connections for every source, not just the last one.
1480 for (Operation &Op : b.getOperations()) {
1481 auto pktDest = dyn_cast<PacketDestOp>(Op);
1482 if (!pktDest)
1483 continue;
1484 auto destTile = cast<TileOp>(pktDest.getTile().getDefiningOp());
1485 Port destPort = pktDest.port();
1486 TileID destCoords = {destTile.colIndex(), destTile.rowIndex()};
1487 // Assign "keep_pkt_header flag"
1488 auto keep = pktFlowOp.getKeepPktHeader();
1489 keepPktHeaderAttr[{destTile.getTileID(), destPort}] =
1490 keep ? BoolAttr::get(Op.getContext(), *keep) : nullptr;
1491
1492 for (auto &[srcCoords, srcPort] : sources) {
1493 TileID srcSB = {srcCoords.col, srcCoords.row};
1494 PathEndPoint srcPoint = {srcSB, srcPort};
1495 if (circuitSources.count(srcPoint))
1496 continue;
1497 const SwitchSettings &settings = settingsOf(srcPoint, flowID);
1498 // The requested streams this flow asks for here; with none, the
1499 // stream the design already routes.
1500 SmallVector<size_t, 1> flowStreams;
1501 if (auto stream = packetStreamIndex.find(
1502 {srcPoint, {destCoords, destPort}, flowID});
1503 stream != packetStreamIndex.end()) {
1504 int mask = static_cast<int>(pktFlowOp.getMask().value_or(~0));
1505 for (size_t i : stream->second)
1506 if (i < conflicts.getRequestedStreams().size() &&
1507 conflicts.getStreams()[i].packetMask == mask)
1508 flowStreams.push_back(i);
1509 if (flowStreams.empty())
1510 flowStreams.push_back(stream->second.front());
1511 }
1512 for (size_t stream : flowStreams) {
1513 SmallVector<StreamHop, 8> &hops = routes[stream];
1514 hops.clear();
1515 // A route may pass a switchbox more than once, but no connection.
1516 size_t connections = 0;
1517 for (const auto &[_, setting] : settings)
1518 connections += setting.srcs.size();
1519 std::optional<std::pair<TileID, Port>> at{{srcSB, srcPort}};
1520 while (at && hops.size() <= connections) {
1521 auto [tile, input] = *at;
1522 hops.push_back({tile, input, std::nullopt});
1523 at.reset();
1524 auto setting = settings.find(tile);
1525 if (setting == settings.end())
1526 break;
1527 for (auto [src, dest] :
1528 llvm::zip(setting->second.srcs, setting->second.dsts))
1529 if (src == input && !(tile == destCoords && dest == destPort) &&
1530 findPathToDest(settings, tile, dest, destCoords, destPort)) {
1531 at = getLinkedInput(tile, dest);
1532 break;
1533 }
1534 }
1535 }
1536 // Track whether the source's own switch connection survives routing.
1537 bool srcRouted = false;
1538 // add connections for all the Switchboxes in SwitchSettings
1539 for (const auto &[curr, setting] : settings) {
1540 assert(setting.srcs.size() == setting.dsts.size());
1541 TileID currTile = {curr.col, curr.row};
1542 for (size_t i = 0; i < setting.srcs.size(); i++) {
1543 Port src = setting.srcs[i];
1544 Port dest = setting.dsts[i];
1545 // reject false broadcast
1546 if (!findPathToDest(settings, currTile, dest, destCoords, destPort))
1547 continue;
1548 if (currTile == srcSB && src.bundle == srcPort.bundle &&
1549 src.channel == srcPort.channel)
1550 srcRouted = true;
1551 Connect connect = {{src.bundle, src.channel},
1552 {dest.bundle, dest.channel}};
1553 if (std::find(
1554 switchboxes[currTile].begin(), switchboxes[currTile].end(),
1555 std::pair{connect, flowID}) == switchboxes[currTile].end())
1556 switchboxes[currTile].push_back({connect, flowID});
1557 // Keyed by slave port as well as ID, since IDs are reused across
1558 // unrelated flows.
1559 PhysPort slavePort = {currTile, {src.bundle, src.channel}};
1560 std::pair<PhysPort, int> slaveFlow = {slavePort, flowID};
1561 for (size_t stream : flowStreams)
1562 if (!llvm::is_contained(slaveFlowStreams[slaveFlow], stream))
1563 slaveFlowStreams[slaveFlow].push_back(stream);
1564 slaveFlowSources[slaveFlow][srcPoint].insert(dest);
1565 if (!llvm::is_contained(slaveFlowLocs[slaveFlow],
1566 pktFlowOp.getLoc()))
1567 slaveFlowLocs[slaveFlow].push_back(pktFlowOp.getLoc());
1568 flowLocOrder.try_emplace(pktFlowOp.getLoc(), flowLocOrder.size());
1569 if (std::optional<uint8_t> mask = pktFlowOp.getMask()) {
1570 pinnedMasks[{{currTile, {src.bundle, src.channel}}, flowID}]
1571 .insert(*mask);
1572 }
1573 if (pktFlowOp.getPriorityRoute().value_or(false)) {
1574 markedFlows.insert(slaveFlow);
1575 if (prioritize || pinned.trees.count(srcPoint)) {
1576 prioritizedFlows.insert(slaveFlow);
1577 }
1578 }
1579 }
1580 }
1581 if (!srcRouted && !incomplete)
1582 incomplete = {
1583 pktFlowOp.getLoc(),
1584 "packet flow source " + describeTilePort(srcCoords, srcPort) +
1585 " could not be routed to destination " +
1586 describeTilePort(destCoords, destPort) +
1587 "; the pathfinder produced an incomplete routing for this "
1588 "placement."};
1589 }
1590 }
1591 }
1592}
1593
1594Location PacketPlan::locOf(ArrayRef<std::pair<PhysPort, int>> slaveFlows,
1595 Location fallback) const {
1596 SmallVector<Location, 2> locs;
1597 for (const auto &flow : slaveFlows)
1598 if (auto found = slaveFlowLocs.find(flow); found != slaveFlowLocs.end())
1599 for (Location loc : found->second)
1600 if (!llvm::is_contained(locs, loc))
1601 locs.push_back(loc);
1602 if (locs.empty())
1603 return fallback;
1604 llvm::sort(locs, [&](Location a, Location b) {
1605 return flowLocOrder.lookup(a) < flowLocOrder.lookup(b);
1606 });
1607 return FusedLoc::get(fallback.getContext(), locs);
1608}
1609
1610// The rules the flows through `slaveFlow` state. A full-width mask selects the
1611// id alone, which the cover states just as well, so only a wider claim becomes
1612// a rule of its own.
1613SmallVector<std::pair<int, int>, 2>
1614PacketPlan::statedCubes(const std::pair<PhysPort, int> &slaveFlow,
1615 int idMask) const {
1616 SmallVector<std::pair<int, int>, 2> cubes;
1617 auto it = pinnedMasks.find(slaveFlow);
1618 if (it != pinnedMasks.end())
1619 for (int mask : it->second)
1620 if (mask != idMask)
1621 cubes.push_back({mask, slaveFlow.second});
1622 return cubes;
1623}
1624
1625const SwitchSettings &PacketFlowRouting::settingsOf(const PathEndPoint &src,
1626 std::optional<int> id) {
1627 if (id)
1628 if (auto own = routing.idSettings.find({src, *id});
1629 own != routing.idSettings.end())
1630 return own->second;
1631 auto it = routing.settings.find(src);
1632 return it == routing.settings.end() ? noSettings : it->second;
1633}
1634
1635static AMSelOp findExclusiveAMSel(MasterSetOp master) {
1636 for (Value selection : master.getAmsels()) {
1637 auto candidate = cast<AMSelOp>(selection.getDefiningOp());
1638 if (llvm::all_of(
1639 master->getBlock()->getOps<MasterSetOp>(),
1640 [&](MasterSetOp otherMaster) {
1641 return otherMaster.destPort() == master.destPort() ||
1642 llvm::none_of(otherMaster.getAmsels(), [&](Value other) {
1643 auto amsel = cast<AMSelOp>(other.getDefiningOp());
1644 return amsel.arbiterIndex() ==
1645 candidate.arbiterIndex() &&
1646 amsel.getMselValue() == candidate.getMselValue();
1647 });
1648 }))
1649 return candidate;
1650 }
1651 return {};
1652}
1653
1654void PacketFlowRouting::findCircuitHops() {
1655 // Seed the reserved set from the packet-switch configuration the switchboxes
1656 // already carry, so this run allocates around it instead of over it.
1657 reservedAmsels = configuredAmsels(device);
1658 AIEDialect::IsCtrlPktOverlayAttrHelper overlay(device.getContext());
1659 for (auto swbox : device.getOps<SwitchboxOp>())
1660 for (auto master : swbox.getConnections().getOps<MasterSetOp>())
1661 if (master.getDestBundle() == WireBundle::TileControl &&
1662 overlay.isAttrPresent(master))
1663 if (auto amsel = findExclusiveAMSel(master))
1664 joinedAmsels[swbox.getTileOp().getTileID()][master.destPort()] =
1665 amsel.arbiterIndex() + amsel.getMselValue() * numArbiters;
1666
1667 // Ports the input's own aie.switchbox ops already drive, circuit or packet.
1668 std::set<PhysPort> claimedSlaves, claimedMasters;
1669 for (auto swbox : device.getOps<SwitchboxOp>()) {
1670 TileID tileId = swbox.getTileOp().getTileID();
1671 Region &ops = swbox.getConnections();
1672 for (auto connect : ops.getOps<ConnectOp>()) {
1673 claimedSlaves.insert({tileId, connect.sourcePort()});
1674 claimedMasters.insert({tileId, connect.destPort()});
1675 }
1676 for (auto rules : ops.getOps<PacketRulesOp>())
1677 claimedSlaves.insert({tileId, rules.sourcePort()});
1678 for (auto masterSet : ops.getOps<MasterSetOp>())
1679 claimedMasters.insert({tileId, masterSet.destPort()});
1680 }
1681 // Circuits not yet lowered claim their ports all the same.
1682 if (routeCircuit)
1683 for (FlowOp flow : device.getOps<FlowOp>())
1684 for (const auto &[tileId, setting] : settingsOf(sourceOf(flow))) {
1685 for (Port p : setting.srcs)
1686 claimedSlaves.insert({tileId, p});
1687 for (Port p : setting.dsts)
1688 claimedMasters.insert({tileId, p});
1689 }
1690 for (auto &[tileId, connects] : switchboxes) {
1691 if (!circuitSwitchHops || targetModel.hasShimMux(tileId.col, tileId.row))
1692 continue;
1693 std::set<Port> masters;
1694 for (const auto &[conn, flowID] : connects)
1695 masters.insert(conn.dst);
1696 SmallVector<Port, 8> slaves;
1697 for (const auto &[conn, flowID] : connects)
1698 if (!llvm::is_contained(slaves, conn.src))
1699 slaves.push_back(conn.src);
1700 const std::set<int> &reserved = reservedAmsels[tileId];
1701 size_t freeArbiters = llvm::count_if(llvm::seq(0, numArbiters), [&](int a) {
1702 return llvm::none_of(llvm::seq(0, numMselsPerArbiter), [&](int m) {
1703 return reserved.count(a + m * numArbiters);
1704 });
1705 });
1706 for (Port slave : slaves) {
1707 if (masters.size() <= freeArbiters)
1708 break;
1709 std::set<Port> reached;
1710 std::map<int, std::set<Port>> reachedByID;
1711 for (const auto &[conn, flowID] : connects)
1712 if (conn.src == slave) {
1713 reached.insert(conn.dst);
1714 reachedByID[flowID].insert(conn.dst);
1715 }
1716 bool exclusive =
1717 !claimedSlaves.count({tileId, slave}) &&
1718 llvm::all_of(reached,
1719 [&, tileId = tileId](Port m) {
1720 return getLinkedInput(tileId, m).has_value() &&
1721 !claimedMasters.count({tileId, m});
1722 }) &&
1723 llvm::all_of(
1724 reachedByID,
1725 [&](const auto &ids) { return ids.second == reached; }) &&
1726 llvm::all_of(connects, [&, tileId = tileId](const auto &entry) {
1727 const auto &[other, otherID] = entry;
1728 if (!reached.count(other.dst))
1729 return true;
1730 return other.src == slave &&
1731 !prioritizedFlows.contains({{tileId, slave}, otherID});
1732 });
1733 if (!exclusive)
1734 continue;
1735 for (Port m : reached) {
1736 circuitHops[tileId].push_back({slave, m});
1737 masters.erase(m);
1738 }
1739 llvm::erase_if(connects, [&](const auto &entry) {
1740 return entry.first.src == slave;
1741 });
1742 }
1743 }
1744}
1745
1746void PacketFlowRouting::collectSlaveFlows() {
1747 LLVM_DEBUG(llvm::dbgs() << "Check switchboxes\n");
1748
1749 for (const auto &[tileId, connects] : switchboxes) {
1750 LLVM_DEBUG(llvm::dbgs() << "***switchbox*** " << tileId.col << " "
1751 << tileId.row << '\n');
1752 for (const auto &[conn, flowID] : connects) {
1753 Port sourcePort = conn.src;
1754 Port destPort = conn.dst;
1755 auto sourceFlow =
1756 std::make_pair(std::make_pair(tileId, sourcePort), flowID);
1757 packetFlows[sourceFlow].push_back({tileId, destPort});
1758 if (markedFlows.contains(sourceFlow))
1759 priorityMasterPorts.insert({tileId, destPort});
1760 slavePorts.push_back(sourceFlow);
1761 LLVM_DEBUG(llvm::dbgs() << "flowID " << flowID << ':'
1762 << stringifyWireBundle(sourcePort.bundle) << " "
1763 << sourcePort.channel << " -> "
1764 << stringifyWireBundle(destPort.bundle) << " "
1765 << destPort.channel << "\n");
1766 }
1767 }
1768
1769 for (const auto &[flow, dests] : packetFlows) {
1770 SlaveFlow &f = tileSlaveFlows[flow.first.first]
1771 .try_emplace({flow.first.second, flow.second},
1772 SlaveFlow{flow.first.second,
1773 flow.second,
1774 {},
1775 prioritizedFlows.contains(flow)})
1776 .first->second;
1777 for (const PhysPort &dest : dests)
1778 if (!llvm::is_contained(f.masters, dest.second))
1779 f.masters.push_back(dest.second);
1780 llvm::sort(f.masters);
1781 }
1782 for (const auto &[tileId, byFlow] : tileSlaveFlows)
1783 for (const auto &[key, f] : byFlow)
1784 tileFlows[tileId].push_back(f);
1785}
1786
1787std::optional<std::pair<size_t, size_t>>
1788PacketFlowRouting::conflictingStreams(TileID tileId, const SlaveFlow &a,
1789 const SlaveFlow &b) {
1790 auto as = slaveFlowStreams.find({{tileId, a.slave}, a.id});
1791 auto bs = slaveFlowStreams.find({{tileId, b.slave}, b.id});
1792 if (as == slaveFlowStreams.end() || bs == slaveFlowStreams.end())
1793 return std::nullopt;
1794 for (size_t s : as->second)
1795 for (size_t t : bs->second)
1796 if (conflicts.conflict(s, t))
1797 return std::pair{s, t};
1798 return std::nullopt;
1799}
1800
1801std::optional<ArbiterPlan> PacketFlowRouting::planTile(
1802 TileID tileId, SmallVectorImpl<std::pair<size_t, size_t>> &blocking) {
1803 if (auto joined = joinedAmsels.find(tileId); joined != joinedAmsels.end()) {
1804 SmallVector<SlaveFlow, 8> &all = tileFlows.at(tileId);
1805 ArbiterPlan plan;
1806 SmallVector<size_t, 8> rest;
1807 for (auto [i, f] : llvm::enumerate(all)) {
1808 auto amsel = joined->second.find(f.masters.front());
1809 if (amsel == joined->second.end()) {
1810 if (llvm::any_of(f.masters,
1811 [&](Port m) { return joined->second.count(m); }))
1812 return std::nullopt;
1813 rest.push_back(i);
1814 } else if (f.masters.size() == 1) {
1815 plan.slaveAmsels[{f.slave, f.id}] = amsel->second;
1816 } else {
1817 return std::nullopt;
1818 }
1819 }
1820 if (!plan.slaveAmsels.empty()) {
1821 SmallVector<SlaveFlow, 8> saved = std::move(all);
1822 all.clear();
1823 for (size_t i : rest)
1824 all.push_back(saved[i]);
1825 size_t known = blocking.size();
1826 std::optional<ArbiterPlan> others =
1827 all.empty() ? ArbiterPlan() : planTile(tileId, blocking);
1828 all = std::move(saved);
1829 for (auto &[a, b] : llvm::drop_begin(blocking, known)) {
1830 a = rest[a];
1831 b = rest[b];
1832 }
1833 if (!others)
1834 return std::nullopt;
1835 others->slaveAmsels.insert(plan.slaveAmsels.begin(),
1836 plan.slaveAmsels.end());
1837 return others;
1838 }
1839 }
1840 ArrayRef<SlaveFlow> flows = tileFlows.at(tileId);
1841 auto key = [&](size_t f) { return FlowKey{flows[f].slave, flows[f].id}; };
1842 auto conflict = [&](size_t a, size_t b) {
1843 return apart.count(
1844 {tileId, std::min(key(a), key(b)), std::max(key(a), key(b))}) ||
1845 conflictingStreams(tileId, flows[a], flows[b]);
1846 };
1847 auto excluded = [&](size_t f, int arbiter) {
1848 return offArbiter.count({tileId, key(f), arbiter}) > 0;
1849 };
1850 SmallVector<size_t, 8> priority, others;
1851 for (auto [i, f] : llvm::enumerate(flows))
1852 (f.isPriority ? priority : others).push_back(i);
1853 if (priority.empty() || (others.empty() && pinned.rules.empty()))
1854 return planArbiters(targetModel, flows, conflict, excluded,
1855 reservedAmsels[tileId], blocking);
1856
1857 auto subset = [&](ArrayRef<size_t> members) {
1858 SmallVector<SlaveFlow, 8> sub;
1859 for (size_t m : members)
1860 sub.push_back(flows[m]);
1861 return sub;
1862 };
1863 auto keepPinned = [&]() -> std::optional<ArbiterPlan> {
1864 ArbiterPlan kept;
1865 for (size_t f : priority) {
1866 Port slave = flows[f].slave;
1867 if (slave.bundle == WireBundle::DMA &&
1868 targetModel.isShimNOCTile(tileId.col, tileId.row) &&
1869 targetModel.hasShimMux(tileId.col, tileId.row))
1870 slave = {WireBundle::South, shimMuxChannelFrom(slave)};
1871 auto rules = pinned.rules.find({tileId, slave});
1872 const std::tuple<int, int, int> *rule = nullptr;
1873 if (rules != pinned.rules.end())
1874 rule = llvm::find_if(rules->second, [&](const auto &r) {
1875 auto [mask, value, amsel] = r;
1876 return (flows[f].id & mask) == (value & mask);
1877 });
1878 if (!rule || rule == rules->second.end())
1879 return std::nullopt;
1880 int amsel = std::get<2>(*rule);
1881 if (excluded(f, amsel % numArbiters) ||
1882 reservedAmsels[tileId].count(amsel) ||
1883 kept.amselMasters.try_emplace(amsel, flows[f].masters)
1884 .first->second != flows[f].masters)
1885 return std::nullopt;
1886 kept.slaveAmsels[key(f)] = amsel;
1887 }
1888 for (auto [k, a] : llvm::enumerate(priority))
1889 for (size_t b : llvm::drop_begin(priority, k + 1))
1890 if (kept.slaveAmsels.at(key(a)) % numArbiters ==
1891 kept.slaveAmsels.at(key(b)) % numArbiters &&
1892 flows[a].slave != flows[b].slave && conflict(a, b)) {
1893 return std::nullopt;
1894 }
1895 return kept;
1896 };
1897 SmallVector<std::pair<size_t, size_t>, 4> stuck;
1898 std::optional<ArbiterPlan> plan;
1899 if (!pinned.rules.empty())
1900 plan = keepPinned();
1901 if (!plan) {
1902 plan = planArbiters(
1903 targetModel, subset(priority),
1904 [&](size_t a, size_t b) { return conflict(priority[a], priority[b]); },
1905 [&](size_t f, int arbiter) { return excluded(priority[f], arbiter); },
1906 reservedAmsels[tileId], stuck);
1907 if (!plan) {
1908 for (auto [a, b] : stuck)
1909 blocking.push_back({priority[a], priority[b]});
1910 return std::nullopt;
1911 }
1912 }
1913 if (others.empty())
1914 return plan;
1915
1916 auto around = [&](ArbiterPlan plan, ArrayRef<size_t> planned,
1917 ArrayRef<size_t> pending,
1918 SmallVectorImpl<std::pair<size_t, size_t>> &blocking)
1919 -> std::optional<ArbiterPlan> {
1920 auto arbiterOf = [&](size_t f) {
1921 return plan.slaveAmsels.at(key(f)) % numArbiters;
1922 };
1923 SmallVector<size_t, 8> placed(planned), rest;
1924 for (size_t f : pending) {
1925 auto same = llvm::find_if(plan.amselMasters, [&](const auto &entry) {
1926 return entry.second == flows[f].masters;
1927 });
1928 if (same == plan.amselMasters.end()) {
1929 rest.push_back(f);
1930 continue;
1931 }
1932 for (size_t g : placed)
1933 if (arbiterOf(g) == same->first % numArbiters &&
1934 flows[g].slave != flows[f].slave && conflict(f, g))
1935 blocking.push_back({g, f});
1936 if (excluded(f, same->first % numArbiters))
1937 blocking.push_back({planned.front(), f});
1938 plan.slaveAmsels[key(f)] = same->first;
1939 placed.push_back(f);
1940 }
1941 if (!blocking.empty())
1942 return std::nullopt;
1943 if (rest.empty())
1944 return plan;
1945
1946 // A master port is tied to one arbiter, so a flow leaving by a master port
1947 // the plan has tied takes that arbiter.
1948 llvm::EquivalenceClasses<Port> tied = tiedMasters(flows);
1949 std::map<Port, std::set<int>> tiedArbiters;
1950 std::set<int> reserved = reservedAmsels[tileId];
1951 for (const auto &[amsel, masters] : plan.amselMasters) {
1952 reserved.insert(amsel);
1953 tiedArbiters[tied.getLeaderValue(masters.front())].insert(amsel %
1954 numArbiters);
1955 }
1956 SmallVector<std::pair<size_t, size_t>, 4> stuck;
1957 std::optional<ArbiterPlan> rested = planArbiters(
1958 targetModel, subset(rest),
1959 [&](size_t a, size_t b) { return conflict(rest[a], rest[b]); },
1960 [&](size_t f, int arbiter) {
1961 auto arbiters = tiedArbiters.find(
1962 tied.getLeaderValue(flows[rest[f]].masters.front()));
1963 return excluded(rest[f], arbiter) ||
1964 (arbiters != tiedArbiters.end() &&
1965 (arbiters->second.size() > 1 ||
1966 !arbiters->second.count(arbiter))) ||
1967 llvm::any_of(placed, [&](size_t g) {
1968 return arbiterOf(g) == arbiter &&
1969 flows[g].slave != flows[rest[f]].slave &&
1970 conflict(rest[f], g);
1971 });
1972 },
1973 reserved, stuck);
1974 if (!rested) {
1975 for (auto [a, b] : stuck)
1976 blocking.push_back({rest[a], rest[b]});
1977 for (size_t f : rest)
1978 for (size_t g : placed)
1979 if (flows[g].slave != flows[f].slave && conflict(f, g))
1980 blocking.push_back({g, f});
1981 return std::nullopt;
1982 }
1983 plan.slaveAmsels.insert(rested->slaveAmsels.begin(),
1984 rested->slaveAmsels.end());
1985 plan.amselMasters.insert(rested->amselMasters.begin(),
1986 rested->amselMasters.end());
1987 return plan;
1988 };
1989 SmallVector<std::pair<size_t, size_t>, 4> first;
1990 if (std::optional<ArbiterPlan> placed =
1991 around(*plan, priority, others, first))
1992 return placed;
1993
1994 llvm::EquivalenceClasses<Port> tied = tiedMasters(flows);
1995 SmallVector<size_t, 8> joint(priority), rest;
1996 for (size_t f : others) {
1997 bool tiedToPriority = llvm::any_of(priority, [&](size_t g) {
1998 return tied.isEquivalent(flows[g].masters.front(),
1999 flows[f].masters.front());
2000 });
2001 (tiedToPriority ? joint : rest).push_back(f);
2002 }
2003 stuck.clear();
2004 std::optional<ArbiterPlan> together;
2005 if (joint.size() > priority.size())
2006 together = planArbiters(
2007 targetModel, subset(joint),
2008 [&](size_t a, size_t b) { return conflict(joint[a], joint[b]); },
2009 [&](size_t f, int arbiter) { return excluded(joint[f], arbiter); },
2010 reservedAmsels[tileId], stuck);
2011 if (!together) {
2012 blocking.append(first.begin(), first.end());
2013 return std::nullopt;
2014 }
2015 return around(*together, joint, rest, blocking);
2016}
2017
2018void PacketFlowRouting::moveFlow(TileID tileId, FlowKey key, bool priority) {
2019 auto move = [&](const Connect &c) {
2020 hazardConnections.insert({tileId, c});
2021 if (priority)
2022 priorityConnections.insert({tileId, c});
2023 };
2024 auto flows = tileSlaveFlows.find(tileId);
2025 if (flows != tileSlaveFlows.end())
2026 if (auto f = flows->second.find(key); f != flows->second.end())
2027 for (Port m : f->second.masters)
2028 move({key.first, m});
2029 for (const Connect &hop : circuitHops[tileId])
2030 if (hop.src == key.first)
2031 move(hop);
2032}
2033
2034// Moves `key` with its whole unit (see planArbiters): a flow's arbiter is
2035// fixed by every flow reaching its master ports too.
2036void PacketFlowRouting::moveUnit(TileID tileId, FlowKey key) {
2037 moveFlow(tileId, key);
2038 auto flows = tileSlaveFlows.find(tileId);
2039 if (flows == tileSlaveFlows.end())
2040 return;
2041 auto self = flows->second.find(key);
2042 if (self == flows->second.end())
2043 return;
2044 llvm::EquivalenceClasses<Port> tied =
2045 tiedMasters(llvm::make_second_range(flows->second));
2046 for (const auto &[other, f] : flows->second)
2047 if (f.masters.size() > 1 &&
2048 tied.isEquivalent(f.masters.front(), self->second.masters.front()))
2049 moveFlow(tileId, other);
2050}
2051
2052void PacketFlowRouting::splitFlow(TileID tileId, FlowKey key,
2053 ArrayRef<FlowKey> partners) {
2054 auto flows = tileSlaveFlows.find(tileId);
2055 if (flows == tileSlaveFlows.end())
2056 return;
2057 auto self = flows->second.find(key);
2058 if (self == flows->second.end())
2059 return;
2060 auto onlySource = [&](FlowKey k) -> std::optional<PathEndPoint> {
2061 auto sources = slaveFlowSources.find({{tileId, k.first}, k.second});
2062 if (sources == slaveFlowSources.end() || sources->second.size() != 1)
2063 return std::nullopt;
2064 return sources->second.begin()->first;
2065 };
2066 std::optional<PathEndPoint> src = onlySource(key);
2067 if (!src)
2068 return;
2069 auto sharesMaster = [&](const auto &f, const std::set<Port> &ports) {
2070 return llvm::any_of(f.masters, [&](Port m) { return ports.count(m); });
2071 };
2072 std::set<Port> own(self->second.masters.begin(), self->second.masters.end());
2073 std::set<FlowKey> siblings;
2074 for (const auto &[other, f] : flows->second)
2075 if (other != key && other.first == key.first && sharesMaster(f, own) &&
2076 onlySource(other) == src)
2077 siblings.insert(other);
2078 // The masters tied to `partner`'s arbiter, not through `key`, nor through
2079 // its siblings if `skipSiblings`.
2080 auto tied = [&](FlowKey partner, bool skipSiblings) {
2081 llvm::EquivalenceClasses<Port> classes =
2082 tiedMasters(llvm::make_filter_range(
2083 llvm::make_second_range(flows->second), [&](const SlaveFlow &f) {
2084 FlowKey other{f.slave, f.id};
2085 return other != key && !(skipSiblings && siblings.count(other));
2086 }));
2087 auto unit = classes.members(flows->second.at(partner).masters.front());
2088 return std::set<Port>(unit.begin(), unit.end());
2089 };
2090 auto split = [&](FlowKey other,
2091 std::optional<PathEndPoint> apart = std::nullopt) {
2092 int a = key.second, b = other.second;
2093 if (!apart && a > b)
2094 std::swap(a, b);
2095 hazardSplits.insert({*src, tileId, a, b, apart});
2096 };
2097 for (FlowKey partner : partners) {
2098 if (partner == key || !flows->second.count(partner))
2099 continue;
2100 if (siblings.count(partner)) {
2101 split(partner);
2102 continue;
2103 }
2104 std::set<Port> partnerUnit = tied(partner, true);
2105 if (sharesMaster(self->second, partnerUnit))
2106 continue;
2107 // A sibling sharing a routing port with the partner's tree ties `key` to
2108 // its arbiter; leaving that port undoes the tie, so move off before split.
2109 bool unjoined = false;
2110 for (FlowKey other : siblings)
2111 for (Port m : flows->second.find(other)->second.masters)
2112 if (partnerUnit.count(m) && isDirectional(m.bundle)) {
2113 hazardConnections.insert({tileId, {other.first, m}});
2114 unjoined = true;
2115 }
2116 if (unjoined)
2117 continue;
2118 std::set<Port> unit = tied(partner, false);
2119 for (FlowKey other : siblings) {
2120 const SlaveFlow &f = flows->second.find(other)->second;
2121 if (!sharesMaster(f, unit))
2122 continue;
2123 // Where the sibling only ties `key` to the partner's arbiter by
2124 // destinations on this tile, those can reach it by a slave port of
2125 // their own, and `key` keeps sharing the rest of the tree.
2126 SmallVector<PathEndPoint, 2> apart;
2127 for (Port m : f.masters)
2128 if (partnerUnit.count(m))
2129 apart.push_back({tileId, m});
2130 if (PathEndPoint{tileId, key.first} == *src || apart.empty() ||
2131 !llvm::all_of(apart, [&](const PathEndPoint &p) {
2132 return packetStreamIndex.count({*src, p, other.second});
2133 })) {
2134 split(other);
2135 continue;
2136 }
2137 for (const PathEndPoint &p : apart)
2138 split(other, p);
2139 }
2140 }
2141}
2142
2143// Plans the arbiters of every switchbox on the routing. Where that fails, the
2144// RoutingFailure names the connections in the way.
2145llvm::Expected<PacketPlan> PacketFlowRouting::plan() {
2146 collectFlows();
2147 findCircuitHops();
2148 collectSlaveFlows();
2149 checkRules();
2150 planTiles();
2151 if (!planFailure)
2152 planFailure = breakHoldCycles();
2153 if (planFailure)
2154 return llvm::make_error<RoutingFailure>(std::move(*planFailure), faults());
2155 return PacketPlan(std::move(*this));
2156}
2157
2158RoutingFaults PacketFlowRouting::faults() const {
2159 RoutingFaults faults;
2160 faults.connections.assign(hazardConnections.begin(), hazardConnections.end());
2161 faults.splits.assign(hazardSplits.begin(), hazardSplits.end());
2162 faults.crowded.assign(crowdedTiles.begin(), crowdedTiles.end());
2163 faults.apart.assign(hazardApart.begin(), hazardApart.end());
2164 faults.together.assign(hazardTogether.begin(), hazardTogether.end());
2165 faults.untrunk.assign(hazardUntrunk.begin(), hazardUntrunk.end());
2166 faults.onlyPriorityMasters = !priorityConnections.empty() &&
2167 hazardSplits.empty() && crowdedTiles.empty() &&
2168 hazardApart.empty() && hazardUntrunk.empty() &&
2169 hazardConnections == priorityConnections;
2170 return faults;
2171}
2172
2173void PacketFlowRouting::checkRules() {
2174 // A slave port holds a few packet rules, and how many its flows need depends
2175 // on which ids leave by the same master ports.
2176 std::map<PhysPort, SmallVector<std::pair<int, int>>> existingCubes;
2177 for (auto swbox : device.getOps<SwitchboxOp>())
2178 for (auto rules : swbox.getConnections().getOps<PacketRulesOp>())
2179 for (auto rule : rules.getRules().getOps<PacketRuleOp>())
2180 existingCubes[{swbox.getTileOp().getTileID(), rules.sourcePort()}]
2181 .push_back({rule.maskInt(), rule.valueInt()});
2182 struct RuleGroup {
2183 SmallVector<std::pair<int, int>, 4> stated;
2184 SmallVector<int, 4> derived;
2185 };
2186 for (const auto &[slaveFlow, sources] : slaveFlowSources) {
2187 const auto &[first, firstMasters] = *sources.begin();
2188 auto other = llvm::find_if(
2189 sources, [&, &firstMasters = firstMasters](const auto &source) {
2190 return source.second != firstMasters;
2191 });
2192 if (other == sources.end())
2193 continue;
2194 const auto &[slavePort, id] = slaveFlow;
2195 TileID tileId = slavePort.first;
2196 moveFlow(tileId, {slavePort.second, id});
2197 if (planFailure)
2198 continue;
2199 const PathEndPoint &second = other->first;
2200 planFailure = llvm::formatv(
2201 "at tile ({0}, {1}), packets with id {2} from {3} and {4} enter on {5} "
2202 "and leave by different ports; a switchbox routes on the id alone, so "
2203 "each source's packets would also go where the other's do.",
2204 tileId.col, tileId.row, id, describeTilePort(first.coords, first.port),
2205 describeTilePort(second.coords, second.port),
2206 describePort(slavePort.second));
2207 }
2208 for (const auto &[tileId, byFlow] : tileSlaveFlows) {
2209 auto newRules =
2210 [&, tileId = tileId, &byFlow = byFlow](
2211 Port slave, std::optional<std::pair<PathEndPoint, Port>> without,
2212 bool priorityOnly,
2213 SmallVector<SmallVector<Port, 4>> *groupMasters = nullptr) {
2214 std::map<std::pair<bool, SmallVector<Port, 4>>, RuleGroup> groups;
2215 for (const auto &[key, f] : byFlow) {
2216 if (f.slave != slave || (priorityOnly && !f.isPriority))
2217 continue;
2218 SmallVector<Port, 4> masters = f.masters;
2219 auto sources = slaveFlowSources.find({{tileId, slave}, f.id});
2220 if (without && sources != slaveFlowSources.end()) {
2221 std::set<Port> kept;
2222 for (const auto &[src, ports] : sources->second)
2223 for (Port m : ports)
2224 if (!(src == without->first) || m != without->second)
2225 kept.insert(m);
2226 masters.assign(kept.begin(), kept.end());
2227 }
2228 if (masters.empty())
2229 continue;
2230 RuleGroup &group = groups[{f.isPriority, masters}];
2231 auto cubes = statedCubes({{tileId, f.slave}, f.id}, idMask);
2232 if (cubes.empty())
2233 group.derived.push_back(f.id);
2234 for (auto cube : cubes)
2235 if (!llvm::is_contained(group.stated, cube))
2236 group.stated.push_back(cube);
2237 }
2238 SmallVector<GroupClaims> claims;
2239 for (const auto &[masters, group] : groups) {
2240 claims.push_back({group.stated, group.derived, masters.first});
2241 if (groupMasters)
2242 groupMasters->push_back(masters.second);
2243 }
2244 return slavePortRules(claims, existingCubes[{tileId, slave}], idBits,
2245 targetModel.getNumSlaveSlots());
2246 };
2247 auto rulesNeeded =
2248 [&, tileId = tileId](
2249 Port slave,
2250 std::optional<std::pair<PathEndPoint, Port>> without = {}) {
2251 return existingCubes[{tileId, slave}].size() +
2252 newRules(slave, without, false).size();
2253 };
2254 // Packets for a destination on the tile that reach it by a slave port of
2255 // their own take their rules with them. The source's tree splits apart the
2256 // destination that frees the most rules on `slave`, if one frees any.
2257 auto splitRules = [&, tileId = tileId, &byFlow = byFlow](Port slave) {
2258 std::map<PathEndPoint, std::map<PathEndPoint, std::set<int>>> dstIds;
2259 for (const auto &[key, f] : byFlow) {
2260 if (f.slave != slave)
2261 continue;
2262 auto streams = slaveFlowStreams.find({{tileId, slave}, f.id});
2263 if (streams == slaveFlowStreams.end())
2264 continue;
2265 for (size_t i : streams->second) {
2266 const RoutedStream &s = conflicts.getStreams()[i];
2267 dstIds[{s.src.tile, s.src.port}][{s.dst.tile, s.dst.port}].insert(
2268 f.id);
2269 }
2270 }
2271 std::optional<std::pair<PathEndPoint, PathEndPoint>> best;
2272 size_t fewest = rulesNeeded(slave);
2273 for (const auto &[src, dsts] : dstIds)
2274 for (const auto &[dst, ids] : dsts)
2275 if (dst.coords == tileId && dsts.size() > 1)
2276 if (size_t n = rulesNeeded(slave, {{src, dst.port}}); n < fewest) {
2277 fewest = n;
2278 best = {src, dst};
2279 }
2280 if (!best)
2281 return false;
2282 const auto &[src, apart] = *best;
2283 const std::set<int> &apartIds = dstIds[src][apart];
2284 for (const auto &[dst, ids] : dstIds[src]) {
2285 auto carries = [&, &src = src, &dst = dst](int id) {
2286 return packetStreamIndex.count({src, dst, id}) > 0;
2287 };
2288 auto b = llvm::find_if_not(apartIds, carries);
2289 if (!(dst == apart) && b != apartIds.end())
2290 hazardSplits.insert({src, tileId, *ids.begin(), *b, apart});
2291 }
2292 return true;
2293 };
2294 // Flows on one slave port that leave by different master ports must not
2295 // claim a common id, and a mask written on an aie.packet_flow claims every
2296 // id it matches.
2297 auto claim = [&, tileId = tileId](const SlaveFlow &f) {
2298 auto cubes = statedCubes({{tileId, f.slave}, f.id}, idMask);
2299 if (cubes.empty())
2300 cubes.push_back({idMask, f.id});
2301 return cubes;
2302 };
2303 for (auto a = byFlow.begin(); a != byFlow.end(); ++a)
2304 for (auto b = std::next(a); b != byFlow.end(); ++b) {
2305 const SlaveFlow &fa = a->second, &fb = b->second;
2306 if (fa.slave != fb.slave || fa.masters == fb.masters)
2307 continue;
2308 std::optional<std::pair<std::pair<int, int>, std::pair<int, int>>>
2309 overlap;
2310 for (auto own : claim(fa))
2311 for (auto other : claim(fb))
2312 if (!overlap && cubesIntersect(own, other))
2313 overlap = {own, other};
2314 if (!overlap)
2315 continue;
2316 auto [own, other] = *overlap;
2317 moveFlow(tileId, a->first);
2318 moveFlow(tileId, b->first);
2319 if (planFailure)
2320 continue;
2321 int witness = (own.second & own.first) |
2322 (other.second & other.first & ~own.first);
2323 planFailure = llvm::formatv(
2324 "at tile ({0}, {1}), packet flows through {2} claim rule (mask "
2325 "0x{3:X-}, id 0x{4:X-}) and rule (mask 0x{5:X-}, id 0x{6:X-}), "
2326 "which both match id 0x{7:X-}; widen one mask to carry both, or "
2327 "route them apart.",
2328 tileId.col, tileId.row, describePort(fa.slave), own.first,
2329 own.second, other.first, other.second, witness);
2330 }
2331 std::set<Port> slaves;
2332 for (const auto &[key, f] : byFlow)
2333 slaves.insert(f.slave);
2334 std::set<Port> priorityMasters;
2335 std::set<SmallVector<Port, 4>> prioritySets;
2336 for (const auto &[key, f] : byFlow)
2337 if (f.isPriority && !pinned.rules.empty()) {
2338 priorityMasters.insert(f.masters.begin(), f.masters.end());
2339 prioritySets.insert(f.masters);
2340 }
2341 for (const auto &[key, f] : byFlow) {
2342 const Port *shared = llvm::find_if(
2343 f.masters, [&](Port m) { return priorityMasters.count(m); });
2344 if (f.isPriority || shared == f.masters.end() ||
2345 prioritySets.count(f.masters))
2346 continue;
2347 moveFlow(tileId, key, /*priority=*/true);
2348 if (!planFailure)
2349 planFailure = llvm::formatv(
2350 "at tile ({0}, {1}), packets with id {2} entering on {3} leave by "
2351 "{4}, a master port of the prioritized flows, but not by one of "
2352 "their fixed master sets.",
2353 tileId.col, tileId.row, f.id, describePort(f.slave),
2354 describePort(*shared));
2355 }
2356 for (Port slave : pinned.rules.empty() ? std::set<Port>{} : slaves) {
2357 SmallVector<SmallVector<Port, 4>> ruleMasters;
2358 SmallVector<PortRule> priority = newRules(slave, {}, true, &ruleMasters);
2359 for (const auto &[key, f] : byFlow) {
2360 if (f.slave != slave || f.isPriority)
2361 continue;
2362 for (auto own : claim(f)) {
2363 const auto *rule =
2364 llvm::find_if(priority, [&, &f = f](const PortRule &r) {
2365 return cubesIntersect(own, {r.mask, r.value}) &&
2366 ruleMasters[r.group] != f.masters;
2367 });
2368 if (rule == priority.end())
2369 continue;
2370 moveFlow(tileId, key);
2371 if (!planFailure)
2372 planFailure = llvm::formatv(
2373 "at tile ({0}, {1}), the packet rule (mask 0x{2:X-}, id "
2374 "0x{3:X-}) of the prioritized flows on "
2375 "{4} also matches packet id 0x{5:X-}, and priority routing "
2376 "keeps their rules; use an id the rule does not match, "
2377 "or route the flow apart.",
2378 tileId.col, tileId.row, rule->mask, rule->value,
2379 describePort(slave), f.id);
2380 break;
2381 }
2382 }
2383 }
2384 for (Port slave : slaves) {
2385 size_t needed = rulesNeeded(slave);
2386 if (needed <= targetModel.getNumSlaveSlots())
2387 continue;
2388 for (const auto &[key, f] : byFlow)
2389 if (f.slave == slave)
2390 moveFlow(tileId, key);
2391 if (!splitRules(slave))
2392 crowdedTiles.insert(tileId);
2393 if (planFailure)
2394 continue;
2395 planFailure = llvm::formatv(
2396 "at tile ({0}, {1}), the packet flows entering on {2} need {3} "
2397 "packet rules, and a slave port holds {4}.",
2398 tileId.col, tileId.row, describePort(slave), needed,
2399 targetModel.getNumSlaveSlots());
2400 }
2401 }
2402}
2403
2404void PacketFlowRouting::planTiles() {
2405 for (const auto &[tileId, flows] : tileFlows) {
2406 SmallVector<std::pair<size_t, size_t>, 4> blocking;
2407 if (std::optional<ArbiterPlan> plan = planTile(tileId, blocking)) {
2408 plans[tileId] = std::move(*plan);
2409 continue;
2410 }
2411 LLVM_DEBUG({
2412 llvm::dbgs() << "No arbiter plan at tile (" << tileId.col << ", "
2413 << tileId.row << "):\n";
2414 for (const SlaveFlow &f : flows) {
2415 llvm::dbgs() << " " << describePort(f.slave) << " id " << f.id
2416 << " ->";
2417 for (Port m : f.masters)
2418 llvm::dbgs() << ' ' << describePort(m);
2419 llvm::dbgs() << '\n';
2420 }
2421 for (auto [a, b] : blocking)
2422 llvm::dbgs() << " blocking " << a << ' ' << b << '\n';
2423 });
2424 std::string reason;
2425 llvm::raw_string_ostream os(reason);
2426 if (blocking.empty()) {
2427 // Ids a source sends out by master sets that overlap tie those sets to
2428 // one arbiter, so its tree branches them apart to free msels.
2429 for (const SlaveFlow &f : flows)
2430 for (const SlaveFlow &g : flows)
2431 if (f.slave == g.slave && f.id < g.id && f.masters != g.masters &&
2432 llvm::any_of(
2433 f.masters,
2434 [&](Port m) { return llvm::is_contained(g.masters, m); })) {
2435 FlowKey keys[] = {{f.slave, f.id}, {g.slave, g.id}};
2436 splitFlow(tileId, keys[0], keys);
2437 }
2438 for (const SlaveFlow &f : flows)
2439 moveFlow(tileId, {f.slave, f.id});
2440 crowdedTiles.insert(tileId);
2441 if (planFailure)
2442 continue;
2443 os << "at tile (" << tileId.col << ", " << tileId.row
2444 << "), the packet flows need more arbiter msels than the switchbox "
2445 "has free.";
2446 planFailure = std::move(reason);
2447 continue;
2448 }
2449 for (auto [a, b] : blocking) {
2450 FlowKey keys[] = {{flows[a].slave, flows[a].id},
2451 {flows[b].slave, flows[b].id}};
2452 for (FlowKey key : keys) {
2453 moveUnit(tileId, key);
2454 splitFlow(tileId, key, keys);
2455 }
2456 }
2457 if (planFailure)
2458 continue;
2459 std::optional<std::pair<size_t, size_t>> pair = conflictingStreams(
2460 tileId, flows[blocking.front().first], flows[blocking.front().second]);
2461 assert(pair && apart.empty() && offArbiter.empty() &&
2462 "before the hold-cycle search, only stream conflicts block a plan");
2463 auto [s, t] = *pair;
2464 os << describeStream(conflicts.getStreams()[s]) << " and "
2465 << describeStream(conflicts.getStreams()[t])
2466 << " can deadlock if they share an arbiter, and no routing found keeps "
2467 "them apart (last tried: tile ("
2468 << tileId.col << ", " << tileId.row << ")). " << conflicts.explain(s, t);
2469 planFailure = std::move(reason);
2470 }
2471}
2472
2473std::optional<std::string> PacketFlowRouting::breakHoldCycles() {
2474 // A packet holds every arbiter it has taken until its tail passes, so waits
2475 // chain from switchbox to switchbox, and planning each alone can close a
2476 // cycle of them. Breaking any one shared arbiter of such a cycle breaks it,
2477 // so the search tries each in turn, up to a budget.
2478 auto arbitrate = [&]() {
2479 for (size_t s = 0; s < conflicts.getRequestedStreams().size(); s++) {
2480 if (!conflicts.getStreams()[s].packetID)
2481 continue;
2482 for (StreamHop &hop : routes[s]) {
2483 hop.arbiter.reset();
2484 auto plan = plans.find(hop.tile);
2485 if (plan == plans.end())
2486 continue;
2487 auto amsel = plan->second.slaveAmsels.find(
2488 {hop.input, *conflicts.getStreams()[s].packetID});
2489 if (amsel != plan->second.slaveAmsels.end())
2490 hop.arbiter = amsel->second % numArbiters;
2491 }
2492 }
2493 };
2494 ArrayRef<RoutedStream> streams = conflicts.getStreams();
2495 size_t numRequested = conflicts.getRequestedStreams().size();
2496 // Every cycle the search meets: the routing moves the flows of each, as the
2497 // first may run only through flows it cannot move.
2498 SmallVector<HoldCycle, 2> cycles;
2499 int replans = 0;
2500 bool forcedWaits = false, definite = false;
2501 auto search = [&](auto &self) -> bool {
2502 arbitrate();
2503 std::optional<HoldCycle> cycle =
2504 conflicts.holdCycle(routes, forcedWaits, definite);
2505 // Waits `definite` drops still count where no receiver is shared, so a
2506 // replan must not close a cycle the first search broke.
2507 if (!cycle && definite)
2508 cycle = conflicts.holdCycle(routes);
2509 if (!cycle)
2510 return true;
2511 cycles.push_back(*cycle);
2512 LLVM_DEBUG(llvm::dbgs()
2513 << "Hold cycle: " << conflicts.explain(*cycle) << '\n');
2514 for (const HoldCycle::Step &step : cycle->steps) {
2515 if (step.wait != HoldCycle::Wait::Arbiter || step.forced)
2516 continue;
2517 FlowKey sharer{step.sharerInput, *streams[step.sharer].packetID};
2518 FlowKey holder{step.holderInput, *streams[step.holding].packetID};
2519 bool sharerNew = step.sharer < numRequested;
2520 bool holderNew = step.holding < numRequested;
2521 std::optional<std::tuple<TileID, FlowKey, FlowKey>> pair;
2522 std::optional<std::tuple<TileID, FlowKey, int>> off;
2523 if (sharerNew && holderNew)
2524 pair = {step.tile, std::min(sharer, holder), std::max(sharer, holder)};
2525 else if (sharerNew || holderNew)
2526 off = {step.tile, sharerNew ? sharer : holder, step.arbiter};
2527 else
2528 continue;
2529 if (replans == maxHoldCycleReplans)
2530 return false;
2531 if ((pair && !apart.insert(*pair).second) ||
2532 (off && !offArbiter.insert(*off).second))
2533 continue;
2534 replans++;
2535 ArbiterPlan saved = plans.at(step.tile);
2536 SmallVector<std::pair<size_t, size_t>, 4> blocking;
2537 if (std::optional<ArbiterPlan> plan = planTile(step.tile, blocking)) {
2538 plans[step.tile] = std::move(*plan);
2539 if (self(self))
2540 return true;
2541 plans[step.tile] = std::move(saved);
2542 }
2543 if (pair)
2544 apart.erase(*pair);
2545 if (off)
2546 offArbiter.erase(*off);
2547 }
2548 return false;
2549 };
2550 // The routing moves the flows of each cycle the search met, but for those
2551 // waiting at a receiver they share.
2552 auto move = [&] {
2553 arbitrate();
2554 for (const HoldCycle &cycle : cycles)
2555 for (const HoldCycle::Step &step : cycle.steps) {
2556 if (step.wait == HoldCycle::Wait::Arbiter && step.forced &&
2557 step.sharer < numRequested && step.holding < numRequested &&
2558 streams[step.sharer].packetID && streams[step.holding].packetID) {
2559 PathEndPoint a{streams[step.sharer].src.tile,
2560 streams[step.sharer].src.port},
2561 b{streams[step.holding].src.tile, streams[step.holding].src.port};
2562 if (!(a == b))
2563 hazardTogether.insert(std::minmax(a, b));
2564 }
2565 if (step.wait != HoldCycle::Wait::Drain && !step.forced) {
2566 SmallVector<FlowKey, 3> keys;
2567 for (auto [s, input] : {std::pair{step.waiting, step.sharerInput},
2568 std::pair{step.sharer, step.sharerInput},
2569 std::pair{step.holding, step.holderInput}})
2570 if (std::optional<int> id = streams[s].packetID;
2571 s < numRequested && id)
2572 keys.push_back({input, *id});
2573 for (FlowKey key : keys) {
2574 moveUnit(step.tile, key);
2575 splitFlow(step.tile, key, keys);
2576 }
2577 // On a link, `waiting` queues behind `holding` itself.
2578 size_t behind =
2579 step.wait == HoldCycle::Wait::Link ? step.waiting : step.sharer;
2580 if (behind >= numRequested || step.holding >= numRequested ||
2581 !streams[behind].packetID || !streams[step.holding].packetID)
2582 continue;
2583 PathEndPoint a{streams[behind].src.tile, streams[behind].src.port},
2584 b{streams[step.holding].src.tile, streams[step.holding].src.port};
2585 // holdCycle relates one source's trees only to themselves.
2586 if (!(a == b))
2587 hazardApart.insert(std::minmax(a, b));
2588 else if (step.wait == HoldCycle::Wait::Arbiter)
2589 hazardUntrunk.insert(a);
2590 }
2591 }
2592 };
2593 if (!search(search)) {
2594 move();
2595 return "packet flows can deadlock holding arbiters across "
2596 "switchboxes, and no arbiter assignment found avoids it. " +
2597 conflicts.explain(cycles.front());
2598 }
2599 // Trees into a receiver they share wait on each other at its master port
2600 // whatever the plan, so a cycle through such waits can only be broken
2601 // elsewhere along it. Where none of it can, the routing fails, unless some
2602 // plan has such cycles only by assumption.
2603 cycles.clear();
2604 replans = 0;
2605 forcedWaits = true;
2606 if (!search(search)) {
2607 LLVM_DEBUG(llvm::dbgs() << "Hold cycle at a shared receiver: "
2608 << conflicts.explain(cycles.front()) << '\n');
2609 cycles.clear();
2610 replans = 0;
2611 definite = true;
2612 if (!search(search)) {
2613 move();
2614 sharedReceiverCycle = cycles.front();
2615 }
2616 }
2617 return std::nullopt;
2618}
2619
2620LogicalResult PacketPlan::emit(DeviceOp device, OpBuilder &builder,
2621 DynamicTileAnalysis &analyzer) const {
2622 const AIETargetModel &targetModel = device.getTargetModel();
2623 const int numArbiters = targetModel.getNumArbiters();
2624 const int numMselsPerArbiter = targetModel.getNumMselsPerArbiter();
2625 const uint32_t maxPacketId = targetModel.getMaxPacketId();
2626 const int idBits = targetModel.getPacketIdBits();
2627 const int idMask = targetModel.getPacketIdMask();
2628 AIEDialect::PriorityRouteAttrHelper priority(builder.getContext());
2629 UnitAttr unit = builder.getUnitAttr();
2630
2631 // A master port can only be associated with one arbiter, and each arbiter
2632 // has numMselsPerArbiter msels, so a tile has numArbiters x
2633 // numMselsPerArbiter "logical" arbiters.
2634 //
2635 // A map from Tile and master selectValue to the ports targetted by that
2636 // master select.
2637 std::map<std::pair<TileID, int>, SmallVector<Port, 4>> masterAMSels;
2638 DenseMap<std::pair<PhysPort, int>, int> slaveAMSels;
2639 for (const auto &[tileId, plan] : plans) {
2640 for (const auto &[amsel, masters] : plan.amselMasters)
2641 masterAMSels[{tileId, amsel}].append(masters.begin(), masters.end());
2642 for (const auto &[flow, amsel] : plan.slaveAmsels)
2643 slaveAMSels[{{tileId, flow.first}, flow.second}] = amsel;
2644 }
2645
2646 // Compute the master set IDs
2647 // A map from a switchbox output port to its associated amsel values
2648 std::map<PhysPort, SmallVector<int, 4>> mastersets;
2649 for (const auto &[tileAmsel, ports] : masterAMSels)
2650 for (Port port : ports)
2651 mastersets[{tileAmsel.first, port}].push_back(tileAmsel.second);
2652
2653 LLVM_DEBUG({
2654 llvm::dbgs() << "CHECK mastersets\n";
2655 for (const auto &[master, values] : mastersets) {
2656 llvm::dbgs() << "master " << master.first << " "
2657 << stringifyWireBundle(master.second.bundle) << " : "
2658 << master.second.channel << '\n';
2659 for (int value : values)
2660 llvm::dbgs() << "amsel: " << value << '\n';
2661 }
2662 });
2663
2664 // Prioritized flows group apart from the others; the ids of a group share its
2665 // packet rules.
2666 SmallVector<SmallVector<std::pair<PhysPort, int>, 4>, 4> slaveGroups;
2667 SmallVector<std::pair<PhysPort, int>, 4> workList(slavePorts);
2668 while (!workList.empty()) {
2669 std::pair<PhysPort, int> slave = workList.pop_back_val();
2670 const SmallVector<PhysPort, 4> &dests = packetFlows.at(slave);
2671 auto *group = llvm::find_if(slaveGroups, [&](const auto &candidate) {
2672 const SmallVector<PhysPort, 4> &groupDests =
2673 packetFlows.at(candidate.front());
2674 return candidate.front().first.second == slave.first.second &&
2675 prioritizedFlows.contains(candidate.front()) ==
2676 prioritizedFlows.contains(slave) &&
2677 groupDests.size() == dests.size() &&
2678 llvm::all_of(dests, [&](const PhysPort &dest) {
2679 return llvm::is_contained(groupDests, dest);
2680 });
2681 });
2682 if (group != slaveGroups.end())
2683 group->push_back(slave);
2684 else
2685 slaveGroups.push_back({slave});
2686 }
2687
2688 // What each group claims on its slave port, as cubes, split into the rules
2689 // its flows state and the ids left for the cover to describe.
2690 SmallVector<SmallVector<std::pair<int, int>, 4>, 4> statedRules(
2691 slaveGroups.size());
2692 SmallVector<SmallVector<int, 4>, 4> derivedIds(slaveGroups.size());
2693 for (size_t gi = 0; gi < slaveGroups.size(); ++gi) {
2694 for (auto member : slaveGroups[gi]) {
2695 auto cubes = statedCubes(member, idMask);
2696 if (cubes.empty()) {
2697 derivedIds[gi].push_back(member.second);
2698 continue;
2699 }
2700 for (auto cube : cubes)
2701 if (!llvm::is_contained(statedRules[gi], cube))
2702 statedRules[gi].push_back(cube);
2703 }
2704 }
2705
2706 // Everything a group claims, for the other groups on its port to avoid.
2707 [[maybe_unused]] auto claimsOf = [&](size_t gi) {
2708 SmallVector<std::pair<int, int>, 8> claims(statedRules[gi].begin(),
2709 statedRules[gi].end());
2710 for (int id : derivedIds[gi])
2711 claims.push_back({idMask, id});
2712 return claims;
2713 };
2714
2715 // Realize the routes in MLIR
2716
2717 // Update tiles map if any new tile op declaration is needed for constructing
2718 // the flow.
2719 std::map<TileID, Operation *> tiles;
2720 for (auto tileOp : device.getOps<TileOp>())
2721 tiles[tileOp.getTileID()] = tileOp;
2722 for (const PhysPort &master : llvm::make_first_range(mastersets))
2723 tiles.try_emplace(master.first, analyzer.getTile(builder, master.first));
2724
2725 for (Operation *tileOp : llvm::make_second_range(tiles)) {
2726 TileOp tile = cast<TileOp>(tileOp);
2727 TileID tileId = tile.getTileID();
2728 Location tileLoc = tile.getLoc();
2729
2730 // Create a switchbox for the routes and insert inside it.
2731 builder.setInsertionPointAfter(tileOp);
2732 SwitchboxOp swbox =
2733 analyzer.getSwitchbox(builder, tile.colIndex(), tile.rowIndex());
2734 SwitchboxOp::ensureTerminator(swbox.getConnections(), builder, tileLoc);
2735 Block &b = swbox.getConnections().front();
2736 builder.setInsertionPoint(b.getTerminator());
2737
2738 if (auto hops = circuitHops.find(tileId); hops != circuitHops.end())
2739 for (const Connect &hop : hops->second) {
2740 SmallVector<std::pair<PhysPort, int>, 4> passing;
2741 for (const auto &flow : llvm::make_first_range(slaveFlowLocs))
2742 if (flow.first == PhysPort{tileId, hop.src})
2743 passing.push_back(flow);
2744 ConnectOp::create(builder, locOf(passing, tileLoc), hop.src.bundle,
2745 hop.src.channel, hop.dst.bundle, hop.dst.channel);
2746 }
2747
2748 // The master sets of this tile, in port order, and the amsels they take.
2749 auto tileMastersets =
2750 llvm::make_filter_range(mastersets, [&](const auto &entry) {
2751 return entry.first.first == tileId;
2752 });
2753 llvm::SmallBitVector amselNeeded(numMselsPerArbiter * numArbiters);
2754 for (const auto &[master, amsels] : tileMastersets)
2755 for (int amsel : amsels)
2756 amselNeeded.set(amsel);
2757 std::map<int, AMSelOp> amselOps;
2758 for (int msel = 0; msel < numMselsPerArbiter; msel++)
2759 for (int arbiter = 0; arbiter < numArbiters; arbiter++)
2760 if (int amsel = arbiter + msel * numArbiters; amselNeeded.test(amsel))
2761 amselOps[amsel] = AMSelOp::create(builder, tileLoc, arbiter, msel);
2762 for (auto amsel : b.getOps<AMSelOp>())
2763 amselOps.try_emplace(
2764 amsel.arbiterIndex() + amsel.getMselValue() * numArbiters, amsel);
2765 for (const auto &[master, msels] : tileMastersets) {
2766 SmallVector<Value, 4> amsels;
2767 for (int msel : msels)
2768 amsels.push_back(amselOps.at(msel));
2769 SmallVector<std::pair<PhysPort, int>, 4> feeding;
2770 for (const auto &[flow, dests] : packetFlows)
2771 if (llvm::is_contained(dests, master))
2772 feeding.push_back(flow);
2773 auto msOp = MasterSetOp::create(
2774 builder, locOf(feeding, tileLoc), builder.getIndexType(),
2775 master.second.bundle, master.second.channel, amsels,
2776 keepPktHeaderAttr.lookup(master));
2777 if (priorityMasterPorts.contains(master))
2778 priority.setAttr(msOp, unit);
2779 }
2780
2781 // Generate the packet rules, adding to any the switchbox already has.
2782 DenseMap<Port, PacketRulesOp> slaveRules;
2783 DenseMap<Port, SmallVector<PacketRuleOp>> existingRules;
2784 struct PortPlan {
2785 SmallVector<size_t, 4> groups;
2786 SmallVector<PortRule> rules;
2787 size_t emitted = 0;
2788 };
2789 std::map<Port, PortPlan> portPlans;
2790 for (auto rulesOp : b.getOps<PacketRulesOp>()) {
2791 slaveRules[rulesOp.sourcePort()] = rulesOp;
2792 llvm::append_range(existingRules[rulesOp.sourcePort()],
2793 rulesOp.getRules().getOps<PacketRuleOp>());
2794 }
2795 for (size_t gi = 0; gi < slaveGroups.size(); ++gi) {
2796 const auto &group = slaveGroups[gi];
2797 builder.setInsertionPoint(b.getTerminator());
2798
2799 auto port = group.front().first;
2800 if (tileId != port.first)
2801 continue;
2802
2803 Port slave = port.second;
2804
2805 SmallVector<int, 4> matchIds =
2806 llvm::to_vector<4>(llvm::make_second_range(group));
2807 for (int id : matchIds)
2808 if (id > static_cast<int>(maxPacketId)) {
2809 SmallVector<std::pair<PhysPort, int>> offending;
2810 for (const auto &flow : group)
2811 if (flow.second == id)
2812 offending.push_back(flow);
2813 return mlir::emitError(locOf(offending, tileLoc))
2814 << "packet id " << id << " exceeds the maximum of "
2815 << maxPacketId;
2816 }
2817
2818 // Rules the switchbox already has, e.g. hand-authored, match first.
2819 for (PacketRuleOp rule : existingRules.lookup(slave))
2820 for (int id : matchIds)
2821 if ((id & rule.maskInt()) == rule.valueInt()) {
2822 rule->emitOpError("can lead to false packet id match for id ")
2823 << id << ", which is not supposed to pass through this port.";
2824 rule->emitRemark("Please consider changing all uses of packet id ")
2825 << id << " to avoid deadlock.";
2826 return failure();
2827 }
2828
2829 // Groups on one slave port carry different destination sets, so
2830 // checkRules let no two of them claim the same id.
2831 assert(llvm::all_of(
2832 llvm::seq<size_t>(0, slaveGroups.size()),
2833 [&](size_t oi) {
2834 return oi == gi || slaveGroups[oi].front().first != port ||
2835 llvm::none_of(claimsOf(gi), [&](auto own) {
2836 return llvm::any_of(claimsOf(oi), [&](auto other) {
2837 return cubesIntersect(own, other);
2838 });
2839 });
2840 }) &&
2841 "groups on one slave port claim the same id");
2842
2843 // The rules of the slave port, planned at its first group, go out in
2844 // order: each group adds those up to its last.
2845 auto [planIt, fresh] = portPlans.try_emplace(slave);
2846 PortPlan &plan = planIt->second;
2847 if (fresh) {
2848 SmallVector<GroupClaims> claims;
2849 for (size_t oi = 0; oi < slaveGroups.size(); ++oi) {
2850 if (slaveGroups[oi].front().first != port)
2851 continue;
2852 plan.groups.push_back(oi);
2853 claims.push_back(
2854 {statedRules[oi], derivedIds[oi],
2855 prioritizedFlows.contains(slaveGroups[oi].front())});
2856 }
2857 SmallVector<std::pair<int, int>> existing;
2858 for (PacketRuleOp rule : existingRules.lookup(slave))
2859 existing.push_back({rule.maskInt(), rule.valueInt()});
2860 plan.rules = slavePortRules(claims, existing, idBits,
2861 targetModel.getNumSlaveSlots());
2862 LLVM_DEBUG({
2863 llvm::dbgs() << "packet rules " << describePort(slave) << ":";
2864 for (const PortRule &r : plan.rules)
2865 llvm::dbgs() << " rule(" << r.mask << ", " << r.value
2866 << ") -> group " << plan.groups[r.group];
2867 llvm::dbgs() << '\n';
2868 });
2869 }
2870
2871 assert(
2872 llvm::all_of(
2873 llvm::seq(0, idMask + 1),
2874 [&](int id) {
2875 bool own = llvm::is_contained(derivedIds[gi], id) ||
2876 llvm::any_of(statedRules[gi], [&](auto c) {
2877 return (id & c.first) == (c.second & c.first);
2878 });
2879 const auto *first =
2880 llvm::find_if(plan.rules, [&](const PortRule &r) {
2881 return (id & r.mask) == r.value;
2882 });
2883 return !own ||
2884 (first != plan.rules.end() &&
2885 slaveAMSels.at(
2886 slaveGroups[plan.groups[first->group]].front()) ==
2887 slaveAMSels.at(slaveGroups[gi].front()));
2888 }) &&
2889 "packet rules send a claimed id elsewhere");
2890
2891 size_t last = plan.emitted;
2892 for (size_t r = plan.emitted; r < plan.rules.size(); ++r)
2893 if (plan.groups[plan.rules[r].group] == gi)
2894 last = r + 1;
2895
2896 PacketRulesOp packetrules = slaveRules.lookup(slave);
2897 if (!packetrules) {
2898 packetrules = PacketRulesOp::create(builder, locOf(group, tileLoc),
2899 slave.bundle, slave.channel);
2900 PacketRulesOp::ensureTerminator(packetrules.getRules(), builder,
2901 tileLoc);
2902 slaveRules[slave] = packetrules;
2903 } else {
2904 // After the amsels its new rules use, and located at their flows too.
2905 packetrules->moveBefore(b.getTerminator());
2906 if (Location more = locOf(group, tileLoc); more != tileLoc)
2907 packetrules->setLoc(FusedLoc::get(builder.getContext(),
2908 {packetrules->getLoc(), more}));
2909 }
2910
2911 Block &rules = packetrules.getRules().front();
2912
2913 assert(llvm::range_size(rules.getOps<PacketRuleOp>()) +
2914 (last - plan.emitted) <=
2915 targetModel.getNumSlaveSlots() &&
2916 "checkRules lets a slave port take more rules than it holds");
2917
2918 builder.setInsertionPoint(rules.getTerminator());
2919 for (; plan.emitted < last; ++plan.emitted) {
2920 const PortRule &r = plan.rules[plan.emitted];
2921 const auto &ruleGroup = slaveGroups[plan.groups[r.group]];
2922 auto rule = PacketRuleOp::create(
2923 builder, locOf(ruleGroup, tileLoc), r.mask, r.value,
2924 amselOps.at(slaveAMSels.at(ruleGroup.front())));
2925 if (llvm::all_of(ruleGroup, [&](const auto &member) {
2926 return markedFlows.contains(member);
2927 }))
2928 priority.setAttr(rule, unit);
2929 }
2930 }
2931
2932 for (auto rulesOp : b.getOps<PacketRulesOp>()) {
2933 auto rules = rulesOp.getRules().front().getOps<PacketRuleOp>();
2934 if (rules.empty() || !llvm::all_of(rules, [&](PacketRuleOp rule) {
2935 return priority.isAttrPresent(rule);
2936 }))
2937 continue;
2938 priority.setAttr(rulesOp, unit);
2939 for (auto rule : rules)
2940 priority.removeAttr(rule);
2941 }
2942 }
2943 return success();
2944}
2945
2946LogicalResult AIEPathfinderPass::runOnPacketFlow(
2947 DeviceOp device, OpBuilder &builder, DynamicTileAnalysis &analyzer,
2948 const StreamConflicts &conflicts, const PacketPlan &plan, bool warn) {
2949 if (warn && plan.sharedReceiverCycle)
2950 emitWarning(device.getLoc(), sharedReceiverCycleReason)
2951 << conflicts.explain(*plan.sharedReceiverCycle);
2952 if (failed(plan.emit(device, builder, analyzer)))
2953 return failure();
2954 lowerShimDMAPorts(device, builder, analyzer);
2955 for (PacketFlowOp flow :
2956 llvm::make_early_inc_range(device.getOps<PacketFlowOp>()))
2957 flow.erase();
2958 return success();
2959}
2960
2961// A copy of `d` in a module like its own, as the analyses look up through it.
2962static DeviceOp cloneInScratch(DeviceOp d, OwningOpRef<ModuleOp> &scratch) {
2963 scratch = ModuleOp::create(d.getLoc());
2964 if (Operation *parent = d->getParentOp())
2965 (*scratch)->setAttrs(parent->getAttrDictionary());
2966 DeviceOp copy = d.clone();
2967 scratch->push_back(copy);
2968 return copy;
2969}
2970
2971// The router names a shim DMA by its own port, and the end of
2972// runOnPacketFlow moves it behind the shim mux onto a South channel. Rules and
2973// master sets a previous run left there are moved back first, so new flows on
2974// the same DMA channel share them.
2975static void unmuxShimDMAPacketPorts(DeviceOp device) {
2976 for (auto shimMux : device.getOps<ShimMuxOp>()) {
2977 auto hasConnect = [&](Port src, Port dst) {
2978 return llvm::any_of(shimMux.getConnections().getOps<ConnectOp>(),
2979 [&](ConnectOp c) {
2980 return c.sourcePort() == src && c.destPort() == dst;
2981 });
2982 };
2983 for (auto switchbox : device.getOps<SwitchboxOp>()) {
2984 if (switchbox.getTileOp() != shimMux.getTileOp())
2985 continue;
2986 for (auto rules : switchbox.getConnections().getOps<PacketRulesOp>())
2987 for (int ch : {0, 1}) {
2988 Port dma{WireBundle::DMA, ch};
2989 Port north{WireBundle::North, shimMuxChannelFrom(dma)};
2990 if (rules.sourcePort() == Port{WireBundle::South, north.channel} &&
2991 hasConnect(dma, north)) {
2992 rules.setSourceBundle(WireBundle::DMA);
2993 rules.setSourceChannel(ch);
2994 break;
2995 }
2996 }
2997 for (auto masterSet : switchbox.getConnections().getOps<MasterSetOp>())
2998 for (int ch : {0, 1}) {
2999 Port dma{WireBundle::DMA, ch};
3000 Port north{WireBundle::North, shimMuxChannelTo(dma)};
3001 if (masterSet.destPort() == Port{WireBundle::South, north.channel} &&
3002 hasConnect(north, dma)) {
3003 masterSet.setDestBundle(WireBundle::DMA);
3004 masterSet.setDestChannel(ch);
3005 break;
3006 }
3007 }
3008 }
3009 }
3010}
3011
3012llvm::Expected<PacketPlan> AIEPathfinderPass::route(
3013 DeviceOp d, DynamicTileAnalysis &analyzer, const StreamConflicts &conflicts,
3014 const PinnedRoutes &pinned, bool circuitSwitchHops, bool prioritize) {
3015 // Packet flows that can deadlock must not share an arbiter. Every routing
3016 // the router finds is checked by planning the arbiters on it, and one that
3017 // cannot be planned counts as illegal, so routing and allocation agree.
3018 std::map<PathEndPoint, SmallVector<size_t, 4>> streamsFrom;
3019 PacketConstraints constraints;
3020 constraints.pinned = pinned.trees;
3021 constraints.pinnedIds = pinned.ids;
3022 constraints.prioritize = prioritize;
3023 if (clRoutePacket && !d.getOps<PacketFlowOp>().empty()) {
3024 const AIETargetModel &targetModel = d.getTargetModel();
3025 if (llvm::Error err = unroutableArbiters(
3026 d, conflicts,
3027 [&](TileID tile) {
3028 return !circuitSwitchHops ||
3029 targetModel.hasShimMux(tile.col, tile.row);
3030 },
3031 pinned.trees))
3032 return std::move(err);
3033 for (auto [i, s] : llvm::enumerate(conflicts.getRequestedStreams()))
3034 if (s.packetID)
3035 streamsFrom[{s.src.tile, s.src.port}].push_back(i);
3036 constraints.apartAcross = [&](llvm::function_ref<bool(TileID)> low, bool up,
3037 size_t limit) {
3038 ArrayRef<RoutedStream> streams = conflicts.getStreams();
3039 SmallVector<size_t, 16> crossing;
3040 std::set<std::pair<TileID, Port>> srcs, dsts;
3041 for (auto [i, s] : llvm::enumerate(conflicts.getRequestedStreams()))
3042 if (s.packetID && low(s.src.tile) == up && low(s.dst.tile) != up) {
3043 crossing.push_back(i);
3044 srcs.insert({s.src.tile, s.src.port});
3045 dsts.insert({s.dst.tile, s.dst.port});
3046 }
3047 PacketsApart apart;
3048 // Streams kept apart have distinct sources and destinations.
3049 size_t most = std::min(srcs.size(), dsts.size());
3050 SmallVector<size_t, 8> best =
3051 most > limit
3052 ? largestApartSet(conflicts, crossing, limit)
3053 : SmallVector<size_t, 8>(
3054 crossing.begin(),
3055 crossing.begin() + std::min<size_t>(1, crossing.size()));
3056 for (size_t s : best)
3057 apart.flows.push_back(describeStream(streams[s]));
3058 if (best.size() > 1)
3059 apart.why = conflicts.explain(best[0], best[1]);
3060 return apart;
3061 };
3062 constraints.conflict = [&](const PathEndPoint &a, const std::set<int> &aIds,
3063 const PathEndPoint &b,
3064 const std::set<int> &bIds) {
3065 auto as = streamsFrom.find(a), bs = streamsFrom.find(b);
3066 if (as == streamsFrom.end() || bs == streamsFrom.end())
3067 return false;
3068 ArrayRef<RoutedStream> streams = conflicts.getStreams();
3069 for (size_t s : as->second)
3070 for (size_t t : bs->second)
3071 if (aIds.count(*streams[s].packetID) &&
3072 bIds.count(*streams[t].packetID) && conflicts.conflict(s, t))
3073 return true;
3074 return false;
3075 };
3076 constraints.check = [&](const Routing &routing) -> llvm::Error {
3077 PacketFlowRouting check(d, routing, conflicts, pinned, clRouteCircuit,
3078 circuitSwitchHops, prioritize);
3079 llvm::Expected<PacketPlan> plan = check.plan();
3080 if (!plan)
3081 return plan.takeError();
3082 RoutingFaults all = check.faults(), faults;
3083 faults.connections = std::move(all.connections);
3084 faults.apart = std::move(all.apart);
3085 faults.together = std::move(all.together);
3086 if (!plan->sharedReceiverCycle ||
3087 (faults.connections.empty() && faults.apart.empty() &&
3088 faults.together.empty()))
3089 return llvm::Error::success();
3090 return llvm::make_error<DeadlockProneRouting>(
3091 conflicts.explain(*plan->sharedReceiverCycle), std::move(faults));
3092 };
3093 }
3094 analyzer.pathfinder.setPacketConstraints(std::move(constraints));
3095 llvm::Error routed = analyzer.runAnalysis(d);
3096 analyzer.pathfinder.setPacketConstraints({});
3097 if (routed)
3098 return std::move(routed);
3099 if (!clRoutePacket)
3100 return PacketPlan();
3101 PacketFlowRouting found(d, analyzer.routing, conflicts, pinned,
3102 clRouteCircuit, circuitSwitchHops, prioritize);
3103 llvm::Expected<PacketPlan> plan = found.plan();
3104 if (found.incomplete) {
3105 llvm::consumeError(plan.takeError());
3106 return llvm::make_error<RoutingFailure>(std::move(found.incomplete->second),
3107 RoutingFaults{},
3108 found.incomplete->first);
3109 }
3110 // The routing found may still leave a hold cycle through receivers flows
3111 // share, as the check lets one through where it names nothing to move.
3112 if (!plan || clAllowDeadlockProne)
3113 return plan;
3114 const std::optional<HoldCycle> &cycle = plan->sharedReceiverCycle;
3115 if (!cycle)
3116 return plan;
3117 return llvm::make_error<DeadlockProneRouting>(
3118 (llvm::Twine(sharedReceiverCycleReason) + conflicts.explain(*cycle) +
3119 allowDeadlockProneHint)
3120 .str());
3121}
3122
3123static LogicalResult checkFixedFlowEndpoints(DeviceOp device) {
3124 DenseMap<PhysPort, Operation *> inputs, outputs;
3125 for (SwitchboxOp box : device.getOps<SwitchboxOp>()) {
3126 TileID tile = box.getTileOp().getTileID();
3127 for (ConnectOp connect : box.getOps<ConnectOp>()) {
3128 inputs[{tile, connect.sourcePort()}] = connect;
3129 outputs[{tile, connect.destPort()}] = connect;
3130 }
3131 for (MasterSetOp master : box.getOps<MasterSetOp>())
3132 outputs[{tile, master.destPort()}] = master;
3133 for (PacketRulesOp rules : box.getOps<PacketRulesOp>())
3134 inputs[{tile, rules.sourcePort()}] = rules;
3135 }
3136 AIEDialect::IsCtrlPktOverlayAttrHelper overlay(device.getContext());
3137 auto check = [&](Operation *flow, Value value, Port port,
3138 bool source) -> LogicalResult {
3139 auto tile = cast<TileOp>(value.getDefiningOp());
3140 auto &reservations = source ? inputs : outputs;
3141 Operation *reserved = reservations.lookup({tile.getTileID(), port});
3142 if (!reserved &&
3143 getTargetModel(tile).hasShimMux(tile.getCol(), tile.getRow()) &&
3144 llvm::is_contained({WireBundle::DMA, WireBundle::NOC, WireBundle::PLIO},
3145 port.bundle)) {
3146 Port south{WireBundle::South,
3147 source ? shimMuxChannelFrom(port) : shimMuxChannelTo(port)};
3148 reserved = reservations.lookup({tile.getTileID(), south});
3149 }
3150 auto packet = dyn_cast<PacketFlowOp>(flow);
3151 if (!reserved || (packet && isa<PacketRulesOp>(reserved)))
3152 return success();
3153 if (packet && !source && port.bundle == WireBundle::TileControl &&
3154 isa<MasterSetOp>(reserved) && overlay.isAttrPresent(reserved)) {
3155 auto master = cast<MasterSetOp>(reserved);
3156 if (AIE::keepsPktHeader(tile.getTileID(), port,
3157 packet.getKeepPktHeader()) !=
3158 master.keepsPktHeader()) {
3159 auto diag = emitError(flow->getLoc());
3160 diag << "keep_pkt_header conflicts with the control packet overlay at "
3161 << describeTilePort(tile.getTileID(), port);
3162 diag.attachNote(master.getLoc())
3163 << "TileControl master set "
3164 << (master.keepsPktHeader() ? "retains" : "drops")
3165 << " packet headers";
3166 return failure();
3167 }
3168 if (findExclusiveAMSel(master))
3169 return success();
3170 auto diag = emitError(flow->getLoc());
3171 diag << "control packet overlay has no TileControl-only amsel at "
3172 << describeTilePort(tile.getTileID(), port);
3173 diag.attachNote(reserved->getLoc())
3174 << "TileControl master set declared here";
3175 return failure();
3176 }
3177 bool fromOverlay = overlay.isAttrPresent(reserved);
3178 if (auto rules = dyn_cast<PacketRulesOp>(reserved))
3179 fromOverlay |= llvm::any_of(
3180 rules.getRules().getOps<PacketRuleOp>(),
3181 [&](PacketRuleOp rule) { return overlay.isAttrPresent(rule); });
3182 auto diag = emitError(flow->getLoc());
3183 diag << "Unable to find a legal routing: ";
3184 if (packet)
3185 diag << "packet flow " << packet.IDInt();
3186 else
3187 diag << "circuit flow";
3188 diag << (source ? " starts at " : " ends at ")
3189 << describeTilePort(tile.getTileID(), port) << ", whose "
3190 << (source ? "input" : "output") << " port is reserved by ";
3191 if (fromOverlay)
3192 diag << "the control packet overlay";
3193 else
3194 diag << "a fixed " << reserved->getName();
3195 diag.attachNote(reserved->getLoc())
3196 << (source ? "input" : "output") << " port reserved here by "
3197 << reserved->getName();
3198 return failure();
3199 };
3200 for (PacketFlowOp flow : device.getOps<PacketFlowOp>()) {
3201 for (PacketSourceOp source : flow.getPorts().getOps<PacketSourceOp>())
3202 if (failed(check(flow, source.getTile(), source.port(), true)))
3203 return failure();
3204 for (PacketDestOp dest : flow.getPorts().getOps<PacketDestOp>())
3205 if (failed(check(flow, dest.getTile(), dest.port(), false)))
3206 return failure();
3207 }
3208 for (FlowOp flow : device.getOps<FlowOp>())
3209 if (failed(check(flow, flow.getSource(),
3210 {flow.getSourceBundle(), flow.getSourceChannel()},
3211 true)) ||
3212 failed(check(flow, flow.getDest(),
3213 {flow.getDestBundle(), flow.getDestChannel()}, false)))
3214 return failure();
3215 return success();
3216}
3217
3218void AIEPathfinderPass::runOnOperation() {
3219
3220 // create analysis pass with routing graph for entire device
3221 LLVM_DEBUG(llvm::dbgs() << "---Begin AIEPathfinderPass---\n");
3222
3223 DeviceOp d = getOperation();
3224 if (failed(verifyDMAChannelsResolved(d)))
3225 return signalPassFailure();
3226 OpBuilder builder = OpBuilder::atBlockTerminator(d.getBody());
3227 if (clRoutePacket)
3228 unmuxShimDMAPacketPorts(d);
3229 if (failed(checkFixedFlowEndpoints(d)))
3230 return signalPassFailure();
3231
3232 StreamConflicts conflicts(d);
3233 if (auto pairs = conflicts.unavoidable(); !pairs.empty()) {
3234 InFlightDiagnostic diag =
3235 (clAllowDeadlockProne ? emitWarning(d.getLoc()) : emitError(d.getLoc()))
3236 << "Flows can deadlock however they are routed: "
3237 << conflicts.explain(pairs[0].first, pairs[0].second);
3238 if (pairs.size() > 1)
3239 diag << " So can " << pairs.size() - 1 << " other pair"
3240 << (pairs.size() > 2 ? "s" : "") << " of flows.";
3241 if (!clAllowDeadlockProne) {
3242 diag << allowDeadlockProneHint;
3243 return signalPassFailure();
3244 }
3245 }
3246 DynamicTileAnalysis analyzer;
3247 // A prioritized flow keeps the route it takes alone, so route the
3248 // prioritized flows without the rest of the design first, and pin their
3249 // trees for the rest to route around. Packets sharing a source and id with
3250 // a prioritized flow go with it (see prioritizedFlows); other packets from
3251 // their sources route freely.
3252 auto sourcesOf = [](PacketFlowOp flow) {
3253 return llvm::map_range(
3254 flow.getPorts().getOps<PacketSourceOp>(), [](PacketSourceOp src) {
3255 return PathEndPoint{
3256 cast<TileOp>(src.getTile().getDefiningOp()).getTileID(),
3257 src.port()};
3258 });
3259 };
3260 std::set<PathEndPoint> prioritized;
3261 std::set<std::pair<PathEndPoint, int>> prioritizedIds;
3262 for (PacketFlowOp flow : d.getOps<PacketFlowOp>())
3263 if (flow.getPriorityRoute().value_or(false))
3264 for (PathEndPoint src : sourcesOf(flow)) {
3265 prioritized.insert(src);
3266 prioritizedIds.insert({src, flow.IDInt()});
3267 }
3268 auto isPrioritized = [&](PacketFlowOp flow) {
3269 return llvm::any_of(sourcesOf(flow), [&](const PathEndPoint &src) {
3270 return prioritizedIds.count({src, flow.IDInt()}) > 0;
3271 });
3272 };
3273 auto routesAlone = isPrioritized;
3274 bool pinned = false;
3275 PinnedRoutes priority;
3276 bool othersToRoute = !d.getOps<FlowOp>().empty() ||
3277 !llvm::all_of(d.getOps<PacketFlowOp>(), routesAlone);
3278 // With no other flows to route, this routing is the route-alone one, so it
3279 // keeps off the avoided ports too.
3280 if (!othersToRoute)
3281 analyzer.avoidedPorts = avoidedPorts;
3282 if (clRoutePacket && !prioritized.empty() && othersToRoute) {
3283 OwningOpRef<ModuleOp> scratch;
3284 DeviceOp alone = cloneInScratch(d, scratch);
3285 SmallVector<Operation *> others;
3286 for (Operation &op : alone.getBody()->without_terminator()) {
3287 auto flow = dyn_cast<PacketFlowOp>(op);
3288 if (flow ? !routesAlone(flow) : isa<FlowOp>(op))
3289 others.push_back(&op);
3290 }
3291 for (Operation *op : others)
3292 op->dropAllReferences();
3293 for (Operation *op : others)
3294 op->erase();
3295 std::map<PathEndPoint, std::set<int>> aloneIds;
3296 for (PacketFlowOp flow : alone.getOps<PacketFlowOp>())
3297 for (auto src : flow.getPorts().getOps<PacketSourceOp>()) {
3298 auto tile = cast<TileOp>(src.getTile().getDefiningOp());
3299 aloneIds[{{tile.colIndex(), tile.rowIndex()}, src.port()}].insert(
3300 flow.IDInt());
3301 }
3302 DynamicTileAnalysis aloneAnalyzer;
3303 aloneAnalyzer.avoidedPorts = avoidedPorts;
3304 StreamConflicts aloneConflicts(alone);
3305 llvm::Expected<PacketPlan> alonePlan =
3306 route(alone, aloneAnalyzer, aloneConflicts, {},
3307 /*circuitSwitchHops=*/false);
3308 if (!alonePlan) {
3309 llvm::consumeError(alonePlan.takeError());
3310 } else {
3311 // The design's own routing keeps these trees, so it warns of any hold
3312 // cycle they leave.
3313 OpBuilder aloneBuilder = OpBuilder::atBlockTerminator(alone.getBody());
3314 if (failed(runOnPacketFlow(alone, aloneBuilder, aloneAnalyzer,
3315 aloneConflicts, *alonePlan, /*warn=*/false)))
3316 return signalPassFailure();
3317 priority = PinnedRoutes{aloneAnalyzer.routing.packetTrees,
3318 std::move(aloneIds), priorityRules(alone)};
3319 pinned = true;
3320 }
3321 }
3322 // If routing fails, the router relaxes how it routes packet flows (see
3323 // Pathfinder::relax) and tries again. The error is the first attempt's, or
3324 // the first to find a routing allow-deadlock-prone would take, as that is
3325 // all that keeps the design from routing.
3326 auto routeRelaxing = [&](DeviceOp dev, DynamicTileAnalysis &an,
3327 const StreamConflicts &c, const PinnedRoutes &pin,
3328 bool prioritize =
3329 true) -> llvm::Expected<PacketPlan> {
3330 // Every attempt of the ladder routes `dev` under the same constraints, so
3331 // one that replays an earlier attempt is skipped (see findPaths).
3332 std::vector<PathfinderAttempt> attempts;
3333 an.pathfinder.attempts = &attempts;
3334 llvm::scope_exit detach([&] { an.pathfinder.attempts = nullptr; });
3335 llvm::Expected<PacketPlan> plan =
3336 route(dev, an, c, pin, clCircuitSwitchHops, prioritize);
3337 if (plan)
3338 return plan;
3339 llvm::Error first = plan.takeError();
3340 while (an.pathfinder.relax()) {
3341 plan = route(dev, an, c, pin, clCircuitSwitchHops, prioritize);
3342 if (plan) {
3343 llvm::consumeError(std::move(first));
3344 return plan;
3345 }
3346 llvm::Error err = plan.takeError();
3347 if (err.isA<DeadlockProneRouting>() && !first.isA<DeadlockProneRouting>())
3348 std::swap(first, err);
3349 llvm::consumeError(std::move(err));
3350 }
3351 return std::move(first);
3352 };
3353 llvm::Expected<PacketPlan> plan =
3354 routeRelaxing(d, analyzer, conflicts, priority);
3355 if (!plan && !prioritized.empty()) {
3356 llvm::Error err = plan.takeError();
3357 priority = {};
3358 DynamicTileAnalysis freeAnalyzer;
3359 plan = routeRelaxing(d, freeAnalyzer, conflicts, priority,
3360 /*prioritize=*/false);
3361 if (plan) {
3362 llvm::consumeError(std::move(err));
3363 analyzer = std::move(freeAnalyzer);
3364 } else {
3365 llvm::Error freeErr = plan.takeError();
3366 if (freeErr.isA<DeadlockProneRouting>() ||
3367 !err.isA<DeadlockProneRouting>())
3368 std::swap(err, freeErr);
3369 llvm::consumeError(std::move(freeErr));
3370 plan = std::move(err);
3371 }
3372 pinned = false;
3373 }
3374 if (!plan) {
3375 llvm::handleAllErrors(plan.takeError(), [&](RoutingFailure &f) {
3376 // Say whether the pinned trees are what stands in the way: the design
3377 // routes if they may move.
3378 if (pinned && !f.reason.empty() &&
3379 !f.isA(PinnedRoutingFailure::classID())) {
3380 OwningOpRef<ModuleOp> scratch;
3381 DeviceOp free = cloneInScratch(d, scratch);
3382 DynamicTileAnalysis freeAnalyzer;
3383 StreamConflicts freeConflicts(free);
3384 llvm::Expected<PacketPlan> freePlan = routeRelaxing(
3385 free, freeAnalyzer, freeConflicts, {}, /*prioritize=*/false);
3386 if (!freePlan) {
3387 llvm::consumeError(freePlan.takeError());
3388 } else {
3389 f.reason = describePrioritized(llvm::to_vector(llvm::map_range(
3390 prioritized,
3391 [](const PathEndPoint &src) {
3392 return describeTilePort(src.coords, src.port);
3393 }))) +
3394 ", and the other flows route only if it moves. Around "
3395 "it, " +
3396 f.reason;
3397 }
3398 }
3399 emitError(f.loc.value_or(d.getLoc())) << f.message();
3400 });
3401 signalPassFailure();
3402 return;
3403 }
3404 for (auto flowOp : d.getOps<FlowOp>()) {
3405 if (!flowOp.getVias().empty()) {
3406 flowOp.emitOpError("cannot be routed while it carries via waypoints; run "
3407 "--aie-split-flow-vias first to lower the vias into "
3408 "switchbox connections");
3409 signalPassFailure();
3410 return;
3411 }
3412 }
3413 for (auto flowOp : d.getOps<PacketFlowOp>()) {
3414 if (!flowOp.getVias().empty()) {
3415 flowOp.emitOpError("cannot be routed while it carries via waypoints; run "
3416 "--aie-split-flow-vias first to lower the vias into "
3417 "switchbox connections");
3418 signalPassFailure();
3419 return;
3420 }
3421 }
3422
3423 if (clRouteCircuit && failed(runOnFlow(d, analyzer))) {
3424 signalPassFailure();
3425 return;
3426 }
3427 if (clRoutePacket && failed(runOnPacketFlow(d, builder, analyzer, conflicts,
3428 *plan, /*warn=*/true))) {
3429 signalPassFailure();
3430 return;
3431 }
3432 // Populate wires between switchboxes and tiles. Re-running the pass on
3433 // already-routed IR must not duplicate the wires a previous run emitted, so
3434 // key the wires already present and emit only the missing ones.
3435 builder.setInsertionPoint(d.getBody()->getTerminator());
3436 llvm::DenseSet<std::tuple<Value, int, Value, int>> existingWires;
3437 // aie.wire is a physical connection, so the IR may spell one adjacency in
3438 // either operand order.
3439 auto recordWire = [&](Value source, int sourceBundle, Value dest,
3440 int destBundle) {
3441 bool absent =
3442 !existingWires.contains({source, sourceBundle, dest, destBundle}) &&
3443 !existingWires.contains({dest, destBundle, source, sourceBundle});
3444 existingWires.insert({source, sourceBundle, dest, destBundle});
3445 existingWires.insert({dest, destBundle, source, sourceBundle});
3446 return absent;
3447 };
3448 for (auto wire : d.getOps<WireOp>()) {
3449 recordWire(wire.getSource(), static_cast<int>(wire.getSourceBundle()),
3450 wire.getDest(), static_cast<int>(wire.getDestBundle()));
3451 }
3452 auto wire = [&](Location loc, Value source, WireBundle sourceBundle,
3453 Value dest, WireBundle destBundle) {
3454 if (recordWire(source, static_cast<int>(sourceBundle), dest,
3455 static_cast<int>(destBundle))) {
3456 WireOp::create(builder, loc, source, sourceBundle, dest, destBundle);
3457 }
3458 };
3459 for (int col = 0; col <= analyzer.getMaxCol(); col++) {
3460 for (int row = 0; row <= analyzer.getMaxRow(); row++) {
3461 TileOp tile = analyzer.lookupTile({col, row});
3462 SwitchboxOp sw = analyzer.lookupSwitchbox({col, row});
3463 if (!tile || !sw)
3464 continue;
3465 Location loc = tile.getLoc();
3466 // connections east-west between stream switches
3467 if (col > 0)
3468 if (SwitchboxOp westsw = analyzer.lookupSwitchbox({col - 1, row}))
3469 wire(loc, westsw, WireBundle::East, sw, WireBundle::West);
3470 if (row > 0) {
3471 // connections between abstract 'core' of tile
3472 wire(loc, tile, WireBundle::Core, sw, WireBundle::Core);
3473 // connections between abstract 'dma' of tile
3474 wire(loc, tile, WireBundle::DMA, sw, WireBundle::DMA);
3475 // connections north-south inside array ( including connection to shim
3476 // row)
3477 if (SwitchboxOp southsw = analyzer.lookupSwitchbox({col, row - 1}))
3478 wire(loc, southsw, WireBundle::North, sw, WireBundle::South);
3479 } else if (tile.isShimNOCTile()) {
3480 if (!d.getTargetModel().hasShimMux(col, row)) {
3481 // Without a shim mux the shim DMA attaches to the switchbox.
3482 wire(loc, tile, WireBundle::DMA, sw, WireBundle::DMA);
3483 } else if (ShimMuxOp shimsw = analyzer.lookupShimMux(col)) {
3484 wire(loc, shimsw,
3485 WireBundle::North, // Changed to connect into the north
3486 sw, WireBundle::South);
3487 // abstract 'DMA' connection on tile is attached to shim mux ( in
3488 // row 0 )
3489 wire(loc, tile, WireBundle::DMA, shimsw, WireBundle::DMA);
3490 }
3491 }
3492 }
3493 }
3494}
3495
3496std::unique_ptr<OperationPass<DeviceOp>> AIE::createAIEPathfinderPass() {
3497 return std::make_unique<AIEPathfinderPass>();
3498}
3499
3500std::unique_ptr<OperationPass<DeviceOp>>
3501AIE::createAIEPathfinderPass(const AIERoutePathfinderFlowsOptions &options) {
3502 return std::make_unique<AIEPathfinderPass>(options);
3503}
3504
3505std::unique_ptr<OperationPass<DeviceOp>>
3506AIE::createAIEPathfinderPass(const AIERoutePathfinderFlowsOptions &options,
3507 ArrayRef<std::pair<TileID, Port>> avoidedPorts) {
3508 auto pass = std::make_unique<AIEPathfinderPass>(options);
3509 pass->avoidedPorts.assign(avoidedPorts.begin(), avoidedPorts.end());
3510 return pass;
3511}
constexpr int maxSearchSteps
std::pair< TileID, Port > PhysPort
constexpr int maxHoldCycleReplans
std::map< PhysPort, SmallVector< std::tuple< int, int, int >, 2 > > PriorityRules
(mask, value, amsel) by slave port, in slot order.
std::tuple< int, int, int, int, int, int, int, int, int, int > FlowKey
virtual uint32_t getNumMselsPerArbiter() const =0
Return the number of master select values per stream-switch arbiter.
virtual uint32_t getNumArbiters() const =0
Return the number of arbiters per stream switch.
virtual int rows() const =0
Return the number of rows in the device.
bool isShimNOCTile(int col, int row) const
Return true if the given tile is a ShimNOC tile.
virtual uint32_t getMaxPacketId() const =0
Return the largest packet id the stream switch can route.
virtual int columns() const =0
Return the number of columns in the device.
int getPacketIdBits() const
Bits a packet id spans, and the mask a switch's id match uses.
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 getNumSlaveSlots() const =0
Return the number of packet-rule slots per stream-switch slave port.
virtual bool hasShimMux(int col, int row) const
True if the tile's DMA/NOC/PLIO ports sit behind an aie.shim_mux; otherwise its DMA is routed in the ...
ShimMuxOp getShimMux(mlir::OpBuilder &builder, int col)
SwitchboxOp getSwitchbox(mlir::OpBuilder &builder, int col, int row)
SwitchboxOp lookupSwitchbox(TileID tile) const
TileOp lookupTile(TileID tile) const
TileOp getTile(mlir::OpBuilder &builder, int col, int row)
llvm::Error runAnalysis(DeviceOp &device)
std::set< PathEndPoint > processedFlows
ShimMuxOp lookupShimMux(int col) const
std::vector< std::pair< TileID, Port > > avoidedPorts
void setPacketConstraints(PacketConstraints c)
std::optional< mlir::Location > loc
The streams a device asks for or already routes, and which pairs of them must not share an arbiter or...
llvm::ArrayRef< RoutedStream > getRequestedStreams() const
The streams the flow ops ask for, which come first in getStreams().
llvm::SmallVector< std::pair< size_t, size_t > > unavoidable() const
The requested streams where the first can hold up the second however they are routed,...
bool mustSeparate(size_t s, size_t t) const
Whether a routing that puts packet streams s and t on one arbiter anywhere has a hold cycle: they con...
llvm::ArrayRef< RoutedStream > getStreams() const
bool conflict(size_t s, size_t t) const
Whether s and t can deadlock if they share an arbiter or a link.
std::optional< HoldCycle > holdCycle(llvm::ArrayRef< llvm::SmallVector< StreamHop, 8 > > routes, bool forcedWaits=false, bool definite=false) const
A cycle of waits the packet streams can deadlock in when routed along routes, indexed like getStreams...
std::string explain(size_t s, size_t t) const
Why s and t conflict.
int shimMuxChannelTo(Port dst)
struct Connect { Port src; Port dst; bool operator==(const Connect &rhs) const { return std::tie(src, dst)==std::tie(rhs.src, rhs.dst); } bool operator!=(const Connect &rhs) const { return !(*this==rhs);} bool operator<(const Connect &rhs) const { return std::tie(src, dst)< std::tie(rhs.src, rhs.dst); } } Connect
Definition AIEDialect.h:305
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
bool isDirectional(WireBundle bundle)
Definition AIEDialect.h:531
std::string describeStream(const RoutedStream &stream)
Names the stream by its endpoints and packet id, e.g.
std::optional< std::pair< TileID, Port > > getLinkedInput(TileID tile, Port output)
The switchbox input driven by an output's physical wire, with the channel preserved.
const AIETargetModel & getTargetModel(mlir::Operation *op)
bool keepsPktHeader(TileID tile, Port master, std::optional< bool > keep)
mlir::LogicalResult verifyDMAChannelsResolved(DeviceOp device)
int shimMuxChannelFrom(Port src)
std::string describeTilePort(TileID tile, Port port)
Names a tile port the way diagnostics do, e.g. "(0, 2) DMA:1".
struct Port { WireBundle bundle; int channel; bool operator==(const Port &rhs) const { return std::tie(bundle, channel)==std::tie(rhs.bundle, rhs.channel); } bool operator!=(const Port &rhs) const { return !(*this==rhs);} bool operator<(const Port &rhs) const { return std::tie(bundle, channel)< std::tie(rhs.bundle, rhs.channel); } friend std::ostream &operator<<(std::ostream &os, const Port &port) { os<< "("; os<< stringifyWireBundle(port.bundle).str(); os<< ": "<< std::to_string(port.channel)<< ")"; return os; } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Port &port) { os<< to_string(port); return os; } } Port
Definition AIEDialect.h:265
std::map< TileID, SwitchSetting > SwitchSettings
std::unique_ptr< mlir::OperationPass< DeviceOp > > createAIEPathfinderPass()
std::string describePort(Port port)
Names a port the way diagnostics do, e.g. "DMA:1".
std::map< PathEndPoint, std::vector< TreeHop > > PacketTrees
std::map< PathEndPoint, std::set< int > > ids
bool forced
The wait holds however the arbiters are planned, as sharer and holding go into a receiver they share ...
std::map< PathEndPoint, std::set< int > > pinnedIds
std::vector< std::string > flows
std::optional< int > packetID
The packet id carried, if any.
std::vector< std::pair< TileID, Connect > > connections
std::vector< PathEndPoint > untrunk
std::vector< std::pair< PathEndPoint, PathEndPoint > > together
std::vector< TreeSplit > splits
std::vector< TileID > crowded
std::vector< std::pair< PathEndPoint, PathEndPoint > > apart
std::map< PathEndPoint, SwitchSettings > settings
std::map< std::pair< PathEndPoint, int >, SwitchSettings > idSettings