MLIR-AIE 1.4.6.dev
AIEPathFinder.cpp
Go to the documentation of this file.
1//===- AIEPathFinder.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
11#include "d_ary_heap.h"
12
13#include "llvm/ADT/MapVector.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Support/FormatVariadic.h"
21
22#include <iterator>
23#include <limits>
24
25using namespace mlir;
26using namespace xilinx;
27using namespace xilinx::AIE;
28
29#define DEBUG_TYPE "aie-pathfinder"
30
31STATISTIC(numReplaysSkipped, "Attempts skipped as replays of an earlier one");
32STATISTIC(numReplaysVerified, "Attempts routed and verified to replay one");
33
34static llvm::cl::opt<bool> clVerifyReplays(
35 "aie-pathfinder-verify-replays", llvm::cl::Hidden,
36 llvm::cl::desc("Route the attempts of a relax ladder that replay an "
37 "earlier one anyway, and abort unless each iteration's "
38 "routing and the result are the earlier attempt's"),
39 llvm::cl::init(false));
40
41static llvm::hash_code hashRouting(const Routing &routing) {
42 llvm::hash_code h = llvm::hash_value(routing.settings.size());
43 auto settings = [&](const SwitchSettings &ss) {
44 for (const auto &[tile, s] : ss) {
45 h = llvm::hash_combine(h, tile.col, tile.row, s.srcs.size(),
46 s.dsts.size());
47 for (const Port &p : s.srcs)
48 h = llvm::hash_combine(h, p.bundle, p.channel);
49 for (const Port &p : s.dsts)
50 h = llvm::hash_combine(h, p.bundle, p.channel);
51 }
52 };
53 auto endpoint = [&](const PathEndPoint &e) {
54 h = llvm::hash_combine(h, e.coords.col, e.coords.row, e.port.bundle,
55 e.port.channel);
56 };
57 for (const auto &[src, ss] : routing.settings) {
58 endpoint(src);
59 settings(ss);
60 }
61 for (const auto &[key, ss] : routing.idSettings) {
62 endpoint(key.first);
63 h = llvm::hash_combine(h, key.second);
64 settings(ss);
65 }
66 for (const auto &[src, hops] : routing.packetTrees) {
67 endpoint(src);
68 for (const TreeHop &hop : hops) {
69 endpoint(hop.from);
70 endpoint(hop.to);
71 h = llvm::hash_combine(h, hop.joined, hop.isCrossbar);
72 }
73 }
74 return h;
75}
76
77namespace {
78// A connection's demand, the cost Dijkstra weighs it by, is
79// (demandBase + overCapacityCoeff * iterations it was over capacity) *
80// (demandBase + usedCapacityCoeff * streams using it), plus its avoidance.
81constexpr double overCapacityCoeff = 0.1;
82constexpr double usedCapacityCoeff = 0.02;
83constexpr double demandBase = 1.0;
84// A full connection's demand grows by this factor, or a prioritized flow's
85// by priorityDemandCoeff, each time another stream takes it.
86constexpr double demandCoeff = 1.1;
87constexpr double priorityDemandCoeff =
88 static_cast<double>(std::numeric_limits<int>::max());
89constexpr int maxCircuitStreamCapacity = 1;
90constexpr int maxPacketStreamCapacity = 32;
91// Demand added to a connection into an avoided port. It exceeds what a long
92// detour costs, so a route takes the port only when every other is taken.
93constexpr double avoidedPortDemand = 100.0;
94// History added to a connection each time the routing check rejects it.
95constexpr int routingCheckPenalty = 5;
96// Iterations spent steering away from a usable routing the check rejects.
97constexpr int maxSteers = 16;
98// Routings in a row the check rejects only for onlyPriorityMasters before
99// routing gives up: the penalties move such a flow between the ports of the
100// switchbox it has to leave by.
101constexpr int maxPriorityFaults = 16;
102// Times the routing check may fault where two trees meet before they stop
103// meeting; each fault moves the meeting elsewhere.
104constexpr int maxMeetFaults = 4;
105// Cost added to a hop that shares an arbiter unit with a flow to avoid.
106constexpr double conflictSharePenalty = 4;
107// Channels per direction packet streams leave a capped tile by (see
108// Pathfinder::relax). A heuristic: fewer channels mean fewer master
109// sets per tile, but more flows on each.
110constexpr int packetFanoutCap = 2;
111// A multicast's next destination may branch off any hop its tree already
112// takes, starting at this cost per hop back to the source: enough of a
113// discount to share hops, while still preferring the shortest path to each
114// destination.
115constexpr double treeSeedFactor = 0.9;
116// A destination's branch is rerouted only when that saves more than this.
117constexpr double rerouteMinSaving = 1e-6;
118// Iterations without fewer overused channels before the circuit trees that
119// overuse one route first (see findPaths).
120constexpr int stallIterations = 50;
121// Iterations of a stall that route the losing circuit trees first, without
122// fewer overused channels, before the attempt gives up.
123constexpr int maxReorderedStall = 300;
124// Iterations without fewer overused channels before an attempt that has never
125// fit the fabric gives up. In the nightly's designs, none that routed took
126// over 275.
127constexpr int maxOverusedStall = 400;
128// Iterations, once a routing has fit the fabric, without the routing check
129// naming fewer faults than before or teaching a split, relation, untrunk or
130// no-join pair it never taught this attempt, before the attempt gives up.
131constexpr int maxRejectedStall = 600;
132// How much faster a stalled routing's overused channels that only circuit
133// trees take accrue history, so the trees spread out sooner.
134constexpr int stallHistory = 4;
135} // namespace
136
138 for (Cell &c : cells)
139 c.demand = (demandBase + overCapacityCoeff * c.overCapacity) *
140 (demandBase + usedCapacityCoeff * c.usedCapacity) +
141 c.avoidance;
142}
143
144void SwitchboxConnect::bumpDemand(size_t i, size_t j) {
145 Cell &c = at(i, j);
146 if (c.usedCapacity >= maxCircuitStreamCapacity)
147 c.demand *= c.isPriority ? priorityDemandCoeff : demandCoeff;
148}
149
150char RoutingFailure::ID = 0;
153
154void RoutingFailure::log(llvm::raw_ostream &os) const {
155 os << kNoLegalRouting;
156 if (!reason.empty())
157 os << ": " << reason;
158}
159
160llvm::Error DynamicTileAnalysis::runAnalysis(DeviceOp &device) {
161 LLVM_DEBUG(llvm::dbgs() << "\t---Begin DynamicTileAnalysis Constructor---\n");
162 // find the maxCol and maxRow
163 maxCol = device.getTargetModel().columns();
164 maxRow = device.getTargetModel().rows();
165
166 pathfinder.initialize(maxCol, maxRow, device.getTargetModel());
167 for (const auto &[coords, port] : avoidedPorts)
168 pathfinder.avoidPort(coords, port);
169
170 // For each flow (circuit + packet) in the device, add it to pathfinder. Each
171 // source can map to multiple different destinations (fanout). Control packet
172 // flows to be routed (as prioritized routings). Then followed by normal
173 // packet flows.
174 for (PacketFlowOp pktFlowOp : device.getOps<PacketFlowOp>()) {
175 Region &r = pktFlowOp.getPorts();
176 Block &b = r.front();
177 SmallVector<std::pair<TileID, Port>, 4> sources;
178 // Pass 1: collect all sources (order-independent; supports fan-in).
179 for (Operation &Op : b.getOperations()) {
180 if (auto pktSource = dyn_cast<PacketSourceOp>(Op)) {
181 auto srcTile = cast<TileOp>(pktSource.getTile().getDefiningOp());
182 sources.push_back(
183 {{srcTile.colIndex(), srcTile.rowIndex()}, pktSource.port()});
184 }
185 }
186
187 bool priorityFlow = pktFlowOp.getPriorityRoute().value_or(false);
188 // Pass 2: add a flow from every source to every destination so
189 // fan-in topologies are routed (not just the last source).
190 for (Operation &Op : b.getOperations()) {
191 if (auto pktDest = dyn_cast<PacketDestOp>(Op)) {
192 auto dstTile = cast<TileOp>(pktDest.getTile().getDefiningOp());
193 Port dstPort = pktDest.port();
194 TileID dstCoords = {dstTile.colIndex(), dstTile.rowIndex()};
195 for (auto &[srcCoords, srcPort] : sources) {
196 LLVM_DEBUG(llvm::dbgs()
197 << "\tAdding Packet Flow: (" << srcCoords.col << ", "
198 << srcCoords.row << ")"
199 << stringifyWireBundle(srcPort.bundle) << srcPort.channel
200 << " -> (" << dstCoords.col << ", " << dstCoords.row << ")"
201 << stringifyWireBundle(dstPort.bundle) << dstPort.channel
202 << "\n");
203 pathfinder.addFlow(srcCoords, srcPort, dstCoords, dstPort,
204 pktFlowOp.IDInt(), priorityFlow,
205 pktFlowOp.getLoc());
206 }
207 }
208 }
209 }
210
211 // Add circuit flows.
212 for (FlowOp flowOp : device.getOps<FlowOp>()) {
213 TileOp srcTile = cast<TileOp>(flowOp.getSource().getDefiningOp());
214 TileOp dstTile = cast<TileOp>(flowOp.getDest().getDefiningOp());
215 TileID srcCoords = {srcTile.colIndex(), srcTile.rowIndex()};
216 TileID dstCoords = {dstTile.colIndex(), dstTile.rowIndex()};
217 Port srcPort = {flowOp.getSourceBundle(), flowOp.getSourceChannel()};
218 Port dstPort = {flowOp.getDestBundle(), flowOp.getDestChannel()};
219 LLVM_DEBUG(llvm::dbgs()
220 << "\tAdding Flow: (" << srcCoords.col << ", " << srcCoords.row
221 << ")" << stringifyWireBundle(srcPort.bundle) << srcPort.channel
222 << " -> (" << dstCoords.col << ", " << dstCoords.row << ")"
223 << stringifyWireBundle(dstPort.bundle) << dstPort.channel
224 << "\n");
225 pathfinder.addFlow(srcCoords, srcPort, dstCoords, dstPort,
226 /*packetId=*/std::nullopt, /*isPriorityFlow=*/false,
227 flowOp.getLoc());
228 }
229
230 // Canonicalize all flows after both packet and circuit flows are collected.
231 pathfinder.sortFlows();
232
233 // add existing connections so Pathfinder knows which resources are
234 // available search all existing SwitchBoxOps for exising connections
235 for (SwitchboxOp switchboxOp : device.getOps<SwitchboxOp>()) {
236 if (failed(pathfinder.addFixedConnection(switchboxOp)))
237 return llvm::make_error<RoutingFailure>(
238 llvm::formatv("cannot add the fixed connections of the switchbox "
239 "at tile ({0}, {1})",
240 switchboxOp.colIndex(), switchboxOp.rowIndex()),
241 RoutingFaults{}, switchboxOp.getLoc());
242 }
243
244 // all flows are now populated, call the congestion-aware pathfinder
245 // algorithm
246 // check whether the pathfinder algorithm creates a legal routing
247 llvm::Expected<Routing> found = pathfinder.findPaths(maxIterations);
248 if (!found)
249 return found.takeError();
250 routing = std::move(*found);
251
252 // fill in coords to TileOps, SwitchboxOps, and ShimMuxOps
253 coordToTile.clear();
254 coordToSwitchbox.clear();
255 coordToShimMux.clear();
256 for (auto tileOp : device.getOps<TileOp>()) {
257 [[maybe_unused]] bool fresh =
258 coordToTile.try_emplace(tileOp.getTileID(), tileOp).second;
259 assert(fresh);
260 }
261 for (auto switchboxOp : device.getOps<SwitchboxOp>()) {
262 [[maybe_unused]] bool fresh =
263 coordToSwitchbox
264 .try_emplace({switchboxOp.colIndex(), switchboxOp.rowIndex()},
265 switchboxOp)
266 .second;
267 assert(fresh);
268 }
269 for (auto shimmuxOp : device.getOps<ShimMuxOp>()) {
270 [[maybe_unused]] bool fresh =
271 coordToShimMux
272 .try_emplace({shimmuxOp.colIndex(), shimmuxOp.rowIndex()},
273 shimmuxOp)
274 .second;
275 assert(fresh);
276 }
277
278 LLVM_DEBUG(llvm::dbgs() << "\t---End DynamicTileAnalysis Constructor---\n");
279 return llvm::Error::success();
280}
281
282TileOp DynamicTileAnalysis::getTile(OpBuilder &builder, int col, int row) {
283 TileOp &tileOp = coordToTile[{col, row}];
284 if (!tileOp)
285 tileOp = TileOp::create(
286 builder,
287 cast<DeviceOp>(builder.getInsertionBlock()->getParentOp()).getLoc(),
288 col, row);
289 return tileOp;
290}
291
292TileOp DynamicTileAnalysis::getTile(OpBuilder &builder, const TileID &tileId) {
293 return getTile(builder, tileId.col, tileId.row);
294}
295
296SwitchboxOp DynamicTileAnalysis::getSwitchbox(OpBuilder &builder, int col,
297 int row) {
298 assert(col >= 0);
299 assert(row >= 0);
300 if (SwitchboxOp switchboxOp = lookupSwitchbox({col, row}))
301 return switchboxOp;
302 auto tileOp = getTile(builder, col, row);
303 auto switchboxOp = SwitchboxOp::create(builder, tileOp.getLoc(), tileOp);
304 SwitchboxOp::ensureTerminator(switchboxOp.getConnections(), builder,
305 tileOp.getLoc());
306 coordToSwitchbox[{col, row}] = switchboxOp;
307 return switchboxOp;
308}
309
310ShimMuxOp DynamicTileAnalysis::getShimMux(OpBuilder &builder, int col) {
311 assert(col >= 0);
312 if (ShimMuxOp shimMuxOp = lookupShimMux(col))
313 return shimMuxOp;
314 auto tileOp = getTile(builder, col, 0);
315 assert(getTargetModel(tileOp).hasShimMux(col, 0));
316 auto shimMuxOp = ShimMuxOp::create(builder, tileOp.getLoc(), tileOp);
317 ShimMuxOp::ensureTerminator(shimMuxOp.getConnections(), builder,
318 tileOp.getLoc());
319 coordToShimMux[{col, 0}] = shimMuxOp;
320 return shimMuxOp;
321}
322
323void Pathfinder::initialize(int maxCol, int maxRow,
324 const AIETargetModel &targetModel) {
325 // Reset the graph and flows so a Pathfinder can be reused across analyses
326 // and devices; the dense-graph cache must be rebuilt for the new topology.
327 // The relax state (shareChannels, settings, relaxStep, leads, leadStep,
328 // cappedTiles, crowdedTiles) survives, so the ladder advances across
329 // attempts.
330 graph.clear();
331 flows.clear();
332 packetIdsTo.clear();
333 priorityIds.clear();
334 flowLocs.clear();
335 graphBuilt = false;
336 columns = maxCol;
337 rows = maxRow;
338 nodeIds.clear();
339 nodes.clear();
340 adjacency.clear();
341 wireEdgesBegin.clear();
342 distance.clear();
343 indexInHeap.clear();
344 colors.clear();
345 preds.clear();
346 predEdge.clear();
347
348 std::map<WireBundle, int> maxChannels;
349 auto intraconnect = [&](int col, int row) {
350 TileID coords = {col, row};
351 SwitchboxConnect &sb =
352 graph.try_emplace(crossbarKey(coords), coords).first->second;
353
354 for (int i = 0, e = getMaxEnumValForWireBundle() + 1; i < e; ++i) {
355 WireBundle bundle = symbolizeWireBundle(i).value();
356 // get all ports into current switchbox
357 int channels =
358 targetModel.getNumSourceSwitchboxConnections(col, row, bundle);
359 if (channels == 0 && targetModel.hasShimMux(col, row)) {
360 // wordaround for shimMux
361 channels = targetModel.getNumSourceShimMuxConnections(col, row, bundle);
362 }
363 for (int channel = 0; channel < channels; channel++) {
364 sb.srcPorts.push_back(Port{bundle, channel});
365 }
366 // get all ports out of current switchbox
367 channels = targetModel.getNumDestSwitchboxConnections(col, row, bundle);
368 if (channels == 0 && targetModel.hasShimMux(col, row)) {
369 // wordaround for shimMux
370 channels = targetModel.getNumDestShimMuxConnections(col, row, bundle);
371 }
372 for (int channel = 0; channel < channels; channel++) {
373 sb.dstPorts.push_back(Port{bundle, channel});
374 }
375 maxChannels[bundle] = channels;
376 }
377 sb.resize();
378 // A shim's mux reaches its DMA, NOC and PLIO ports from any port.
379 auto isMuxed = [&](Port p) {
380 return targetModel.hasShimMux(col, row) &&
381 llvm::is_contained(
382 {WireBundle::DMA, WireBundle::NOC, WireBundle::PLIO},
383 p.bundle);
384 };
385 for (auto [i, pIn] : llvm::enumerate(sb.srcPorts))
386 for (auto [j, pOut] : llvm::enumerate(sb.dstPorts))
387 sb.at(i, j).available =
388 targetModel.isLegalTileConnection(col, row, pIn.bundle, pIn.channel,
389 pOut.bundle, pOut.channel) ||
390 isMuxed(pIn) || isMuxed(pOut);
391 };
392
393 auto interconnect = [&](int col, int row, int targetCol, int targetRow,
394 WireBundle srcBundle, WireBundle dstBundle) {
395 TileID src = {col, row}, dst = {targetCol, targetRow};
396 SwitchboxConnect &sb =
397 graph.try_emplace(wireKey(src, dst), src, dst).first->second;
398 sb.isCrossbar = false;
399 for (int channel = 0; channel < maxChannels[srcBundle]; channel++) {
400 sb.srcPorts.push_back(Port{srcBundle, channel});
401 sb.dstPorts.push_back(Port{dstBundle, channel});
402 }
403 sb.resize();
404 for (size_t i = 0; i < sb.srcPorts.size(); i++)
405 sb.at(i, i).available = true;
406 };
407
408 for (int row = 0; row <= maxRow; row++) {
409 for (int col = 0; col <= maxCol; col++) {
410 maxChannels.clear();
411 // connections within the same switchbox
412 intraconnect(col, row);
413
414 // connections between switchboxes
415 if (row > 0) {
416 // from south to north
417 interconnect(col, row, col, row - 1, WireBundle::South,
418 WireBundle::North);
419 }
420 if (row < maxRow) {
421 // from north to south
422 interconnect(col, row, col, row + 1, WireBundle::North,
423 WireBundle::South);
424 }
425 if (col > 0) {
426 // from east to west
427 interconnect(col, row, col - 1, row, WireBundle::West,
428 WireBundle::East);
429 }
430 if (col < maxCol) {
431 // from west to east
432 interconnect(col, row, col + 1, row, WireBundle::East,
433 WireBundle::West);
434 }
435 }
436 }
437}
438
439// Add a flow from src to dst can have an arbitrary number of dst locations
440// due to fanout.
441void Pathfinder::addFlow(TileID srcCoords, Port srcPort, TileID dstCoords,
442 Port dstPort, std::optional<int> packetId,
443 bool isPriorityFlow,
444 std::optional<mlir::Location> loc) {
445 auto pinnedIds = constraints.pinnedIds.find({srcCoords, srcPort});
446 if (constraints.pinned.count({srcCoords, srcPort}))
447 isPriorityFlow &= packetId && pinnedIds != constraints.pinnedIds.end() &&
448 pinnedIds->second.count(*packetId);
449 else
450 isPriorityFlow &= constraints.prioritize;
451 if (loc)
452 flowLocs[{srcCoords, srcPort}].try_emplace({dstCoords, dstPort}, *loc);
453 if (packetId) {
454 auto &ids = packetIdsTo[{{srcCoords, srcPort}, {dstCoords, dstPort}}];
455 if (!llvm::is_contained(ids, *packetId))
456 ids.push_back(*packetId);
457 if (isPriorityFlow)
458 priorityIds[{srcCoords, srcPort}].insert(*packetId);
459 }
460 // A source has one flow, with all its destinations.
461 PathEndPoint src{srcCoords, srcPort}, dst{dstCoords, dstPort};
462 auto flow = llvm::find_if(flows, [&](const Flow &f) { return f.src == src; });
463 if (flow == flows.end()) {
464 // sortFlows assigns the packet groups.
465 flows.push_back(
466 Flow{packetId ? 0 : -1, isPriorityFlow, src, {dst}, packetId});
467 } else if (isPriorityFlow) {
468 flow->isPriorityFlow = true;
469 flow->dsts.insert(flow->dsts.begin(), dst);
470 } else {
471 flow->dsts.push_back(dst);
472 }
473}
474
475// Where the flow from `src` to `dst`, or to any destination if `dst` is null,
476// was declared.
477std::optional<mlir::Location>
478Pathfinder::flowLoc(const PathEndPoint &src, const PathEndPoint *dst) const {
479 auto locs = flowLocs.find(src);
480 if (locs == flowLocs.end())
481 return std::nullopt;
482 auto it = dst ? locs->second.find(*dst) : locs->second.begin();
483 if (it == locs->second.end())
484 return std::nullopt;
485 return it->second;
486}
487
488bool Pathfinder::shareAllChannels() {
489 shareChannels = true;
490 return llvm::any_of(flows, [](const Flow &f) { return f.packetGroupId > 0; });
491}
492
493bool Pathfinder::capCrowdedFanOut() {
494 size_t capped = cappedTiles.size();
495 cappedTiles.insert(crowdedTiles.begin(), crowdedTiles.end());
496 return cappedTiles.size() > capped;
497}
498
499std::map<PathEndPoint, std::set<int>> Pathfinder::idsBySource() const {
500 std::map<PathEndPoint, std::set<int>> ids;
501 for (const auto &[ends, sent] : packetIdsTo)
502 ids[ends.first].insert(sent.begin(), sent.end());
503 return ids;
504}
505
506bool Pathfinder::routeIdsApart() {
507 if (any(settings & Relax::IdsApart))
508 return false;
509 settings |= Relax::IdsApart;
510 shareChannels = false;
511 cappedTiles.clear();
512 return llvm::any_of(idsBySource(),
513 [](const auto &s) { return s.second.size() > 1; });
514}
515
516bool Pathfinder::splitSharedIds() {
517 if (any(settings & Relax::SplitShared))
518 return false;
519 settings |= Relax::SplitShared;
520 shareChannels = false;
521 cappedTiles.clear();
522 std::map<PathEndPoint, std::set<int>> ids = idsBySource();
523 for (const auto &[src, srcIds] : ids)
524 for (const auto &[other, otherIds] : ids) {
525 const std::set<int> &theirs = otherIds;
526 if (!(src == other) &&
527 llvm::any_of(srcIds, [&](int id) { return theirs.count(id); }) &&
528 llvm::any_of(srcIds, [&](int id) { return !theirs.count(id); }))
529 return true;
530 }
531 return false;
532}
533
534// The steps before it bent the routing around the meetings, so the ladder
535// starts over without them.
536bool Pathfinder::stopMeeting() {
537 if (any(settings & Relax::MeetApart) || !treesMet)
538 return false;
539 settings |= Relax::MeetApart;
540 settings &= ~(Relax::IdsApart | Relax::SplitShared);
541 shareChannels = false;
542 cappedTiles.clear();
543 relaxStep = 0;
544 return true;
545}
546
547// Which tree routes first decides where the others meet it, and a switchbox
548// takes trees in to one master set only by slave ports of matching channels,
549// so the first a cluster routes can leave the rest no switchbox to meet at.
550bool Pathfinder::rotateLeads() {
551 std::map<PathEndPoint, std::map<PathEndPoint, std::set<int>>> to;
552 for (const auto &[ends, ids] : packetIdsTo)
553 to[ends.first][ends.second].insert(ids.begin(), ids.end());
554 // Whether `a` sends some id to two or more receivers `b` reaches too.
555 auto spans = [&](const PathEndPoint &a, const PathEndPoint &b) {
556 std::map<int, int> shared;
557 for (const auto &[dst, ids] : to[a])
558 if (to[b].count(dst))
559 for (int id : ids)
560 if (++shared[id] > 1)
561 return true;
562 return false;
563 };
564 SmallVector<PathEndPoint, 8> srcs(llvm::make_first_range(to));
565 llvm::IntEqClasses clusters(srcs.size());
566 for (auto [i, a] : llvm::enumerate(srcs))
567 for (auto [j, b] : llvm::enumerate(srcs))
568 if (i < j && spans(a, b) && spans(b, a))
569 clusters.join(i, j);
570 clusters.compress();
571 std::vector<SmallVector<PathEndPoint, 4>> members(clusters.getNumClasses());
572 for (auto [i, src] : llvm::enumerate(srcs))
573 members[clusters[i]].push_back(src);
574 // The first member of each cluster leads already.
575 ++leadStep;
576 leads.clear();
577 for (const auto &cluster : members)
578 if (leadStep < cluster.size())
579 leads.insert(cluster[leadStep]);
580 return !leads.empty();
581}
582
583// A flow with a same-id partner meets another id's tree only on the way to
584// destinations the partner does not reach, as the partner, routed first, has
585// to be met there. A partner routed later meets the flow's tree instead, so
586// in a cluster of two such pairs the first of each can meet the other's.
587bool Pathfinder::meetAhead() {
588 if (any(settings & Relax::MeetAheadOfPartners) || !treesMet)
589 return false;
590 settings |= Relax::MeetAheadOfPartners;
591 return true;
592}
593
594namespace {
595enum class RelaxStep {
596 ShareChannels,
597 CapCrowdedTiles,
598 RouteIdsApart,
599 SplitSharedIds,
600 RotateLeads,
601 MeetAhead,
602 StopMeeting
603};
604// Stopping meetings comes last, and runs the ladder once more: what it routes
605// can hold arbiters in a cycle through the receivers trees share.
606constexpr RelaxStep relaxLadder[] = {
607 RelaxStep::ShareChannels, RelaxStep::CapCrowdedTiles,
608 RelaxStep::RouteIdsApart, RelaxStep::ShareChannels,
609 RelaxStep::CapCrowdedTiles, RelaxStep::SplitSharedIds,
610 RelaxStep::ShareChannels, RelaxStep::CapCrowdedTiles,
611 RelaxStep::RotateLeads, RelaxStep::MeetAhead,
612 RelaxStep::StopMeeting};
613constexpr size_t rotateLeadsStep = std::size(relaxLadder) - 3;
614} // namespace
615
617 if (!packetsFailed) {
618 LLVM_DEBUG(llvm::dbgs() << "No packet stream crosses an overused link\n");
619 return false;
620 }
621 while (relaxStep < std::size(relaxLadder)) {
622 switch (relaxLadder[relaxStep++]) {
623 case RelaxStep::ShareChannels:
624 if (shareAllChannels()) {
625 LLVM_DEBUG(llvm::dbgs() << "Relax: share channels\n");
626 return true;
627 }
628 break;
629 case RelaxStep::CapCrowdedTiles:
630 if (capCrowdedFanOut()) {
631 LLVM_DEBUG(llvm::dbgs() << "Relax: cap crowded tiles\n");
632 return true;
633 }
634 break;
635 case RelaxStep::RouteIdsApart:
636 if (routeIdsApart()) {
637 LLVM_DEBUG(llvm::dbgs() << "Relax: route ids apart\n");
638 return true;
639 }
640 // With one id per source, the steps up to the last two would only
641 // repeat.
642 relaxStep = rotateLeadsStep;
643 break;
644 case RelaxStep::SplitSharedIds:
645 if (splitSharedIds()) {
646 LLVM_DEBUG(llvm::dbgs() << "Relax: split shared ids\n");
647 return true;
648 }
649 relaxStep = rotateLeadsStep;
650 break;
651 case RelaxStep::RotateLeads:
652 // Each member of a cluster leads in turn, the step repeating till all
653 // have.
654 if (rotateLeads()) {
655 --relaxStep;
656 LLVM_DEBUG(llvm::dbgs()
657 << "Relax: route cluster member " << leadStep << " first\n");
658 return true;
659 }
660 break;
661 case RelaxStep::MeetAhead:
662 if (meetAhead()) {
663 LLVM_DEBUG(llvm::dbgs() << "Relax: meet ahead of same-id partners\n");
664 return true;
665 }
666 break;
667 case RelaxStep::StopMeeting:
668 if (stopMeeting()) {
669 LLVM_DEBUG(llvm::dbgs() << "Relax: stop meeting\n");
670 return true;
671 }
672 break;
673 }
674 }
675 return false;
676}
677
678// Sort flows to (1) get deterministic routing, and (2) perform routings on
679// prioritized flows before others, for routing consistency on those flows.
681 for (auto &flow : flows)
682 llvm::sort(flow.dsts);
683
684 // The groups shareAllChannels merges, whatever order the flows were
685 // added in: packet flows to a common destination are in one.
686 llvm::IntEqClasses groups(flows.size());
687 std::map<PathEndPoint, unsigned> firstTo;
688 for (auto [k, flow] : llvm::enumerate(flows)) {
689 if (flow.packetGroupId < 0)
690 continue;
691 for (const PathEndPoint &dst : flow.dsts) {
692 auto [it, fresh] = firstTo.try_emplace(dst, k);
693 if (!fresh)
694 groups.join(k, it->second);
695 }
696 }
697 llvm::DenseMap<unsigned, int> groupOf;
698 for (auto [k, flow] : llvm::enumerate(flows))
699 if (flow.packetGroupId >= 0)
700 flow.packetGroupId =
701 shareChannels
702 ? 0
703 : groupOf.try_emplace(groups.findLeader(k), groupOf.size())
704 .first->second;
705
706 auto flowRank = [](const Flow &flow) {
707 if (flow.isPriorityFlow)
708 return 0;
709 if (flow.packetGroupId >= 0)
710 return 1;
711 return 2;
712 };
713 llvm::sort(flows, [&](const Flow &lhs, const Flow &rhs) {
714 return std::make_tuple(flowRank(lhs), !leads.count(lhs.src), lhs.src) <
715 std::make_tuple(flowRank(rhs), !leads.count(rhs.src), rhs.src);
716 });
717}
718
720 // DMA0 -> N3, DMA1 -> N7; NOC0/1 -> N2/3, NOC2/3 -> N6/7.
721 if (src.bundle == WireBundle::DMA)
722 return src.channel == 0 ? 3 : 7;
723 if (src.bundle == WireBundle::NOC)
724 return src.channel >= 2 ? src.channel + 4 : src.channel + 2;
725 return src.channel;
726}
727
729 // N2 -> DMA0, N3 -> DMA1; N2-5 -> NOC0-3.
730 if (dst.bundle == WireBundle::DMA)
731 return dst.channel == 0 ? 2 : 3;
732 if (dst.bundle == WireBundle::NOC)
733 return dst.channel + 2;
734 return dst.channel;
735}
736
737LogicalResult Pathfinder::addFixedConnection(SwitchboxOp switchboxOp) {
738 int col = switchboxOp.colIndex();
739 int row = switchboxOp.rowIndex();
740 TileID coords = {col, row};
741 auto &sb = graph[crossbarKey(coords)];
742 // Validate every connect against the original connectivity before reserving
743 // any resource, so a broadcast (one source fanning out to several dests) does
744 // not invalidate its own sibling connects mid-scan. A destination port may be
745 // driven only once; a source port may legally recur across a broadcast.
746 llvm::SmallVector<std::pair<int, int>, 8> reserved;
747 llvm::SmallDenseSet<int, 8> claimedDsts;
748 for (ConnectOp connectOp : switchboxOp.getOps<ConnectOp>()) {
749 int srcIdx = sb.srcIndex(connectOp.sourcePort());
750 int dstIdx = sb.dstIndex(connectOp.destPort());
751 // Reject an illegal pair (absent from the switchbox model) or a second
752 // driver on the same output port; a repeated source port is a broadcast.
753 if (srcIdx < 0 || dstIdx < 0 || !sb.at(srcIdx, dstIdx).available ||
754 !claimedDsts.insert(dstIdx).second) {
755 return failure();
756 }
757 reserved.emplace_back(srcIdx, dstIdx);
758 }
759 // A pre-placed packet-switched output (an aie.masterset) also monopolizes its
760 // destination port. That stream-switch output is already configured for
761 // packet switching, so no circuit stream may drive it, and the router cannot
762 // emit a second masterset on the same port for another packet flow. The
763 // circuit pathfinder does not read packet ops, so without this reservation it
764 // may route a flow onto an output the masterset owns and produce two ops
765 // driving one destination.
766 llvm::SmallVector<int, 8> reservedMasterDsts;
767 for (MasterSetOp masterSetOp : switchboxOp.getOps<MasterSetOp>()) {
768 int dstIdx = sb.dstIndex(masterSetOp.destPort());
769 // Reject an output port absent from the switchbox model or already driven
770 // by a circuit connect or another masterset.
771 if (dstIdx < 0 || !claimedDsts.insert(dstIdx).second) {
772 return failure();
773 }
774 // Packets ending at the overlay's TileControl join its arbiter.
775 if (masterSetOp.getDestBundle() == WireBundle::TileControl &&
776 AIEDialect::IsCtrlPktOverlayAttrHelper(masterSetOp.getContext())
777 .isAttrPresent(masterSetOp))
778 sb.packetJoinDst.set(dstIdx);
779 else
780 reservedMasterDsts.push_back(dstIdx);
781 }
782 // A circuit-switched ConnectOp monopolizes both its source port (the stream
783 // switch input) and its destination port (the output): no other stream may
784 // inject on that input, and the output can carry only this one stream.
785 // Reserving the whole column also reserves the outgoing wire, since that wire
786 // is reachable only by driving this output port.
787 for (auto [srcIdx, dstIdx] : reserved) {
788 for (size_t j = 0; j < sb.dstPorts.size(); j++)
789 sb.at(srcIdx, j).available = false;
790 for (size_t i = 0; i < sb.srcPorts.size(); i++)
791 sb.at(i, dstIdx).available = false;
792 }
793 // A masterset fixes only its output port. Its inputs arrive through arbiters
794 // that packet flows share, so the source rows stay free.
795 for (int dstIdx : reservedMasterDsts)
796 for (size_t i = 0; i < sb.srcPorts.size(); i++)
797 sb.at(i, dstIdx).available = false;
798 // A fixed op on a shim's South channel claims the port the shim mux carries
799 // on it (see shimMuxChannelFrom).
800 if (getTargetModel(switchboxOp).hasShimMux(col, row)) {
801 auto isMuxed = [](Port p) {
802 return llvm::is_contained(
803 {WireBundle::DMA, WireBundle::NOC, WireBundle::PLIO}, p.bundle);
804 };
805 llvm::SmallDenseSet<int, 8> southDsts, southSrcs;
806 for (int dstIdx : claimedDsts)
807 if (sb.dstPorts[dstIdx].bundle == WireBundle::South)
808 southDsts.insert(sb.dstPorts[dstIdx].channel);
809 for (auto [srcIdx, dstIdx] : reserved)
810 if (sb.srcPorts[srcIdx].bundle == WireBundle::South)
811 southSrcs.insert(sb.srcPorts[srcIdx].channel);
812 for (size_t j = 0; j < sb.dstPorts.size(); j++)
813 if (isMuxed(sb.dstPorts[j]) &&
814 southDsts.count(shimMuxChannelTo(sb.dstPorts[j])))
815 for (size_t i = 0; i < sb.srcPorts.size(); i++)
816 sb.at(i, j).available = false;
817 for (size_t i = 0; i < sb.srcPorts.size(); i++)
818 if (isMuxed(sb.srcPorts[i]) &&
819 southSrcs.count(shimMuxChannelFrom(sb.srcPorts[i])))
820 for (size_t j = 0; j < sb.dstPorts.size(); j++)
821 sb.at(i, j).available = false;
822 }
823 for (PacketRulesOp rulesOp : switchboxOp.getOps<PacketRulesOp>()) {
824 int srcIdx = sb.srcIndex(rulesOp.sourcePort());
825 if (srcIdx < 0)
826 return failure();
827 sb.packetOnlySrc.set(srcIdx);
828 }
829 return success();
830}
831
833 auto it = graph.find(crossbarKey(coords));
834 if (it == graph.end())
835 return;
836 SwitchboxConnect &sb = it->second;
837 for (size_t i = 0; i < sb.srcPorts.size(); i++)
838 for (size_t j = 0; j < sb.dstPorts.size(); j++)
839 sb.at(i, j).available = false;
840}
841
843 auto it = graph.find(crossbarKey(coords));
844 if (it == graph.end())
845 return;
846 SwitchboxConnect &sb = it->second;
847 int j = sb.dstIndex(port);
848 if (j < 0)
849 return;
850 for (size_t i = 0; i < sb.srcPorts.size(); i++)
851 sb.at(i, j).avoidance = avoidedPortDemand;
852}
853
854static constexpr double INF = std::numeric_limits<double>::max();
855
856namespace {
857enum Color : int8_t { WHITE = 0, GRAY = 1, BLACK = 2 };
858} // namespace
859
860int Pathfinder::getOrAddNodeId(const PathEndPoint &pep) {
861 auto it = nodeIds.find(pep);
862 if (it != nodeIds.end())
863 return it->second;
864 int id = static_cast<int>(nodes.size());
865 nodeIds[pep] = id;
866 nodes.push_back(pep);
867 return id;
868}
869
870// Build the dense integer node numbering and per-node adjacency once. The graph
871// topology is fixed across congestion iterations (only the demand weights
872// change), so this is computed a single time and the edges carry live pointers
873// into `graph` for demand lookups. A node's crossbar edges come first, then its
874// wire edges, each sorted by the PathEndPoint they reach, so Dijkstra breaks
875// ties the same way every run.
876void Pathfinder::buildRoutingGraph() {
877 // Seed the dense node set with all flow endpoints (the only nodes Dijkstra is
878 // ever started from or traced back to). Remaining nodes are discovered as
879 // edge destinations below.
880 for (auto &f : flows) {
881 getOrAddNodeId(f.src);
882 for (auto &d : f.dsts)
883 getOrAddNodeId(d);
884 }
885
886 // Process nodes by growing index; getOrAddNodeId() may append new nodes as
887 // edge destinations are discovered, so re-read nodes.size() each iteration.
888 for (size_t id = 0; id < nodes.size(); id++) {
889 PathEndPoint src = nodes[id];
890 // The ports the crossbar connects this one to, and the neighbours' ports
891 // its wire reaches.
892 std::vector<std::pair<PathEndPoint, SwitchboxConnect *>> dests;
893 auto intraIt = graph.find(crossbarKey(src.coords));
894 if (intraIt != graph.end()) {
895 auto &sb = intraIt->second;
896 for (auto [i, pIn] : llvm::enumerate(sb.srcPorts))
897 for (auto [j, pOut] : llvm::enumerate(sb.dstPorts))
898 if (pIn == src.port && sb.at(i, j).available)
899 dests.push_back({{src.coords, pOut}, &sb});
900 }
901 std::pair<TileID, Port> neighbors[] = {
902 {{src.coords.col, src.coords.row - 1},
903 {WireBundle::North, src.port.channel}},
904 {{src.coords.col - 1, src.coords.row},
905 {WireBundle::East, src.port.channel}},
906 {{src.coords.col, src.coords.row + 1},
907 {WireBundle::South, src.port.channel}},
908 {{src.coords.col + 1, src.coords.row},
909 {WireBundle::West, src.port.channel}}};
910 for (const auto &[neighborCoords, neighborPort] : neighbors) {
911 auto nIt = graph.find(wireKey(src.coords, neighborCoords));
912 if (nIt != graph.end() &&
913 src.port.bundle == getConnectingBundle(neighborPort.bundle) &&
914 llvm::is_contained(nIt->second.dstPorts, neighborPort))
915 dests.push_back({{neighborCoords, neighborPort}, &nIt->second});
916 }
917 llvm::sort(dests, [](const auto &a, const auto &b) {
918 return std::make_tuple(a.first, !a.second->isCrossbar) <
919 std::make_tuple(b.first, !b.second->isCrossbar);
920 });
921
922 std::vector<Edge> edges;
923 edges.reserve(dests.size());
924 for (auto &[dest, link] : dests) {
925 auto &sb = *link;
926 int i = sb.srcIndex(src.port);
927 int j = sb.dstIndex(dest.port);
928 assert(i >= 0 && j >= 0);
929 int destId = getOrAddNodeId(dest);
930 edges.push_back(Edge{destId, &sb, i, j});
931 }
932 auto wires =
933 std::stable_partition(edges.begin(), edges.end(),
934 [](const Edge &e) { return e.sb->isCrossbar; });
935 if (wireEdgesBegin.size() < nodes.size())
936 wireEdgesBegin.resize(nodes.size());
937 wireEdgesBegin[id] = wires - edges.begin();
938 // getOrAddNodeId above may have reallocated `adjacency` via index growth in
939 // later iterations, but we only assign this node's edges now.
940 if (adjacency.size() < nodes.size())
941 adjacency.resize(nodes.size());
942 adjacency[id] = std::move(edges);
943 }
944 size_t n = nodes.size();
945 if (adjacency.size() < n)
946 adjacency.resize(n);
947 wireEdgesBegin.resize(n);
948
949 // Size the reusable Dijkstra scratch buffers. These are indexed by state id,
950 // i.e. two entries per node -- one per side of the port.
951 distance.assign(2 * n, INF);
952 indexInHeap.assign(2 * n, 0);
953 colors.assign(2 * n, WHITE);
954 preds.assign(2 * n, -1);
955 predEdge.assign(2 * n, Edge{-1, nullptr, 0, 0});
956 graphBuilt = true;
957}
958
959double Pathfinder::edgeWeight(const Edge &e, std::optional<int> packetId,
960 const llvm::BitVector *avoid,
961 const llvm::BitVector *avoidBranch) const {
962 const SwitchboxConnect::Cell &cell = e.sb->at(e.i, e.j);
963 double w = cell.demand;
964 // Sharing it would take a second stream's capacity, which the demand
965 // only shows once the group is routed.
966 if (packetId && cell.packetFlowCount > 0 && cell.packetIds.count(*packetId))
967 w *= demandCoeff;
968 if (e.sb->isCrossbar)
969 for (const llvm::BitVector *flows : {avoid, avoidBranch})
970 if (flows && llvm::any_of(e.sb->unitFlows(e.j),
971 [&](int f) { return flows->test(f); }))
972 w += conflictSharePenalty;
973 return w;
974}
975
976// Dijkstra over the dense graph from the states in `seeds`, searching states
977// (node, PortSide) rather than bare nodes. Fills the `preds` and `predEdge`
978// scratch buffers, both indexed by state id.
979void Pathfinder::dijkstraShortestPaths(
980 ArrayRef<int> seeds, ArrayRef<double> seedCosts,
981 std::optional<int> packetId, const llvm::BitVector *avoid,
982 const llvm::DenseMap<int, llvm::BitVector> *branchAvoid,
983 const llvm::DenseSet<int> *stops, ArrayRef<int> targets,
984 llvm::function_ref<bool(int, int)> mayCross) {
985 llvm::fill(distance, INF);
986 llvm::fill(colors, static_cast<int8_t>(WHITE));
987 llvm::fill(preds, -1);
988 llvm::fill(indexInHeap, uint64_t{0});
989
990 using MutableQueue = d_ary_heap_indirect<
991 /*Value=*/int, /*Arity=*/4,
992 /*IndexInHeapPropertyMap=*/std::vector<uint64_t> &,
993 /*DistanceMap=*/std::vector<double> &,
994 /*Compare=*/std::less<>>;
995 MutableQueue Q(distance, indexInHeap);
996
997 for (auto [seed, cost] : llvm::zip_equal(seeds, seedCosts)) {
998 distance[seed] = cost;
999 colors[seed] = GRAY;
1000 Q.push(seed);
1001 }
1002 // A settled state's distance and predecessor never change again.
1003 SmallVector<int, 8> unsettled(targets);
1004 while (!Q.empty()) {
1005 int s = Q.top();
1006 Q.pop();
1007 if (llvm::is_contained(unsettled, s)) {
1008 llvm::erase(unsettled, s);
1009 if (unsettled.empty())
1010 break;
1011 }
1012 if (stops && stops->count(s)) {
1013 colors[s] = BLACK;
1014 continue;
1015 }
1016 // In takes crossbar edges and lands on the Out side of the port it picks;
1017 // Out takes the wire to the neighbour and lands on that tile's In side. Any
1018 // other pairing would either turn the stream around inside a switchbox or
1019 // ride a wire the crossbar was never set to drive.
1020 const bool sIsOut = (s & 1) == Out;
1021 const llvm::BitVector *avoidBranch = nullptr;
1022 if (branchAvoid)
1023 if (auto it = branchAvoid->find(s); it != branchAvoid->end())
1024 avoidBranch = &it->second;
1025 ArrayRef<Edge> out = adjacency[stateNode(s)];
1026 size_t wires = wireEdgesBegin[stateNode(s)];
1027 const bool isIntra = !sIsOut;
1028 for (const Edge &e :
1029 sIsOut ? out.drop_front(wires) : out.take_front(wires)) {
1030 if ((isIntra && !packetId &&
1031 (e.sb->packetOnlySrc[e.i] || e.sb->packetJoinDst[e.j])) ||
1032 (isIntra && packetId && e.sb->circuitOnlyDst[e.j]))
1033 continue;
1034 int dst = stateId(e.dst, isIntra ? Out : In);
1035 if (colors[dst] == BLACK || (isIntra && mayCross && !mayCross(s, dst)))
1036 continue;
1037 double w = edgeWeight(e, packetId, avoid, avoidBranch);
1038 if (distance[s] + w >= distance[dst])
1039 continue;
1040 distance[dst] = distance[s] + w;
1041 preds[dst] = s;
1042 predEdge[dst] = e;
1043 if (colors[dst] == WHITE) {
1044 colors[dst] = GRAY;
1045 Q.push(dst);
1046 } else {
1047 Q.update(dst);
1048 }
1049 }
1050 colors[s] = BLACK;
1051 }
1052}
1053
1054// What findPaths keeps from one flow and iteration to the next.
1056 explicit RouteState(const Pathfinder &pf);
1057
1058 int groupOf(const Flow &f) const;
1059 SmallVector<int, 4> idsTo(int flow, int dstState) const;
1060 void relateParts();
1061 int splitPart(int flow, const std::set<int> &ids);
1062 bool isPinned(const Flow &f) const;
1063
1066 // Stamp-based "processed" set (avoids O(n) clears per flow).
1067 std::vector<uint32_t> processedStamp;
1068 uint32_t curStamp = 0;
1069 // The flows to route: one per source, less the packets split off into parts
1070 // of their own (see below), which route as flows from the same source.
1071 std::vector<Flow> parts;
1072 std::map<PathEndPoint, SmallVector<int, 2>> partsOf;
1073 std::set<PathEndPoint> flowDsts;
1074 // group flows based on packetGroupId; pinned trees go in first, so the
1075 // flows routed around them see them.
1076 llvm::MapVector<int, SmallVector<int, 8>> groupedFlows;
1077 // Packet flows that conflict, by the ids each carries or by
1078 // RoutingFaults::apart.
1079 std::vector<llvm::BitVector> conflicting;
1080 std::set<std::pair<PathEndPoint, PathEndPoint>> apartSources;
1081 std::set<std::pair<PathEndPoint, PathEndPoint>> togetherSources;
1082 // Sources a tree had to meet this iteration but whose other ids conflict
1083 // with it (see TreeBuilder::meet), which route together from then on.
1084 std::set<std::pair<PathEndPoint, PathEndPoint>> meetBlocked;
1085 // Ids a source routes as a part of their own so the rest of its tree can
1086 // meet another source's, by that pair (see TreeBuilder::findJoins).
1087 std::set<std::pair<std::pair<PathEndPoint, PathEndPoint>, std::set<int>>>
1089 // The packet ids each flow carries, in all and to each destination.
1090 std::vector<std::set<int>> flowIds;
1091 std::vector<SmallVector<int, 4>> sameId;
1092 // Each packet flow's tree as routed so far this iteration: the state each
1093 // hop reaches, from which state and by which edge; and its destinations.
1094 std::vector<llvm::DenseMap<int, std::pair<int, Edge>>> treeOf;
1095 // Each circuit flow's hops this iteration, which treeOf keeps for packet
1096 // flows only.
1097 std::vector<SmallVector<Edge, 8>> circuitHops;
1098 std::vector<SmallVector<int, 4>> treeDsts;
1099 // The hops each flow takes only by joining another flow's tree, by the flow
1100 // it joined. A join the routing check faults is not made again.
1101 std::vector<SmallVector<std::pair<int, Edge>, 8>> joinedHops;
1102 std::set<std::pair<int, int>> noJoin;
1103 // Where the routing check split a flow's tree: the tile it branches at, the
1104 // ids to branch apart there, and the state of the destination that reaches
1105 // the tile apart, if one does.
1106 struct IdSplit {
1108 int a, b;
1109 std::optional<int> apart;
1110 bool operator<(const IdSplit &other) const {
1111 return std::tie(at, a, b, apart) <
1112 std::tie(other.at, other.a, other.b, other.apart);
1113 }
1114 };
1115 std::vector<std::set<IdSplit>> splitsOf;
1116 // Each split, relation, untrunk and no-join pair the routing check has taught
1117 // this attempt, counted once: a stall drops splitsOf, and the check teaching
1118 // the same split again is no progress.
1119 std::set<std::pair<int, IdSplit>> splitsTaught;
1120 int lessons = 0;
1121 // A split one tree cannot make, since a destination takes both ids, moves
1122 // the second id to a part of its own. Parts of a source split apart at a
1123 // tile leave it by different master ports: the part routed later keeps off
1124 // those the other's tree takes there.
1125 std::vector<std::set<std::pair<TileID, int>>> partSplits;
1126 // Flows that found no one switchbox to meet a tree routed before them at,
1127 // by that tree's flow; each such pair routes the other way round once.
1128 std::set<std::pair<int, int>> unmet, reordered;
1129 // A tree branching for two destinations at its source switchbox may leave
1130 // no slave port there to meet it by. Each of an unmet pair then reaches the
1131 // destinations it shares with the other by one master port out of it.
1132 std::set<std::pair<int, int>> trunked;
1133 // Sources whose trunk took their tree back through a switchbox it holds an
1134 // arbiter in (RoutingFaults::untrunk), which branch freely from then on.
1135 std::set<PathEndPoint> untrunked;
1136 // The flows that met a tree this iteration, by its flow, and how often the
1137 // routing check faulted a meeting of each pair.
1138 std::set<std::pair<int, int>> met;
1139 // The source whose tree met another's by each slave port this iteration, by
1140 // the tree it met: a tree from another source meeting it there would only
1141 // share the first one's way in, not meet.
1142 std::map<std::pair<int, int>, PathEndPoint> meetingPorts;
1143 std::map<std::pair<int, int>, int> meetFaults;
1144 // Joined pairs the routing check faulted along with hops neither joined,
1145 // which were left to the penalties on those hops once.
1146 std::set<std::pair<int, int>> spared;
1147 // A control-packet reload keeps the master sets the prioritized flows' trees
1148 // leave each switchbox by, so another flow leaving by one of those master
1149 // ports leaves by all of one such set and no others.
1150 llvm::DenseSet<int> priorityMasters;
1151 std::vector<SmallVector<int, 4>> prioritySets;
1152 bool mayLeave(ArrayRef<int> masters, int next) const;
1153 bool reorder(int later, int earlier, bool again = false);
1154 void splitOwnIds(const std::pair<PathEndPoint, PathEndPoint> &pair);
1155};
1156
1158 : pf(pf), processedStamp(2 * pf.nodes.size(), 0), parts(pf.flows),
1159 conflicting(parts.size(), llvm::BitVector(parts.size())),
1160 flowIds(parts.size()), treeOf(parts.size()), circuitHops(parts.size()),
1161 treeDsts(parts.size()), joinedHops(parts.size()), splitsOf(parts.size()),
1162 partSplits(parts.size()) {
1163 for (auto [k, f] : llvm::enumerate(parts)) {
1164 partsOf[f.src].push_back(k);
1165 flowDsts.insert(f.dsts.begin(), f.dsts.end());
1166 }
1167 for (auto [k, f] : llvm::enumerate(parts))
1168 groupedFlows[groupOf(f)].push_back(k);
1169 for (const auto &[ends, ids] : pf.packetIdsTo)
1170 flowIds[partsOf.at(ends.first).front()].insert(ids.begin(), ids.end());
1171 relateParts();
1172 // A pinned source's other packets follow the pinned tree where they go
1173 // everywhere it goes, so they leave each switchbox by its master sets, and
1174 // otherwise route as a part of their own.
1175 for (size_t k = 0, n = parts.size(); k < n; k++) {
1176 if (!isPinned(parts[k]))
1177 continue;
1178 const PathEndPoint &src = parts[k].src;
1179 const std::set<int> &prioritized = pf.priorityIds.at(src);
1180 std::set<PathEndPoint> treeDsts;
1181 std::map<int, std::set<PathEndPoint>> dstsOf;
1182 for (const auto &[ends, ids] : pf.packetIdsTo)
1183 if (ends.first == src)
1184 for (int id : ids)
1185 (prioritized.count(id) ? treeDsts : dstsOf[id]).insert(ends.second);
1186 std::set<int> others;
1187 for (const auto &[id, dsts] : dstsOf)
1188 if (!prioritized.count(id) && dsts != treeDsts)
1189 others.insert(id);
1190 if (!others.empty())
1191 splitPart(k, others);
1192 }
1193 for (const auto &[src, tree] : pf.constraints.pinned) {
1194 std::map<PathEndPoint, SmallVector<int, 4>> sets;
1195 for (const TreeHop &h : tree) {
1196 auto to = pf.nodeIds.find(h.to);
1197 if (h.isCrossbar && to != pf.nodeIds.end())
1198 sets[h.from].push_back(stateId(to->second, Out));
1199 }
1200 for (auto &[_, set] : sets) {
1201 llvm::sort(set);
1202 priorityMasters.insert(set.begin(), set.end());
1203 prioritySets.push_back(std::move(set));
1204 }
1205 }
1206}
1207
1208// Route `later` before `earlier` from the next iteration on, unless the two
1209// were reordered before and this is not `again`.
1210bool Pathfinder::RouteState::reorder(int later, int earlier, bool again) {
1211 if (!again && (reordered.count({earlier, later}) ||
1212 !reordered.insert({later, earlier}).second))
1213 return false;
1214 SmallVector<int, 8> &group = groupedFlows[groupOf(parts[later])];
1215 if (!llvm::is_contained(group, earlier))
1216 return false;
1217 group.erase(llvm::find(group, later));
1218 group.insert(llvm::find(group, earlier), later);
1219 return true;
1220}
1221
1222// Trees with an id in common join where they meet, so the ids a source sends
1223// that the other does not route apart as a part of their own.
1225 const std::pair<PathEndPoint, PathEndPoint> &pair) {
1226 for (auto [src, other] : {pair, std::pair{pair.second, pair.first}}) {
1227 auto srcParts = partsOf.find(src);
1228 auto otherParts = partsOf.find(other);
1229 if (srcParts == partsOf.end() || otherParts == partsOf.end())
1230 continue;
1231 std::set<int> otherIds;
1232 for (int k : otherParts->second)
1233 otherIds.insert(flowIds[k].begin(), flowIds[k].end());
1234 for (int k : SmallVector<int, 2>(srcParts->second)) {
1235 std::set<int> own;
1236 for (int id : flowIds[k])
1237 if (!otherIds.count(id))
1238 own.insert(id);
1239 if (!parts[k].isPriorityFlow && !own.empty() &&
1240 own.size() < flowIds[k].size())
1241 splitPart(k, own);
1242 }
1243 }
1244}
1245
1246// Whether a tree whose packets leave a switchbox by `masters` from one slave
1247// port may leave it by `next` too; see priorityMasters.
1248bool Pathfinder::RouteState::mayLeave(ArrayRef<int> masters, int next) const {
1249 if (!priorityMasters.count(next) &&
1250 llvm::none_of(masters, [&](int m) { return priorityMasters.count(m); }))
1251 return true;
1252 return llvm::any_of(prioritySets, [&](const SmallVector<int, 4> &set) {
1253 return llvm::is_contained(set, next) && llvm::all_of(masters, [&](int m) {
1254 return llvm::is_contained(set, m);
1255 });
1256 });
1257}
1258
1260 return f.isPriorityFlow && pf.constraints.pinned.count(f.src);
1261}
1262
1264 return isPinned(f) ? std::numeric_limits<int>::min() : f.packetGroupId;
1265}
1266
1267SmallVector<int, 4> Pathfinder::RouteState::idsTo(int flow,
1268 int dstState) const {
1269 SmallVector<int, 4> ids;
1270 auto it =
1271 pf.packetIdsTo.find({parts[flow].src, pf.nodes[stateNode(dstState)]});
1272 if (it != pf.packetIdsTo.end())
1273 for (int id : it->second)
1274 if (flowIds[flow].count(id))
1275 ids.push_back(id);
1276 return ids;
1277}
1278
1280 sameId.assign(parts.size(), {});
1281 conflicting.assign(parts.size(), llvm::BitVector(parts.size()));
1282 for (size_t a = 0; a < parts.size(); a++)
1283 for (size_t b = 0; b < parts.size(); b++) {
1284 // Trees with an id in common join where they meet, so are never apart.
1285 bool same = llvm::any_of(flowIds[a],
1286 [&](int id) { return flowIds[b].count(id); });
1287 if (a != b && same)
1288 sameId[a].push_back(b);
1289 if (a < b && parts[a].packetId && parts[b].packetId &&
1290 ((!same &&
1291 apartSources.count(std::minmax(parts[a].src, parts[b].src))) ||
1292 (pf.constraints.conflict &&
1293 pf.constraints.conflict(parts[a].src, flowIds[a], parts[b].src,
1294 flowIds[b])))) {
1295 conflicting[a].set(b);
1296 conflicting[b].set(a);
1297 }
1298 }
1299}
1300
1301int Pathfinder::RouteState::splitPart(int flow, const std::set<int> &ids) {
1302 int part = parts.size();
1303 Flow f = parts[flow];
1304 LLVM_DEBUG({
1305 llvm::dbgs() << "\t\tRouting ids";
1306 for (int id : ids)
1307 llvm::dbgs() << ' ' << id;
1308 llvm::dbgs() << " from " << describeTilePort(f.src.coords, f.src.port)
1309 << " apart\n";
1310 });
1311 for (int id : ids)
1312 flowIds[flow].erase(id);
1313 flowIds.push_back(ids);
1314 auto carries = [&](int k, const PathEndPoint &p) {
1315 auto it = pf.packetIdsTo.find({f.src, p});
1316 return it != pf.packetIdsTo.end() &&
1317 llvm::any_of(it->second, [&](int i) { return flowIds[k].count(i); });
1318 };
1319 llvm::erase_if(f.dsts,
1320 [&](const PathEndPoint &p) { return !carries(part, p); });
1321 llvm::erase_if(parts[flow].dsts,
1322 [&](const PathEndPoint &p) { return !carries(flow, p); });
1323 f.packetId = *ids.begin();
1324 std::optional<int> &flowId = parts[flow].packetId;
1325 if (flowId && ids.count(*flowId))
1326 flowId = *flowIds[flow].begin();
1327 auto prioritized = [&](const std::set<int> &carried) {
1328 auto prio = pf.priorityIds.find(f.src);
1329 return prio != pf.priorityIds.end() && llvm::any_of(carried, [&](int id) {
1330 return prio->second.count(id);
1331 });
1332 };
1333 f.isPriorityFlow = prioritized(ids);
1334 parts[flow].isPriorityFlow = prioritized(flowIds[flow]);
1335 parts.push_back(f);
1336 partsOf[f.src].push_back(part);
1337 groupedFlows[groupOf(f)].push_back(part);
1338 relateParts();
1339 treeOf.emplace_back();
1340 circuitHops.emplace_back();
1341 treeDsts.emplace_back();
1342 joinedHops.emplace_back();
1343 for (auto [a, b] : std::set<std::pair<int, int>>(noJoin))
1344 if (a == flow || b == flow)
1345 noJoin.insert({a == flow ? part : a, b == flow ? part : b});
1346 splitsOf.push_back(splitsOf[flow]);
1347 partSplits.push_back(partSplits[flow]);
1348 for (auto [at, other] : partSplits[flow])
1349 partSplits[other].insert({at, part});
1350 for (auto [at, a, b, apart] : splitsOf[flow])
1351 if (ids.count(a) != ids.count(b) &&
1352 flowIds[flow].count(ids.count(a) ? b : a)) {
1353 partSplits[flow].insert({at, part});
1354 partSplits[part].insert({at, flow});
1355 }
1356 return part;
1357}
1358
1359// A link with a channel no flow takes and a free master port driving it
1360// was overused only by the way the flows went; its flows could spread.
1361bool Pathfinder::hasRoom(const SwitchboxConnect &sb) const {
1362 if (sb.isCrossbar)
1363 return true;
1364 auto xbar = graph.find(crossbarKey(sb.srcCoords));
1365 for (size_t i = 0; i < sb.srcPorts.size(); i++)
1366 for (size_t j = 0; j < sb.dstPorts.size(); j++) {
1367 const SwitchboxConnect::Cell &c = sb.at(i, j);
1368 if (!c.available || c.usedCapacity > 0)
1369 continue;
1370 if (xbar == graph.end())
1371 return true;
1372 const SwitchboxConnect &x = xbar->second;
1373 int k = x.dstIndex(sb.srcPorts[i]);
1374 if (k < 0)
1375 return true;
1376 for (size_t row = 0; row < x.srcPorts.size(); row++)
1377 if (x.at(row, k).available)
1378 return true;
1379 }
1380 return false;
1381}
1382
1383llvm::Error Pathfinder::explainNoRouting(const RouteState &st) const {
1384 // A prioritized flow keeps the route it takes alone, so the others
1385 // may have had to fit around it.
1386 auto overused = [](const SwitchboxConnect &sb) {
1387 return !sb.isCrossbar &&
1388 llvm::any_of(sb.cells, [](const SwitchboxConnect::Cell &c) {
1389 return c.usedCapacity > maxCircuitStreamCapacity;
1390 });
1391 };
1392 auto link = [](const SwitchboxConnect &sb) -> std::string {
1393 return llvm::formatv("from tile ({0}, {1}) to ({2}, {3})", sb.srcCoords.col,
1394 sb.srcCoords.row, sb.dstCoords.col, sb.dstCoords.row);
1395 };
1396 const Flow *prioritized = nullptr;
1397 llvm::SetVector<const SwitchboxConnect *> held;
1398 for (auto [k, f] : llvm::enumerate(st.parts)) {
1399 if (!st.isPinned(f))
1400 continue;
1401 prioritized = prioritized ? prioritized : &f;
1402 for (const auto &[_, hop] : st.treeOf[k]) {
1403 if (overused(*hop.second.sb)) {
1404 return llvm::make_error<PinnedRoutingFailure>(
1405 describePrioritized(describeTilePort(f.src.coords, f.src.port)) +
1406 ", and it holds a channel " + link(*hop.second.sb) +
1407 " the other flows need.");
1408 }
1409 if (!hop.second.sb->isCrossbar)
1410 held.insert(hop.second.sb);
1411 }
1412 }
1413 if (prioritized && llvm::any_of(graph, [&](const auto &entry) {
1414 return overused(entry.second);
1415 })) {
1416 return llvm::make_error<PinnedRoutingFailure>(
1418 describeTilePort(prioritized->src.coords, prioritized->src.port)) +
1419 ", and the router found no routing for the other flows around the "
1420 "channels it holds " +
1421 joinNames(llvm::to_vector(
1422 llvm::map_range(llvm::make_pointee_range(held), link))) +
1423 ".");
1424 }
1425 // The routing check says more than the overuse it led to.
1426 if (!checkReason.empty())
1427 return llvm::make_error<RoutingFailure>(checkReason);
1428 // Name the channel the last iteration overused that was overused in the
1429 // most iterations, on a link with no room if there is one, and the flows
1430 // the last one routed through it.
1431 const SwitchboxConnect *worst = nullptr;
1432 int worstI = 0, worstJ = 0;
1433 std::pair<bool, int> worstRank{false, 0};
1434 for (const auto &[_, sb] : graph) {
1435 std::optional<bool> roomless;
1436 for (size_t i = 0; i < sb.srcPorts.size(); i++)
1437 for (size_t j = 0; j < sb.dstPorts.size(); j++) {
1438 if (sb.at(i, j).usedCapacity <= maxCircuitStreamCapacity)
1439 continue;
1440 if (!roomless)
1441 roomless = !hasRoom(sb);
1442 std::pair<bool, int> rank{*roomless, sb.at(i, j).overCapacity};
1443 if (rank > worstRank) {
1444 worst = &sb;
1445 worstI = i;
1446 worstJ = j;
1447 worstRank = rank;
1448 }
1449 }
1450 }
1451 if (!worst)
1452 return llvm::make_error<RoutingFailure>("");
1453 bool crossbar = worst->isCrossbar;
1454 std::vector<std::string> users;
1455 for (const auto &[src, settings] : st.routing.settings) {
1456 auto it = settings.find(worst->srcCoords);
1457 if (it == settings.end())
1458 continue;
1459 const SwitchSetting &s = it->second;
1460 bool uses = false;
1461 for (size_t k = 0; k < s.dsts.size() && !uses; k++)
1462 uses = crossbar
1463 ? k < s.srcs.size() && s.srcs[k] == worst->srcPorts[worstI] &&
1464 s.dsts[k] == worst->dstPorts[worstJ]
1465 : llvm::is_contained(worst->srcPorts, s.dsts[k]);
1466 if (uses)
1467 users.push_back(describeTilePort(src.coords, src.port));
1468 }
1469 std::string where =
1470 crossbar ? llvm::formatv("the connection from {0} to {1} at tile ({2}, "
1471 "{3})",
1472 describePort(worst->srcPorts[worstI]),
1473 describePort(worst->dstPorts[worstJ]),
1474 worst->srcCoords.col, worst->srcCoords.row)
1475 .str()
1476 : "the links " + link(*worst);
1477 if (users.empty())
1478 return llvm::make_error<RoutingFailure>(
1479 "the router found no routing that fits " + where + ".");
1480 return llvm::make_error<RoutingFailure>(
1481 "the flows from " + joinNames(users) + " need " + where +
1482 ", and the router found no routing that fits them.");
1483}
1484
1485std::tuple<bool, int, bool> xilinx::AIE::boundaryOf(TileID a, TileID b) {
1486 bool rows = a.col == b.col;
1487 return {rows, rows ? std::min(a.row, b.row) : std::min(a.col, b.col),
1488 rows ? b.row > a.row : b.col > a.col};
1489}
1490
1491llvm::Error Pathfinder::cutOverflow() const {
1492 // Each circuit tree crossing a boundary needs a channel of its own, and the
1493 // packet flows one more, or one each for streams no two of which may share
1494 // an arbiter, since a channel's master port has one. Channels fixed
1495 // connections hold are not the router's to use, so this rejects only what
1496 // it could not route anyway.
1497 auto onDevice = [&](TileID t) { return t.col < columns && t.row < rows; };
1498 std::map<std::tuple<bool, int, bool>, size_t> channels;
1499 for (const auto &[ends, sb] : graph) {
1500 const auto &[a, b, isCrossbar] = ends;
1501 auto xbar = graph.find(crossbarKey(a));
1502 if (isCrossbar || !onDevice(a) || !onDevice(b) || xbar == graph.end())
1503 continue;
1504 std::tuple<bool, int, bool> cut = boundaryOf(a, b);
1505 const SwitchboxConnect &x = xbar->second;
1506 // A boundary with no available channel at all (every one is a fixed
1507 // connection's) still needs an entry, so flows that must cross it are
1508 // not skipped as if the boundary did not exist.
1509 channels[cut] += 0;
1510 for (Port port : sb.srcPorts) {
1511 int k = x.dstIndex(port);
1512 if (k >= 0 &&
1513 llvm::any_of(llvm::seq<size_t>(0, x.srcPorts.size()),
1514 [&](size_t i) { return x.at(i, k).available; }))
1515 channels[cut]++;
1516 }
1517 }
1518 for (const auto &[cut, available] : channels) {
1519 bool rows = std::get<0>(cut), up = std::get<2>(cut);
1520 int below = std::get<1>(cut);
1521 auto low = [&](TileID t) { return (rows ? t.row : t.col) <= below; };
1522 std::vector<std::string> circuits;
1523 bool packets = false;
1524 for (const Flow &f : flows) {
1525 if (low(f.src.coords) != up ||
1526 llvm::none_of(f.dsts, [&](const PathEndPoint &d) {
1527 return low(d.coords) != up;
1528 }))
1529 continue;
1530 if (f.packetId)
1531 packets = true;
1532 else
1533 circuits.push_back(describeTilePort(f.src.coords, f.src.port));
1534 }
1535 PacketsApart apart;
1536 if (packets && constraints.apartAcross && available > circuits.size())
1537 apart = constraints.apartAcross(low, up, available - circuits.size());
1538 size_t needed =
1539 circuits.size() + std::max<size_t>(packets, apart.flows.size());
1540 LLVM_DEBUG(llvm::dbgs() << "Cut " << (rows ? "row " : "column ") << below
1541 << (up ? " up" : " down") << ": " << needed
1542 << " of " << available << " channels\n");
1543 if (needed <= available)
1544 continue;
1545 int from = up ? below : below + 1, to = up ? below + 1 : below;
1546 auto channel = [](size_t n) { return n == 1 ? "channel" : "channels"; };
1547 std::string who =
1548 circuits.empty() ? "" : "the circuit flows from " + joinNames(circuits);
1549 if (apart.flows.size() > 1)
1550 who += (who.empty() ? "" : ", and ") + joinNames(apart.flows) +
1551 ", no two of which can share an arbiter,";
1552 else if (packets)
1553 who =
1554 circuits.empty() ? "the packet flows" : who + ", with packet flows,";
1555 std::string why =
1556 apart.flows.size() > 1 ? " For example, " + apart.why : "";
1557 return llvm::make_error<RoutingFailure>(llvm::formatv(
1558 "{0} cross from {1} {2} to {1} {3}, which takes {4} {5} across, and "
1559 "it has {6} {7}.{8}",
1560 who, rows ? "row" : "column", from, to, needed, channel(needed),
1561 available, channel(available), why));
1562 }
1563 return llvm::Error::success();
1564}
1565
1566// One flow's tree, grown by routePart.
1569
1570 // A destination port is driven by its switchbox, so it is reached on
1571 // the Out side.
1572 int dstState(const PathEndPoint &p) const {
1573 return stateId(pf.nodeIds.at(p), Out);
1574 }
1575 bool isPending(int state) const;
1576 void reach(ArrayRef<int> dsts);
1577 bool joinable(int at, ArrayRef<int> dsts) const;
1578 void findJoins();
1579 void meet();
1580 void meet(int owner);
1581 void search(const llvm::DenseSet<int> &drop, ArrayRef<int> targets,
1582 const llvm::DenseSet<int> &off = {});
1583 bool trace(int state);
1584 llvm::DenseSet<int> splitOff(int dst) const;
1585 llvm::DenseSet<int> trunkOff(int dst) const;
1586 llvm::Error placePinned();
1587 llvm::Error grow();
1588 void reroute();
1589 void claim();
1590 bool join(int state, int predId, const Edge &e);
1591 void joinTrees();
1592 void record();
1593
1596 int flow;
1597 const Flow &part;
1598 const llvm::BitVector *avoid;
1599 // The route the flow takes alone, if it is pinned to it.
1600 const std::vector<TreeHop> *pinned = nullptr;
1602 // The states the tree reaches, and how many hops from the source each is.
1603 SmallVector<int, 16> tree, treeHops;
1604 SmallVector<int, 16> seeds;
1605 SmallVector<double, 16> seedCosts;
1606 // The tree's hops, by the state each reaches, from which state and by
1607 // which edge, in the order they were traced. They take effect once the
1608 // tree is final.
1609 llvm::MapVector<int, std::pair<int, Edge>> planned;
1610 llvm::DenseMap<int, int> children;
1611 // A branch off a port the tree already crosses joins that port's unit
1612 // (see planArbiters), so it avoids the flows conflicting with any flow
1613 // on those arbiters too.
1614 llvm::DenseMap<int, llvm::BitVector> branchAvoid;
1615 SmallVector<PathEndPoint, 4> pending;
1616 bool toSelf = false;
1617 // The destination to reach first, if not the nearest.
1618 std::optional<PathEndPoint> first;
1619 // A switchbox routes on the id alone, so packets that reach a master
1620 // port another source's tree takes an id they share by go wherever
1621 // that id goes from there. The flow may join the tree there only if
1622 // it still has to reach each of those destinations, with just the ids
1623 // they share.
1624 llvm::DenseMap<int, SmallVector<int, 4>> joins;
1625 llvm::DenseMap<int, SmallVector<int, 2>> joinOwners;
1626 llvm::DenseSet<int> stops, unjoinable;
1627 // The destinations the flow still has to reach that each other source's
1628 // tree reaches with the ids they share, less the trees it may not join.
1629 llvm::MapVector<int, SmallVector<int, 4>> sharedDsts;
1630 // The destinations it shares with trees it could meet but for the other
1631 // ids those trees carry.
1632 llvm::MapVector<int, SmallVector<int, 4>> blockedDsts;
1633 // The destinations it shares with trees with other ids it could meet but
1634 // for its own ids that go elsewhere, and those ids.
1635 llvm::MapVector<int, std::pair<SmallVector<int, 4>, std::set<int>>>
1637 llvm::DenseSet<int> disagree, foreign;
1638 // The destinations the flow reaches where it meets another tree.
1639 SmallVector<int, 4> met;
1640 // The master ports the source's other parts take at the tiles the flow
1641 // was split apart from them at.
1642 llvm::DenseSet<int> partOff;
1643 // The destinations the flow reaches by one master port out of its source
1644 // switchbox (see RouteState::trunked).
1645 llvm::DenseSet<int> trunkDsts;
1646 SmallVector<int, 4> reached;
1647 SmallVector<std::pair<int, const SmallVector<int, 4> *>, 2> joinedAt;
1648 SmallVector<std::pair<int, std::pair<int, Edge>>, 8> pinnedJoins;
1649 SmallVector<int, 4> pinnedJoinDsts;
1650};
1651
1653 : pf(pf), st(st), flow(flow), part(st.parts[flow]),
1654 avoid(part.packetId ? &st.conflicting[flow] : nullptr) {
1655 if (st.isPinned(part))
1656 pinned = &pf.constraints.pinned.at(part.src);
1657 // The flow source port feeds into its switchbox, so the tree starts
1658 // on its In side and the first edge taken is necessarily a crossbar
1659 // hop.
1660 int srcId = pf.nodeIds.at(part.src);
1661 tree.push_back(stateId(srcId, In));
1662 treeHops.push_back(0);
1663 st.processedStamp[tree.front()] = ++st.curStamp;
1664 for (const PathEndPoint &endPoint : part.dsts) {
1665 // Route to self: the port is both ends. Where its switchbox cannot
1666 // connect it to itself (Core to Core), the stream has to leave and
1667 // come back, which Dijkstra finds from the In side to the Out side.
1668 // A tree the flow joins may reach the port for it instead. A port in
1669 // priorityMasters is reached like any other destination, so mayLeave
1670 // still holds.
1671 int self = stateId(srcId, Out);
1672 if (endPoint == part.src && !st.priorityMasters.count(self) &&
1673 llvm::any_of(pf.adjacency[srcId],
1674 [&](const Edge &e) { return e.dst == srcId; })) {
1675 toSelf = true;
1676 continue;
1677 }
1678 pending.push_back(endPoint);
1679 }
1680 findJoins();
1681 for (auto it = st.trunked.lower_bound({flow, 0});
1682 !st.untrunked.count(part.src) && it != st.trunked.end() &&
1683 it->first == flow;
1684 ++it) {
1685 SmallVector<int, 4> shared;
1686 for (const PathEndPoint &dst : st.parts[it->second].dsts)
1687 if (llvm::is_contained(part.dsts, dst))
1688 shared.push_back(dstState(dst));
1689 if (shared.size() > 1)
1690 trunkDsts.insert(shared.begin(), shared.end());
1691 }
1692 for (auto [at, other] : st.partSplits[flow])
1693 for (const auto &[state, _] : st.treeOf[other])
1694 if ((state & 1) == Out && pf.nodes[stateNode(state)].coords == at)
1695 partOff.insert(state);
1696}
1697
1699 return (toSelf && state == dstState(part.src)) ||
1700 llvm::any_of(pending, [&](const PathEndPoint &p) {
1701 return dstState(p) == state;
1702 });
1703}
1704
1705void Pathfinder::TreeBuilder::reach(ArrayRef<int> dsts) {
1706 llvm::erase_if(pending, [&](const PathEndPoint &p) {
1707 return llvm::is_contained(dsts, dstState(p));
1708 });
1709 if (llvm::is_contained(dsts, dstState(part.src)))
1710 toSelf = false;
1711}
1712
1713bool Pathfinder::TreeBuilder::joinable(int at, ArrayRef<int> dsts) const {
1714 return !unjoinable.count(at) &&
1715 llvm::all_of(dsts, [&](int dst) { return isPending(dst); });
1716}
1717
1719 auto shared = [&](ArrayRef<int> ids, int other) {
1720 std::set<int> common;
1721 for (int id : ids)
1722 if (st.flowIds[other].count(id))
1723 common.insert(id);
1724 return common;
1725 };
1726 for (int other : st.sameId[flow]) {
1727 // A tree reaching its own source port takes no hop for it.
1728 const Flow &o = st.parts[other];
1729 int self = dstState(o.src);
1730 if (!st.treeDsts[other].empty() && llvm::is_contained(o.dsts, o.src) &&
1731 isPending(self) && !shared(st.idsTo(other, self), flow).empty())
1732 sharedDsts[other].push_back(self);
1733 for (int dst : st.treeDsts[other]) {
1734 std::set<int> common = shared(st.idsTo(other, dst), flow);
1735 if (common.empty())
1736 continue;
1737 // Joining shares the other flow's arbiters below the join with the
1738 // packets it takes there. A prioritized flow's tree is pinned, so it
1739 // joins only trees pinned with it. A destination of the other flow alone
1740 // keeps the flow off the hops toward it, as no join there is joinable.
1741 bool canJoin =
1742 (!isPending(dst) || common == shared(st.idsTo(flow, dst), other)) &&
1743 !st.noJoin.count({flow, other}) &&
1744 (!part.isPriorityFlow || st.parts[other].isPriorityFlow);
1745 bool agree = canJoin && !(pf.constraints.conflict &&
1746 pf.constraints.conflict(part.src, common, o.src,
1747 st.flowIds[other]));
1748 if (!agree)
1749 disagree.insert(other);
1750 else if (isPending(dst))
1751 sharedDsts[other].push_back(dst);
1752 // Only the conflict kept it from joining, and only the ids it shares
1753 // with the tree are left to conflict if those leave apart.
1754 if (canJoin && !agree && isPending(dst) &&
1755 !pf.constraints.conflict(part.src, common, o.src, common))
1756 blockedDsts[other].push_back(dst);
1757 for (auto it = st.treeOf[other].find(dst); it != st.treeOf[other].end();
1758 it = st.treeOf[other].find(it->second.first)) {
1759 int up = it->second.first;
1760 if ((up & 1) != Out)
1761 continue;
1762 stops.insert(up);
1763 if (!agree)
1764 unjoinable.insert(up);
1765 if (!llvm::is_contained(joins[up], dst))
1766 joins[up].push_back(dst);
1767 if (!llvm::is_contained(joinOwners[up], other))
1768 joinOwners[up].push_back(other);
1769 }
1770 }
1771 }
1772 // A tree with other ids reaching two of the flow's destinations is met the
1773 // same way, the flow taking its hops below the meeting with its own ids.
1774 // Not for a destination a tree with one of its ids also reaches, which the
1775 // flow has to meet on the way there instead; after meetAhead, only a tree
1776 // routed already, as one routed later meets the flow's tree and so this one.
1777 if (!part.packetId || part.isPriorityFlow)
1778 return;
1779 llvm::DenseSet<int> sameIdDsts;
1780 for (int other : st.sameId[flow]) {
1781 if (pf.consult(Relax::MeetAheadOfPartners) && st.treeDsts[other].empty())
1782 continue;
1783 for (const PathEndPoint &dst : st.parts[other].dsts)
1784 if (!shared(st.idsTo(other, dstState(dst)), flow).empty())
1785 sameIdDsts.insert(dstState(dst));
1786 }
1787 for (auto [other, o] : llvm::enumerate(st.parts)) {
1788 int k = other;
1789 if (k == flow || o.src == part.src || !o.packetId || o.isPriorityFlow ||
1790 st.treeDsts[k].empty() || llvm::is_contained(st.sameId[flow], k) ||
1791 st.noJoin.count({flow, k}))
1792 continue;
1793 SmallVector<int, 4> dsts;
1794 for (int dst : st.treeDsts[k])
1795 if (isPending(dst) && !sameIdDsts.count(dst) && st.treeOf[k].count(dst))
1796 dsts.push_back(dst);
1797 if (dsts.size() < 2)
1798 continue;
1799 if (!st.conflicting[flow].test(k)) {
1800 sharedDsts[k] = std::move(dsts);
1801 foreign.insert(k);
1802 continue;
1803 }
1804 // Where only ids the flow sends elsewhere conflict with the tree, those
1805 // can leave as a part of their own and the rest meet it.
1806 std::set<int> meeting, rest;
1807 for (int dst : dsts)
1808 for (int id : st.idsTo(flow, dst))
1809 meeting.insert(id);
1810 for (int id : st.flowIds[flow])
1811 if (!meeting.count(id))
1812 rest.insert(id);
1813 if (!rest.empty() && pf.constraints.conflict &&
1814 !st.apartSources.count(std::minmax(part.src, o.src)) &&
1815 !pf.constraints.conflict(part.src, meeting, o.src, st.flowIds[k]))
1816 blockedIds[k] = {std::move(dsts), std::move(rest)};
1817 }
1818}
1819
1820// Trees from two sources wait on each other wherever they meet (see HoldCycle),
1821// so two trees meeting at two switchboxes can each hold one arbiter and wait at
1822// the other. The flow meets each tree it shares destinations with at one
1823// switchbox, those it shares the most with first, on that tree's way from its
1824// source to where it branches for them, by a slave port that takes each master
1825// port the tree takes there toward them. Only a packet going to two of them can
1826// hold the arbiter where the trees meet for one and wait where they meet for
1827// the other, so two trees meet only when each sends some id to two shared
1828// destinations.
1830 if (pf.consult(Relax::MeetApart))
1831 return;
1832 auto spans = [&](int k, ArrayRef<int> dsts) {
1833 return llvm::any_of(st.flowIds[k], [&](int id) {
1834 return llvm::count_if(dsts, [&](int dst) {
1835 return llvm::is_contained(st.idsTo(k, dst), id);
1836 }) > 1;
1837 });
1838 };
1839 auto mustMeet = [&](int other) {
1840 return spans(flow, sharedDsts[other]) && spans(other, sharedDsts[other]);
1841 };
1842 // A tree it has to meet but for the other ids it carries leaves those ids to
1843 // a part of their own, which findPaths splits off once the iteration ends.
1844 for (const auto &[other, dsts] : blockedDsts)
1845 if (spans(flow, dsts) && spans(other, dsts))
1846 st.meetBlocked.insert({part.src, st.parts[other].src});
1847 for (const auto &[other, blocked] : blockedIds)
1848 if (spans(flow, blocked.first) && spans(other, blocked.first))
1849 st.meetSplits.insert({{part.src, st.parts[other].src}, blocked.second});
1850 SmallVector<int, 4> owners;
1851 for (int other : llvm::make_first_range(sharedDsts))
1852 if (!disagree.count(other) && mustMeet(other))
1853 owners.push_back(other);
1854 llvm::stable_sort(owners, [&](int a, int b) {
1855 return sharedDsts[a].size() > sharedDsts[b].size();
1856 });
1857 for (int owner : owners) {
1858 llvm::erase_if(sharedDsts[owner], [&](int dst) { return !isPending(dst); });
1859 if (mustMeet(owner))
1860 meet(owner);
1861 }
1862}
1863
1865 st.unmet.insert({flow, owner});
1866 pf.treesMet = true;
1867 bool other = foreign.count(owner);
1868 const auto &t = st.treeOf[owner];
1869 const Flow &o = st.parts[owner];
1870 int root = stateId(pf.nodeIds.at(o.src), In);
1871 // The owner's states from its source down to each shared destination.
1872 SmallVector<SmallVector<int, 16>, 4> paths;
1873 for (int dst : sharedDsts[owner]) {
1874 SmallVector<int, 16> &path = paths.emplace_back(1, dst);
1875 for (auto it = t.find(dst); it != t.end(); it = t.find(it->second.first))
1876 path.push_back(it->second.first);
1877 if (path.size() == 1)
1878 path.push_back(root);
1879 if (path.back() != root)
1880 return;
1881 std::reverse(path.begin(), path.end());
1882 }
1883 size_t trunk = 0;
1884 while (llvm::all_of(paths, [&](const auto &path) {
1885 return trunk + 1 < path.size() && path[trunk] == paths[0][trunk];
1886 }))
1887 trunk++;
1888 struct Meeting {
1889 int in;
1890 SmallVector<std::pair<int, Edge>, 4> hops;
1891 double cost;
1892 size_t at;
1893 };
1894 SmallVector<Meeting, 8> meetings;
1895 SmallVector<int, 8> targets;
1896 // Below a meeting with other ids the flow takes the owner's hops itself.
1897 auto below = [&](size_t k) {
1898 llvm::MapVector<int, std::pair<int, Edge>> hops;
1899 for (const auto &path : paths)
1900 for (size_t l = k + 1; l + 1 < path.size(); l++)
1901 hops.insert({path[l + 1], t.find(path[l + 1])->second});
1902 return hops;
1903 };
1904 for (size_t k = 0; k < trunk; k++) {
1905 int at = paths[0][k];
1906 if ((at & 1) != In)
1907 continue;
1908 SetVector<int> next;
1909 for (const auto &path : paths)
1910 next.insert(path[k + 1]);
1911 if (!other && llvm::any_of(next, [&](int s) {
1912 return !isPending(s) && !(joins.count(s) && joinable(s, joins[s]));
1913 }))
1914 continue;
1915 auto taken = [&](int s) {
1916 return st.processedStamp[s] == st.curStamp || stops.count(s) ||
1917 partOff.count(s);
1918 };
1919 if (other && (llvm::any_of(next, taken) ||
1920 llvm::any_of(below(k), [&](const auto &hop) {
1921 const Edge &e = hop.second.second;
1922 return taken(hop.first) ||
1923 (e.sb->isCrossbar && e.sb->circuitOnlyDst[e.j]);
1924 })))
1925 continue;
1926 SmallVector<int, 4> leaving;
1927 if (llvm::any_of(next, [&](int s) {
1928 bool ok = st.mayLeave(leaving, s);
1929 leaving.push_back(s);
1930 return !ok;
1931 }))
1932 continue;
1933 TileID tile = pf.nodes[stateNode(at)].coords;
1934 auto sb = pf.graph.find(crossbarKey(tile));
1935 if (sb == pf.graph.end())
1936 continue;
1937 for (Port port : sb->second.srcPorts) {
1938 auto node = pf.nodeIds.find({tile, port});
1939 if (node == pf.nodeIds.end())
1940 continue;
1941 int in = stateId(node->second, In);
1942 auto taken = st.meetingPorts.find({owner, in});
1943 if (in == at || t.count(in) ||
1944 (taken != st.meetingPorts.end() && !(taken->second == part.src)))
1945 continue;
1946 Meeting m{in, {}, 0, k};
1947 for (int s : next)
1948 for (const Edge &e : pf.adjacency[node->second])
1949 if (e.dst == stateNode(s) && e.sb == &sb->second &&
1950 !(part.packetId && e.sb->circuitOnlyDst[e.j])) {
1951 m.hops.push_back({s, e});
1952 m.cost += pf.edgeWeight(e, part.packetId, avoid, nullptr);
1953 break;
1954 }
1955 if (m.hops.size() == next.size()) {
1956 meetings.push_back(std::move(m));
1957 targets.push_back(in);
1958 }
1959 }
1960 }
1961 if (meetings.empty())
1962 return;
1963 llvm::DenseSet<int> off;
1964 if (other)
1965 for (const auto &[s, _] : below(0))
1966 off.insert(s);
1967 search({}, targets, off);
1968 const Meeting *best = nullptr;
1969 for (const Meeting &m : meetings)
1970 if (pf.distance[m.in] < INF &&
1971 (!best ||
1972 pf.distance[m.in] + m.cost < pf.distance[best->in] + best->cost))
1973 best = &m;
1974 if (!best || !trace(best->in))
1975 return;
1976 st.unmet.erase({flow, owner});
1977 st.meetingPorts.try_emplace({owner, best->in}, part.src);
1978 st.met.insert({flow, owner});
1979 int hops = treeHops[llvm::find(tree, best->in) - tree.begin()] + 1;
1980 auto add = [&](int s, int from, const Edge &e, int depth) {
1981 planned.insert({s, {from, e}});
1982 ++children[from];
1983 st.processedStamp[s] = st.curStamp;
1984 tree.push_back(s);
1985 treeHops.push_back(depth);
1986 };
1987 for (const auto &[s, e] : best->hops) {
1988 add(s, best->in, e, hops);
1989 if (other) {
1990 st.joinedHops[flow].push_back({owner, e});
1991 continue;
1992 }
1993 if (isPending(s)) {
1994 met.push_back(s);
1995 reach(s);
1996 continue;
1997 }
1998 const SmallVector<int, 4> &dsts = joins[s];
1999 reach(dsts);
2000 joinedAt.push_back({s, &dsts});
2001 ++children[s];
2002 }
2003 if (!other)
2004 return;
2005 for (const auto &[s, hop] : below(best->at)) {
2006 const auto &[from, e] = hop;
2007 add(s, from, e, treeHops[llvm::find(tree, from) - tree.begin()] + 1);
2008 st.joinedHops[flow].push_back({owner, e});
2009 }
2010 for (int dst : sharedDsts[owner]) {
2011 met.push_back(dst);
2012 reach(dst);
2013 }
2014}
2015
2016// Dijkstra from the tree, less the states in `drop`, and not through
2017// those in `off`, until the states in `targets` are settled.
2018void Pathfinder::TreeBuilder::search(const llvm::DenseSet<int> &drop,
2019 ArrayRef<int> targets,
2020 const llvm::DenseSet<int> &off) {
2021 branchAvoid.clear();
2022 llvm::DenseMap<int, llvm::BitVector> onArbiter;
2023 if (avoid)
2024 for (const auto &[state, hop] : planned) {
2025 const auto &[from, e] = hop;
2026 if (!e.sb->isCrossbar || drop.count(state))
2027 continue;
2028 llvm::BitVector &away =
2029 branchAvoid.try_emplace(from, st.conflicting.size()).first->second;
2030 llvm::BitVector &on =
2031 onArbiter.try_emplace(from, st.conflicting.size()).first->second;
2032 for (int other : e.sb->unitFlows(e.j)) {
2033 on.set(other);
2034 if (other != flow)
2035 away |= st.conflicting[other];
2036 }
2037 }
2038 // A flow sharing an arbiter with itself is no conflict, and flows
2039 // already on those arbiters share them whatever the branch does.
2040 for (auto &[from, away] : branchAvoid) {
2041 away.reset(onArbiter.find(from)->second);
2042 away.reset(flow);
2043 }
2044 seeds.clear();
2045 seedCosts.clear();
2046 for (auto [state, hops] : llvm::zip_equal(tree, treeHops))
2047 if (!drop.count(state) && !off.count(state)) {
2048 seeds.push_back(state);
2049 seedCosts.push_back(treeSeedFactor * hops);
2050 }
2051 llvm::DenseSet<int> blocked;
2052 if (!off.empty()) {
2053 blocked = stops;
2054 blocked.insert(off.begin(), off.end());
2055 }
2056 llvm::DenseMap<int, SmallVector<int, 4>> masters;
2057 bool limited = !st.priorityMasters.empty();
2058 if (limited)
2059 for (const auto &[state, hop] : planned)
2060 if ((hop.first & 1) == In && !drop.count(state))
2061 masters[hop.first].push_back(state);
2062 auto mayCross = [&](int from, int to) {
2063 auto it = masters.find(from);
2064 return st.mayLeave(it == masters.end() ? ArrayRef<int>{} : it->second, to);
2065 };
2066 pf.dijkstraShortestPaths(
2067 seeds, seedCosts, part.packetId, avoid, &branchAvoid,
2068 off.empty() ? &stops : &blocked, targets,
2069 limited ? llvm::function_ref<bool(int, int)>(mayCross) : nullptr);
2070}
2071
2072// Trace the path Dijkstra found to `state` back to the tree.
2074 size_t grown = tree.size();
2075 while (st.processedStamp[state] != st.curStamp) {
2076 // If Dijkstra never reached this node it has no predecessor; the
2077 // destination is unroutable under the current demand.
2078 int pred = pf.preds[state];
2079 if (pred < 0)
2080 return false;
2081 planned.insert({state, {pred, pf.predEdge[state]}});
2082 ++children[pred];
2083 st.processedStamp[state] = st.curStamp;
2084 tree.push_back(state);
2085 state = pred;
2086 }
2087 // The new hops were traced from the destination back to the tree.
2088 int hops = treeHops[llvm::find(tree, state) - tree.begin()] +
2089 static_cast<int>(tree.size() - grown);
2090 while (treeHops.size() < tree.size())
2091 treeHops.push_back(hops--);
2092 return true;
2093}
2094
2095// The path to `dst` stays off the hops another destination's path
2096// takes below where the check split the two apart, and off the
2097// slave port it takes there too if one of them has to reach the tile
2098// on its own.
2099llvm::DenseSet<int> Pathfinder::TreeBuilder::splitOff(int dst) const {
2100 llvm::DenseSet<int> off = partOff;
2101 auto carries = [&](int d, int id) {
2102 return llvm::is_contained(st.idsTo(flow, d), id);
2103 };
2104 auto only = [&](int d, int id, int other) {
2105 return carries(d, id) && !carries(d, other);
2106 };
2107 for (auto [at, a, b, apart] : st.splitsOf[flow])
2108 for (int other : reached) {
2109 bool splits = !apart ? (only(dst, a, b) && only(other, b, a)) ||
2110 (only(dst, b, a) && only(other, a, b))
2111 : (only(dst, a, b) && other == *apart) ||
2112 (dst == *apart && only(other, a, b));
2113 if (!splits)
2114 continue;
2115 SmallVector<int, 8> below;
2116 int s = other;
2117 auto entersAt = [&, tile = at](int state) {
2118 return (state & 1) == In && pf.nodes[stateNode(state)].coords == tile;
2119 };
2120 for (auto *hop = planned.find(s); !entersAt(s) && hop != planned.end();
2121 hop = planned.find(s)) {
2122 below.push_back(s);
2123 s = hop->second.first;
2124 }
2125 if (!entersAt(s))
2126 continue;
2127 off.insert(below.begin(), below.end());
2128 if (apart)
2129 off.insert(s);
2130 }
2131 return off;
2132}
2133
2134// The path to a trunked destination leaves the tree below the master port
2135// the others it has reached leave the source switchbox by.
2136llvm::DenseSet<int> Pathfinder::TreeBuilder::trunkOff(int dst) const {
2137 llvm::DenseSet<int> off;
2138 if (!trunkDsts.count(dst))
2139 return off;
2140 int root = tree.front();
2141 auto exitOf = [&](int s) {
2142 for (const auto *it = planned.find(s);
2143 it != planned.end() && it->second.first != root; it = planned.find(s))
2144 s = it->second.first;
2145 return s;
2146 };
2147 const auto *other = llvm::find_if(reached, [&](int d) {
2148 return d != dst && trunkDsts.count(d) && planned.count(d);
2149 });
2150 if (other == reached.end())
2151 return off;
2152 int exit = exitOf(*other);
2153 for (int s : tree)
2154 if (s == root || exitOf(s) != exit)
2155 off.insert(s);
2156 return off;
2157}
2158
2159// Lay the tree along the route the flow takes alone.
2161 for (const auto &[from, to, joined, intra] : *pinned) {
2162 if (toSelf && from == to)
2163 continue;
2164 auto fromId = pf.nodeIds.find(from), toId = pf.nodeIds.find(to);
2165 const Edge *e = nullptr;
2166 if (fromId != pf.nodeIds.end() && toId != pf.nodeIds.end())
2167 for (const Edge &out : pf.adjacency[fromId->second])
2168 if (out.dst == toId->second && out.sb->isCrossbar == intra)
2169 e = &out;
2170 if (!e)
2171 return llvm::make_error<RoutingFailure>(
2172 "the route packet flows from " +
2173 describeTilePort(part.src.coords, part.src.port) +
2174 " take alone does not fit this design: it goes from " +
2175 describeTilePort(from.coords, from.port) + " to " +
2176 describeTilePort(to.coords, to.port) +
2177 ", which the design's own switchboxes leave no connection for.",
2178 RoutingFaults{}, pf.flowLoc(part.src, nullptr));
2179 std::pair<int, std::pair<int, Edge>> hop{
2180 stateId(toId->second, intra ? Out : In),
2181 {stateId(fromId->second, intra ? In : Out), *e}};
2182 if (joined)
2183 pinnedJoins.push_back(hop);
2184 else
2185 planned.insert(hop);
2186 }
2187 int self = dstState(part.src);
2188 if (toSelf && llvm::is_contained(llvm::make_first_range(pinnedJoins), self)) {
2189 toSelf = false;
2190 pinnedJoinDsts.push_back(self);
2191 }
2192 for (const PathEndPoint &p : pending)
2193 (planned.count(dstState(p)) ? reached : pinnedJoinDsts)
2194 .push_back(dstState(p));
2195 pending.clear();
2196 return llvm::Error::success();
2197}
2198
2199// Grow the tree one destination at a time: Dijkstra, given the current
2200// demand, from everything the tree reaches so far to the next destination,
2201// whose path is then traced back to the tree. Growing from the tree rather
2202// than the source lets destinations share hops; see treeSeedFactor for what
2203// a branch off the tree costs.
2205 // A path to another tree can leave the destination to reach first no way
2206 // to it, so the tree meets the others once it reaches it.
2207 bool metTrees = !first || !llvm::is_contained(pending, *first);
2208 if (metTrees)
2209 meet();
2210 while (!pending.empty()) {
2211 SmallVector<int, 8> targets;
2212 for (const PathEndPoint &p : pending)
2213 targets.push_back(dstState(p));
2214 for (const auto &[at, dsts] : joins)
2215 if (joinable(at, dsts))
2216 targets.push_back(at);
2217 search({}, targets);
2218 // The nearest destination joins the tree next, or the nearest join
2219 // brings every destination below it.
2220 auto *nearest =
2221 first && llvm::is_contained(pending, *first)
2222 ? llvm::find(pending, *first)
2223 : llvm::min_element(
2224 pending, [&](const PathEndPoint &a, const PathEndPoint &b) {
2225 return pf.distance[dstState(a)] < pf.distance[dstState(b)];
2226 });
2227 PathEndPoint endPoint = *nearest;
2228 int currId = dstState(endPoint);
2229 llvm::DenseSet<int> off = splitOff(currId);
2230 llvm::DenseSet<int> trunk = trunkOff(currId);
2231 off.insert(trunk.begin(), trunk.end());
2232 if (!off.empty()) {
2233 search({}, targets, off);
2234 if (pf.distance[currId] == INF)
2235 search({}, targets);
2236 }
2237 const SmallVector<int, 4> *joined = nullptr;
2238 for (const auto &[at, dsts] : joins)
2239 if (pf.distance[at] < pf.distance[currId] && joinable(at, dsts)) {
2240 currId = at;
2241 joined = &dsts;
2242 }
2243 if (joined) {
2244 reach(*joined);
2245 joinedAt.push_back({currId, joined});
2246 // The tree it joins goes on below.
2247 ++children[currId];
2248 } else {
2249 pending.erase(nearest);
2250 reached.push_back(currId);
2251 }
2252 if (!trace(currId))
2253 return llvm::make_error<RoutingFailure>(
2254 "no path leads from " +
2255 describeTilePort(part.src.coords, part.src.port) + " to " +
2256 describeTilePort(endPoint.coords, endPoint.port) +
2257 " through the connections the switchboxes allow and existing "
2258 "routing leaves free.",
2259 RoutingFaults{}, pf.flowLoc(part.src, &endPoint));
2260 if (!metTrees) {
2261 metTrees = true;
2262 meet();
2263 }
2264 }
2265 return llvm::Error::success();
2266}
2267
2268// A destination's path was chosen before the tree reached the later
2269// ones, so reroute each destination's own branch from the rest of the
2270// tree where that is cheaper.
2272 for (int dst : reached) {
2273 llvm::DenseSet<int> branch;
2274 int top = dst;
2275 for (int below = 0; top != tree.front() && children.lookup(top) == below;
2276 below = 1) {
2277 branch.insert(top);
2278 top = planned.find(top)->second.first;
2279 }
2280 if (branch.empty())
2281 continue;
2282 llvm::DenseSet<int> off = splitOff(dst), trunk = trunkOff(dst);
2283 off.insert(trunk.begin(), trunk.end());
2284 search(branch, dst, off);
2285 double cost =
2286 treeSeedFactor * treeHops[llvm::find(tree, top) - tree.begin()];
2287 for (int s = dst; s != top;) {
2288 const auto &[from, e] = planned.find(s)->second;
2289 auto away = branchAvoid.find(from);
2290 cost +=
2291 pf.edgeWeight(e, part.packetId, avoid,
2292 away == branchAvoid.end() ? nullptr : &away->second);
2293 s = from;
2294 }
2295 if (pf.distance[dst] + rerouteMinSaving >= cost)
2296 continue;
2297 for (int s : branch) {
2298 st.processedStamp[s] = 0;
2299 planned.erase(s);
2300 children.erase(s);
2301 }
2302 --children[top];
2303 for (size_t k = tree.size(); k-- > 0;)
2304 if (branch.count(tree[k])) {
2305 tree.erase(tree.begin() + k);
2306 treeHops.erase(treeHops.begin() + k);
2307 }
2308 [[maybe_unused]] bool traced = trace(dst);
2309 assert(traced && "a rerouted branch reaches its destination");
2310 }
2311}
2312
2313// Take the channels the tree's hops cross.
2315 if (toSelf) {
2316 switchSettings[part.src.coords].srcs.push_back(part.src.port);
2317 switchSettings[part.src.coords].dsts.push_back(part.src.port);
2318 if (part.packetId) {
2319 st.routing.packetTrees[part.src].push_back(
2320 {part.src, part.src, false, true});
2321 // On the tree too, so a tree that has to meet this one finds the port.
2322 int srcId = pf.nodeIds.at(part.src);
2323 for (const Edge &e : ArrayRef<Edge>(pf.adjacency[srcId])
2324 .take_front(pf.wireEdgesBegin[srcId]))
2325 if (e.dst == srcId) {
2326 st.treeOf[flow].try_emplace(dstState(part.src), tree.front(), e);
2327 st.treeDsts[flow].push_back(dstState(part.src));
2328 break;
2329 }
2330 }
2331 }
2332 const std::optional<int> &packetId = part.packetId;
2333 int packetGroupId = part.packetGroupId;
2334 llvm::DenseMap<int, std::pair<SwitchboxConnect *, int>> branchPort;
2335 for (const auto &[currId, hop] : planned) {
2336 const auto &[predId, e] = hop;
2337 const PathEndPoint &curr = pf.nodes[stateNode(currId)];
2338 const PathEndPoint &pred = pf.nodes[stateNode(predId)];
2339 SwitchboxConnect &sb = *e.sb;
2340 int i = e.i;
2341 int j = e.j;
2342 SwitchboxConnect::Cell &cell = sb.at(i, j);
2343 if (packetId)
2344 st.treeOf[flow].try_emplace(currId, predId, e);
2345 else
2346 st.circuitHops[flow].push_back(e);
2347 cell.isPriority |= part.isPriorityFlow;
2348 // Two trees with the same id may merge onto one only where nothing fans out
2349 // after, or where both take the id to the same destinations, so a merged id
2350 // never fans back out to one tree's destinations alone. The flow's own tree
2351 // branching at a port never merges back.
2352 // packetGroupId only becomes >= 0 when packetId has a value (see
2353 // Pathfinder::addFlow), so the dereferences below are safe; the
2354 // checker just can't correlate the two across this loop's back edge.
2355 // NOLINTBEGIN(bugprone-unchecked-optional-access)
2356 auto seen =
2357 packetId ? cell.packetIds.find(*packetId) : cell.packetIds.end();
2358 auto mergeable = [&] {
2359 if (sb.isCrossbar && !getLinkedInput(sb.dstCoords, sb.dstPorts[j]))
2360 return true;
2361 auto reached = [&](const Flow &f) {
2362 std::set<PathEndPoint> dsts;
2363 for (const PathEndPoint &dst : f.dsts)
2364 if (auto ids = pf.packetIdsTo.find({f.src, dst});
2365 ids != pf.packetIdsTo.end() &&
2366 llvm::is_contained(ids->second, *packetId))
2367 dsts.insert(dst);
2368 return dsts;
2369 };
2370 return reached(part) == reached(st.parts[seen->second]);
2371 };
2372 bool sameGroupUnseen =
2373 packetGroupId >= 0 && packetId.has_value() &&
2374 (cell.packetGroupId == -1 || cell.packetGroupId == packetGroupId) &&
2375 (seen == cell.packetIds.end() || seen->second == flow || mergeable());
2376 if (sameGroupUnseen) {
2377 int packetIdValue = *packetId;
2378 // NOLINTEND(bugprone-unchecked-optional-access)
2379 auto claim = [&](SwitchboxConnect::Cell &c) {
2380 c.packetGroupId = packetGroupId;
2381 c.packetIds.try_emplace(packetIdValue, flow);
2382 };
2383 for (size_t k = 0; k < sb.srcPorts.size(); k++)
2384 claim(sb.at(k, j));
2385 for (size_t l = 0; l < sb.dstPorts.size(); l++)
2386 if (l != static_cast<size_t>(j))
2387 claim(sb.at(i, l));
2388 // maximum packet stream sharing per channel
2389 if (++cell.packetFlowCount >= maxPacketStreamCapacity) {
2390 cell.packetFlowCount = 0;
2391 cell.usedCapacity++;
2392 }
2393 } else {
2394 cell.usedCapacity++;
2395 }
2396 // if at capacity, bump demand to discourage using this Channel
2397 // this means the order matters!
2398 sb.bumpDemand(i, j);
2399 if (sb.isCrossbar) {
2400 switchSettings[pred.coords].srcs.push_back(pred.port);
2401 switchSettings[curr.coords].dsts.push_back(curr.port);
2402 if (packetId) {
2403 sb.addToUnit(j, flow);
2404 auto [it, first] = branchPort.try_emplace(predId, &sb, j);
2405 if (!first)
2406 sb.joinUnits(it->second.second, j);
2407 }
2408 }
2409 }
2410 // A flow from a switchbox port (as --aie-split-flow-vias leaves a via, or a
2411 // packet source on a port) takes the wire that port is fed by, and a circuit
2412 // to one the wire it drives, though no hop of its tree crosses them.
2413 auto takeWire = [](SwitchboxConnect &link, int k) {
2414 if (k < 0)
2415 return;
2416 link.at(k, k).usedCapacity++;
2417 link.bumpDemand(k, k);
2418 };
2419 // A via's next segment starts where the last one ended, on the wire that
2420 // one already takes. A packet source's parts share its wire, which the first
2421 // takes.
2422 bool takesSource = !packetId || st.partsOf.at(part.src).front() == flow;
2423 if (takesSource && getLinkedInput(part.src.coords, part.src.port))
2424 for (auto &[_, link] : pf.graph) {
2425 if (link.isCrossbar || link.dstCoords != part.src.coords)
2426 continue;
2427 int k = link.dstIndex(part.src.port);
2428 if (k >= 0 && !st.flowDsts.count({link.srcCoords, link.srcPorts[k]}))
2429 takeWire(link, k);
2430 }
2431 for (const PathEndPoint &dst : part.dsts)
2432 if (!packetId && getLinkedInput(dst.coords, dst.port)) {
2433 int node = pf.nodeIds.at(dst);
2434 for (const Edge &e : ArrayRef<Edge>(pf.adjacency[node])
2435 .drop_front(pf.wireEdgesBegin[node]))
2436 takeWire(*e.sb, e.i);
2437 }
2438 if (packetId) {
2439 st.treeDsts[flow].append(reached.begin(), reached.end());
2440 st.treeDsts[flow].append(met.begin(), met.end());
2441 for (const auto &[currId, hop] : planned)
2442 st.routing.packetTrees[part.src].push_back(
2443 {pf.nodes[stateNode(hop.first)], pf.nodes[stateNode(currId)], false,
2444 hop.second.sb->isCrossbar});
2445 }
2446}
2447
2448// Below a join the flow's packets follow the tree they joined.
2449bool Pathfinder::TreeBuilder::join(int state, int predId, const Edge &e) {
2450 if (!st.treeOf[flow].try_emplace(state, predId, e).second)
2451 return false;
2452 const PathEndPoint &pred = pf.nodes[stateNode(predId)];
2453 const PathEndPoint &curr = pf.nodes[stateNode(state)];
2454 st.routing.packetTrees[part.src].push_back(
2455 {pred, curr, true, e.sb->isCrossbar});
2456 if (e.sb->isCrossbar) {
2457 switchSettings[pred.coords].srcs.push_back(pred.port);
2458 switchSettings[curr.coords].dsts.push_back(curr.port);
2459 e.sb->addToUnit(e.j, flow);
2460 }
2461 return true;
2462}
2463
2465 for (const auto &[joinAt, joined] : joinedAt) {
2466 for (int other : joinOwners[joinAt]) {
2467 st.joinedHops[flow].push_back(
2468 {other, planned.find(joinAt)->second.second});
2469 for (int dst : *joined) {
2470 const auto &t = st.treeOf[other];
2471 SmallVector<std::pair<int, std::pair<int, Edge>>, 8> path;
2472 auto it = t.find(dst);
2473 for (; it != t.end() && it->first != joinAt;
2474 it = t.find(it->second.first))
2475 path.push_back(*it);
2476 if (it == t.end())
2477 continue;
2478 for (const auto &[state, hop] : path)
2479 if (join(state, hop.first, hop.second))
2480 st.joinedHops[flow].push_back({other, hop.second});
2481 }
2482 }
2483 st.treeDsts[flow].append(joined->begin(), joined->end());
2484 }
2485 for (const auto &[state, hop] : pinnedJoins)
2486 join(state, hop.first, hop.second);
2487 st.treeDsts[flow].append(pinnedJoinDsts.begin(), pinnedJoinDsts.end());
2488}
2489
2490// Add the tree to the routing.
2492 const PathEndPoint &src = part.src;
2493 if (st.partsOf.at(src).size() == 1) {
2494 st.routing.settings[src] = switchSettings;
2495 return;
2496 }
2497 for (int id : st.flowIds[flow])
2498 st.routing.idSettings[{src, id}] = switchSettings;
2499 for (const auto &[tile, setting] : switchSettings) {
2500 SwitchSetting &all = st.routing.settings[src][tile];
2501 for (auto [in, out] : llvm::zip(setting.srcs, setting.dsts))
2502 if (!llvm::is_contained(llvm::zip(all.srcs, all.dsts),
2503 std::make_tuple(in, out))) {
2504 all.srcs.push_back(in);
2505 all.dsts.push_back(out);
2506 }
2507 }
2508}
2509
2510llvm::Error Pathfinder::routePart(RouteState &st, int flow) {
2511 std::optional<TreeBuilder> tree;
2512 tree.emplace(*this, st, flow);
2513 llvm::Error err = tree->pinned ? tree->placePinned() : tree->grow();
2514 // Kept to the prioritized flows' master sets, the branch a tree takes first
2515 // can leave it no way to another destination; each is then tried first.
2516 if (err && !tree->pinned && !st.priorityMasters.empty())
2517 for (const PathEndPoint &dst : st.parts[flow].dsts) {
2518 for (auto *pairs : {&st.unmet, &st.met})
2519 pairs->erase(pairs->lower_bound({flow, 0}),
2520 pairs->lower_bound({flow + 1, 0}));
2521 st.joinedHops[flow].clear();
2522 tree.emplace(*this, st, flow);
2523 tree->first = dst;
2524 if (llvm::Error retry = tree->grow()) {
2525 llvm::consumeError(std::move(retry));
2526 continue;
2527 }
2528 llvm::consumeError(std::move(err));
2529 break;
2530 }
2531 if (err)
2532 return err;
2533 if (!tree->pinned && tree->reached.size() + tree->joinedAt.size() > 1)
2534 tree->reroute();
2535 tree->claim();
2536 tree->joinTrees();
2537 tree->record();
2538 return llvm::Error::success();
2539}
2540
2541int Pathfinder::applyRoutingFaults(RouteState &st, const RoutingFaults &faults,
2542 int &pinnedOnly) {
2543 int illegalEdges = 0;
2544 pinnedOnly = 0;
2545 for (const TreeSplit &split : faults.splits) {
2546 auto src = st.partsOf.find(split.src);
2547 if (src == st.partsOf.end())
2548 continue;
2549 auto partWith = [&](int id) {
2550 for (int k : src->second)
2551 if (st.flowIds[k].count(id))
2552 return k;
2553 return -1;
2554 };
2555 int flow = partWith(split.a), other = partWith(split.b);
2556 if (flow < 0 || other < 0)
2557 continue;
2558 std::optional<int> apart;
2559 if (split.apart) {
2560 auto it = nodeIds.find(*split.apart);
2561 if (it == nodeIds.end())
2562 continue;
2563 apart = stateId(it->second, Out);
2564 }
2565 // Whether a destination taking both ids is reached through the tile.
2566 auto inseparable = [&] {
2567 const Flow &f = st.parts[flow];
2568 for (const PathEndPoint &dst : f.dsts) {
2569 auto ids = packetIdsTo.find({f.src, dst});
2570 if (ids == packetIdsTo.end() ||
2571 !llvm::is_contained(ids->second, split.a) ||
2572 !llvm::is_contained(ids->second, split.b))
2573 continue;
2574 const auto &tree = st.treeOf[flow];
2575 auto it = tree.find(stateId(nodeIds.at(dst), Out));
2576 if (it == tree.end() && dst == f.src && dst.coords == split.at)
2577 return true;
2578 for (; it != tree.end(); it = tree.find(it->second.first)) {
2579 int up = it->second.first;
2580 if ((up & 1) == In && nodes[stateNode(up)].coords == split.at)
2581 return true;
2582 }
2583 }
2584 return false;
2585 };
2586 if (consult(Relax::IdsApart) && flow == other && !split.apart &&
2587 !st.parts[flow].isPriorityFlow && inseparable())
2588 other = st.splitPart(flow, {split.b});
2589 if (flow != other) {
2590 if (st.partSplits[flow].insert({split.at, other}).second) {
2591 illegalEdges++;
2592 st.lessons++;
2593 }
2594 st.partSplits[other].insert({split.at, flow});
2595 } else if (st.splitsOf[flow]
2596 .insert({split.at, split.a, split.b, apart})
2597 .second) {
2598 st.lessons +=
2599 st.splitsTaught.insert({flow, {split.at, split.a, split.b, apart}})
2600 .second;
2601 LLVM_DEBUG(llvm::dbgs()
2602 << "Split ids " << split.a << " and " << split.b << " from "
2603 << describeTilePort(split.src.coords, split.src.port)
2604 << " at tile (" << split.at.col << ", " << split.at.row
2605 << ")\n");
2606 illegalEdges++;
2607 }
2608 }
2609 crowdedTiles.insert(faults.crowded.begin(), faults.crowded.end());
2610 bool related = false;
2611 for (const auto &pair : faults.apart) {
2612 if (!st.apartSources.insert(pair).second)
2613 continue;
2614 related = true;
2615 LLVM_DEBUG(llvm::dbgs()
2616 << "Route apart: "
2617 << describeTilePort(pair.first.coords, pair.first.port)
2618 << " and "
2619 << describeTilePort(pair.second.coords, pair.second.port)
2620 << "\n");
2621 if (consult(Relax::SplitShared))
2622 st.splitOwnIds(pair);
2623 }
2624 for (const auto &pair : faults.together) {
2625 // Trees with one id that share a single receiver wait on each other
2626 // wherever they join above it, so they fan in at that receiver alone.
2627 for (int x : st.partsOf.at(pair.first))
2628 for (int y : st.partsOf.at(pair.second))
2629 if (llvm::is_contained(st.sameId[x], y) &&
2630 llvm::count_if(st.parts[x].dsts, [&](const PathEndPoint &dst) {
2631 return llvm::is_contained(st.parts[y].dsts, dst);
2632 }) < 2) {
2633 st.lessons += st.noJoin.insert({x, y}).second;
2634 st.noJoin.insert({y, x});
2635 }
2636 if (!st.togetherSources.insert(pair).second)
2637 continue;
2638 related = true;
2639 LLVM_DEBUG(llvm::dbgs()
2640 << "Route together: "
2641 << describeTilePort(pair.first.coords, pair.first.port)
2642 << " and "
2643 << describeTilePort(pair.second.coords, pair.second.port)
2644 << "\n");
2645 st.splitOwnIds(pair);
2646 }
2647 if (related) {
2648 illegalEdges++;
2649 st.lessons++;
2650 st.relateParts();
2651 }
2652 for (const PathEndPoint &src : faults.untrunk)
2653 if (st.untrunked.insert(src).second) {
2654 LLVM_DEBUG(llvm::dbgs()
2655 << "Untrunk: " << describeTilePort(src.coords, src.port)
2656 << "\n");
2657 illegalEdges++;
2658 st.lessons++;
2659 }
2660 std::set<std::pair<int, int>> faulted;
2661 bool unjoined = false;
2662 for (const auto &[tile, conn] : faults.connections) {
2663 illegalEdges++;
2664 auto it = graph.find(crossbarKey(tile));
2665 if (it == graph.end())
2666 continue;
2667 SwitchboxConnect &sb = it->second;
2668 int i = sb.srcIndex(conn.src);
2669 int j = sb.dstIndex(conn.dst);
2670 if (i < 0 || j < 0)
2671 continue;
2672 sb.at(i, j).overCapacity += routingCheckPenalty;
2673 auto takes = [&](const Edge &e) {
2674 return e.sb == &sb && e.i == i && e.j == j;
2675 };
2676 bool taken = false, pinnedTakesAll = true;
2677 for (auto [k, part] : llvm::enumerate(st.parts))
2678 if (llvm::any_of(st.circuitHops[k], takes) ||
2679 llvm::any_of(st.treeOf[k], [&](const auto &hop) {
2680 return takes(hop.second.second);
2681 })) {
2682 taken = true;
2683 pinnedTakesAll &= st.isPinned(part);
2684 }
2685 pinnedOnly += taken && pinnedTakesAll;
2686 bool joined = false;
2687 for (auto [flow, hops] : llvm::enumerate(st.joinedHops))
2688 for (const auto &[other, e] : hops)
2689 if (e.sb == &sb && sb.srcPorts[e.i] == conn.src &&
2690 sb.dstPorts[e.j] == conn.dst) {
2691 faulted.insert({static_cast<int>(flow), other});
2692 joined = true;
2693 }
2694 unjoined |= !joined;
2695 }
2696 // Moving the hops neither joined may be enough, so a joined pair is first
2697 // left to their penalties.
2698 for (auto [flow, other] : faulted)
2699 if (unjoined && st.spared.insert({flow, other}).second)
2700 continue;
2701 else if (st.met.count({flow, other}) &&
2702 ++st.meetFaults[{std::min(flow, other), std::max(flow, other)}] <=
2703 maxMeetFaults)
2704 st.reorder(flow, other, /*again=*/true);
2705 else
2706 st.lessons += st.noJoin.insert({flow, other}).second;
2707 return illegalEdges;
2708}
2709
2710// Perform congestion-aware routing for all flows which have been added.
2711// Use Dijkstra's shortest path to find routes, and use "demand" as the
2712// weights. If the routing finds too much congestion, update the demand
2713// weights and repeat the process until a valid solution is found. Returns
2714// the switchbox settings for all flows, or a RoutingFailure if no legal
2715// routing is found after maxIterations.
2716llvm::Expected<Routing> Pathfinder::findPaths(const int maxIterations) {
2717 LLVM_DEBUG(llvm::dbgs() << "\t---Begin Pathfinder::findPaths---\n");
2718 checkReason.clear();
2719 packetsFailed = true;
2720 // Build the dense routing graph once; topology is invariant across
2721 // iterations.
2722 if (!graphBuilt)
2723 buildRoutingGraph();
2724 if (llvm::Error err = cutOverflow()) {
2725 packetsFailed = false;
2726 return std::move(err);
2727 }
2728 crowdedTiles.clear();
2729 consulted = Relax::None;
2730 // initialize all Channel histories to 0
2731 for (auto &[_, sb] : graph) {
2732 if (sb.isCrossbar)
2733 for (auto [j, port] : llvm::enumerate(sb.dstPorts))
2734 sb.circuitOnlyDst[j] = cappedTiles.contains(sb.srcCoords) &&
2735 port.channel >= packetFanoutCap &&
2736 getLinkedInput(sb.dstCoords, port).has_value();
2737 for (SwitchboxConnect::Cell &c : sb.cells) {
2738 c.usedCapacity = 0;
2739 c.overCapacity = 0;
2740 c.isPriority = false;
2741 }
2742 }
2743 if (!attempts)
2744 return negotiate(maxIterations, nullptr);
2745
2746 // Of what a relax step changes, an attempt reads the flows as sortFlows
2747 // left them, the circuit-only ports, and the settings it consults while it
2748 // routes. One that reads all of these as an earlier attempt did, the
2749 // settings only where that one consulted them, routes as it did: the two
2750 // run alike up to the first read that differs, which the earlier one made.
2752 now.flows = flows;
2753 for (const auto &[_, sb] : graph)
2754 now.circuitOnly.push_back(sb.circuitOnlyDst);
2755 now.values = settings;
2756 auto sameFlow = [](const Flow &a, const Flow &b) {
2757 return std::tie(a.packetGroupId, a.isPriorityFlow, a.src, a.dsts,
2758 a.packetId) == std::tie(b.packetGroupId, b.isPriorityFlow,
2759 b.src, b.dsts, b.packetId);
2760 };
2761 auto replays = [&](const PathfinderAttempt &a) {
2762 return llvm::equal(a.flows, now.flows, sameFlow) &&
2763 a.circuitOnly == now.circuitOnly &&
2764 !any((a.values ^ settings) & a.consulted);
2765 };
2766 auto replayed = llvm::find_if(*attempts, replays);
2767 if (replayed != attempts->end() && !clVerifyReplays) {
2768 LLVM_DEBUG(llvm::dbgs() << "\tPathfinder: this attempt replays attempt "
2769 << (replayed - attempts->begin())
2770 << " of the ladder, so it is skipped\n");
2771 ++numReplaysSkipped;
2772 crowdedTiles = replayed->crowdedTiles;
2773 packetsFailed = replayed->packetsFailed;
2774 checkReason = replayed->checkReason;
2775 if (replayed->routing)
2776 return *replayed->routing;
2777 return llvm::Error(replayed->prototype->clone(
2778 replayed->reason, replayed->faults, replayed->loc));
2779 }
2780
2781 llvm::Expected<Routing> found =
2782 negotiate(maxIterations, clVerifyReplays ? &now.trajectory : nullptr);
2783 now.consulted = consulted;
2784 now.crowdedTiles = crowdedTiles;
2785 now.packetsFailed = packetsFailed;
2786 now.checkReason = checkReason;
2787 bool replayable = static_cast<bool>(found);
2788 if (found)
2789 now.routing = *found;
2790 llvm::Error failure =
2791 found ? llvm::Error::success()
2792 : llvm::handleErrors(
2793 found.takeError(),
2794 [&](std::unique_ptr<RoutingFailure> f) -> llvm::Error {
2795 // Reaching this handler already means f is a
2796 // RoutingFailure or a registered subclass of it.
2797 replayable = true;
2798 now.reason = f->reason;
2799 now.faults = f->faults;
2800 now.loc = f->loc;
2801 now.prototype = f->clone(f->reason, f->faults, f->loc);
2802 return llvm::Error(std::move(f));
2803 });
2804 if (replayed != attempts->end()) {
2805 bool sameFailureType =
2806 static_cast<bool>(replayed->prototype) ==
2807 static_cast<bool>(now.prototype) &&
2808 (!now.prototype || replayed->prototype->dynamicClassID() ==
2809 now.prototype->dynamicClassID());
2810 bool same = replayed->trajectory == now.trajectory &&
2811 replayed->routing.has_value() == now.routing.has_value() &&
2812 (!now.routing || hashRouting(*replayed->routing) ==
2813 hashRouting(*now.routing)) &&
2814 sameFailureType && replayed->reason == now.reason &&
2815 replayed->crowdedTiles == now.crowdedTiles &&
2816 replayed->packetsFailed == now.packetsFailed &&
2817 replayed->checkReason == now.checkReason;
2818 if (!same)
2819 llvm::report_fatal_error(llvm::Twine("aie-pathfinder-verify-replays: "
2820 "attempt ") +
2821 llvm::Twine(attempts->size()) +
2822 " does not replay attempt " +
2823 llvm::Twine(replayed - attempts->begin()));
2824 LLVM_DEBUG(llvm::dbgs() << "\tPathfinder: this attempt replays attempt "
2825 << (replayed - attempts->begin())
2826 << " of the ladder, as verified\n");
2827 ++numReplaysVerified;
2828 } else if (replayable) {
2829 attempts->push_back(std::move(now));
2830 }
2831 if (failure)
2832 return std::move(failure);
2833 return found;
2834}
2835
2836llvm::Expected<Routing>
2837Pathfinder::negotiate(const int maxIterations,
2838 std::vector<llvm::hash_code> *trajectory) {
2839 RouteState st(*this);
2840
2841 int iterationCount = -1;
2842 int illegalEdges = 0;
2843 std::optional<Routing> usable;
2844 int usableAt = 0;
2845 int fewestIllegal = std::numeric_limits<int>::max(), sinceFewest = 0;
2846 // Iterations of the current stall that moved circuit trees first.
2847 int reorderedStall = 0;
2848 int priorityFaults = 0;
2849 // Once a routing has fit the fabric, the iterations since the routing check
2850 // last named fewer faults or taught a lesson, overused ones included.
2851 int fewestRejected = std::numeric_limits<int>::max(), sinceFewestRejected = 0;
2852 do {
2853 if (usable && (iterationCount + 1 >= maxIterations ||
2854 iterationCount - usableAt >= maxSteers)) {
2855 LLVM_DEBUG(llvm::dbgs() << "\t\tKeeping the usable routing\n");
2856 return std::move(*usable);
2857 }
2858 // if reach maxIterations, throw an error since no routing can be found;
2859 // so too once the overuse stalls for good, or routing the losing circuit
2860 // trees first has stopped helping
2861 if (++iterationCount >= maxIterations ||
2862 (fewestIllegal > 0 && sinceFewest >= maxOverusedStall) ||
2863 reorderedStall >= maxReorderedStall ||
2864 sinceFewestRejected >= maxRejectedStall) {
2865 LLVM_DEBUG(llvm::dbgs()
2866 << "\t\tPathfinder: giving up after " << iterationCount
2867 << " iterations ("
2868 << (iterationCount >= maxIterations ? "the iteration limit"
2869 : reorderedStall >= maxReorderedStall
2870 ? "circuit trees routed first stopped helping"
2871 : sinceFewestRejected >= maxRejectedStall
2872 ? "the routing check stopped making progress"
2873 : "the overuse stalled")
2874 << ")...unable to find routing for flows.\n");
2875 // Packet streams took part if they share a switchbox or link with an
2876 // overused channel, or cross a boundary one does: a channel they take
2877 // across it is one fewer for the rest.
2878 auto overused = [](const SwitchboxConnect::Cell &c) {
2879 return c.usedCapacity > maxCircuitStreamCapacity;
2880 };
2881 auto packets = [](const SwitchboxConnect::Cell &c) {
2882 return c.packetGroupId >= 0;
2883 };
2884 std::set<std::tuple<bool, int, bool>> full;
2885 for (const auto &[_, sb] : graph)
2886 if (!sb.isCrossbar && llvm::any_of(sb.cells, overused))
2887 full.insert(boundaryOf(sb.srcCoords, sb.dstCoords));
2888 packetsFailed =
2889 !checkReason.empty() || llvm::any_of(graph, [&](const auto &entry) {
2890 const SwitchboxConnect &sb = entry.second;
2891 return llvm::any_of(sb.cells, packets) &&
2892 (llvm::any_of(sb.cells, overused) ||
2893 (!sb.isCrossbar &&
2894 full.count(boundaryOf(sb.srcCoords, sb.dstCoords))));
2895 });
2896 return explainNoRouting(st);
2897 }
2898
2899 LLVM_DEBUG(llvm::dbgs() << "\t\t---Begin findPaths iteration #"
2900 << iterationCount << "---\n");
2901 // update demand at the beginning of each iteration
2902 for (auto &[_, sb] : graph) {
2903 sb.updateDemand();
2904 }
2905
2906 // "rip up" all routes
2907 illegalEdges = 0;
2908 st.routing = {};
2909 for (auto &[_, sb] : graph) {
2910 for (SwitchboxConnect::Cell &c : sb.cells) {
2911 c.usedCapacity = 0;
2912 c.packetFlowCount = 0;
2913 c.packetGroupId = -1;
2914 c.packetIds.clear();
2915 }
2916 sb.resetUnits();
2917 }
2918 for (auto &tree : st.treeOf)
2919 tree.clear();
2920 for (auto &hops : st.circuitHops)
2921 hops.clear();
2922 for (auto &dsts : st.treeDsts)
2923 dsts.clear();
2924 for (auto &hops : st.joinedHops)
2925 hops.clear();
2926 st.unmet.clear();
2927 st.met.clear();
2928 st.meetingPorts.clear();
2929
2930 // for each flow, find the shortest path from source to destination
2931 // update used_capacity for the path between them
2932
2933 for (const auto &[_, group] : st.groupedFlows) {
2934 for (int flow : group)
2935 if (llvm::Error err = routePart(st, flow))
2936 return std::move(err);
2937 for (auto &[_, sb] : graph) {
2938 for (size_t i = 0; i < sb.srcPorts.size(); i++)
2939 for (size_t j = 0; j < sb.dstPorts.size(); j++) {
2940 SwitchboxConnect::Cell &c = sb.at(i, j);
2941 // fix used capacity for packet flows
2942 if (c.packetFlowCount > 0) {
2943 c.packetFlowCount = 0;
2944 c.usedCapacity++;
2945 }
2946 sb.bumpDemand(i, j);
2947 }
2948 }
2949 }
2950
2951 // The tree routed first may branch where none from elsewhere can meet it
2952 // at one switchbox, though it could meet a tree routed before it, or one
2953 // that leaves its source switchbox by one master port for them.
2954 for (auto [later, earlier] : st.unmet) {
2955 bool steered = st.reorder(later, earlier);
2956 steered |= st.trunked.insert({later, earlier}).second;
2957 steered |= st.trunked.insert({earlier, later}).second;
2958 if (steered)
2959 illegalEdges++;
2960 }
2961 bool split = false;
2962 for (const auto &pair : st.meetBlocked)
2963 if (st.togetherSources.insert(pair).second) {
2964 LLVM_DEBUG(llvm::dbgs()
2965 << "Route together to meet: "
2966 << describeTilePort(pair.first.coords, pair.first.port)
2967 << " and "
2968 << describeTilePort(pair.second.coords, pair.second.port)
2969 << "\n");
2970 st.splitOwnIds(pair);
2971 // Trunks steered them to where they could not meet; split, they can.
2972 for (int a : st.partsOf.at(pair.first))
2973 for (int b : st.partsOf.at(pair.second)) {
2974 st.trunked.erase({a, b});
2975 st.trunked.erase({b, a});
2976 }
2977 split = true;
2978 }
2979 st.meetBlocked.clear();
2980 for (const auto &[pair, ids] : st.meetSplits)
2981 for (int k : SmallVector<int, 2>(st.partsOf.at(pair.first)))
2982 if (!st.parts[k].isPriorityFlow && ids.size() < st.flowIds[k].size() &&
2983 llvm::all_of(ids,
2984 [&](int id) { return st.flowIds[k].count(id); })) {
2985 LLVM_DEBUG(llvm::dbgs()
2986 << "Route apart to meet: "
2987 << describeTilePort(pair.first.coords, pair.first.port)
2988 << " and "
2989 << describeTilePort(pair.second.coords, pair.second.port)
2990 << "\n");
2991 st.splitPart(k, ids);
2992 for (int a : st.partsOf.at(pair.first))
2993 for (int b : st.partsOf.at(pair.second)) {
2994 st.trunked.erase({a, b});
2995 st.trunked.erase({b, a});
2996 }
2997 split = true;
2998 }
2999 st.meetSplits.clear();
3000 if (split) {
3001 st.relateParts();
3002 illegalEdges++;
3003 }
3004
3005 for (auto &[_, sb] : graph) {
3006 for (size_t i = 0; i < sb.srcPorts.size(); i++) {
3007 for (size_t j = 0; j < sb.dstPorts.size(); j++) {
3008 SwitchboxConnect::Cell &c = sb.at(i, j);
3009 // check that every channel does not exceed max capacity
3010 if (c.usedCapacity > maxCircuitStreamCapacity) {
3011 c.overCapacity +=
3012 sinceFewest >= stallIterations && c.packetGroupId < 0
3013 ? stallHistory
3014 : 1;
3015 illegalEdges++;
3016 LLVM_DEBUG(llvm::dbgs()
3017 << "\t\t\tToo much capacity on (" << sb.srcCoords.col
3018 << "," << sb.srcCoords.row << ") "
3019 << sb.srcPorts[i].bundle << sb.srcPorts[i].channel
3020 << " -> (" << sb.dstCoords.col << "," << sb.dstCoords.row
3021 << ") " << sb.dstPorts[j].bundle
3022 << sb.dstPorts[j].channel << ", used_capacity = "
3023 << c.usedCapacity << ", demand = " << c.demand
3024 << ", over_capacity_count = " << c.overCapacity << "\n");
3025 }
3026 }
3027 }
3028 }
3029 // Once the overuse stalls, circuit trees that overuse a circuit-only
3030 // channel route first, so the same tree stops losing it. Packet-shared
3031 // overuse is left to the packet steering.
3032 if (illegalEdges < fewestIllegal) {
3033 fewestIllegal = illegalEdges;
3034 sinceFewest = reorderedStall = 0;
3035 } else {
3036 sinceFewest++;
3037 }
3038 // Overuse after a fit is out of reach of maxOverusedStall, which needs the
3039 // attempt never to have fit, so it stalls the routing check's count.
3040 if (fewestIllegal == 0 && illegalEdges > 0) {
3041 sinceFewestRejected++;
3042 LLVM_DEBUG(llvm::dbgs()
3043 << "Rejected-routing stall " << sinceFewestRejected << '\n');
3044 }
3045 if (illegalEdges && sinceFewest >= stallIterations) {
3046 auto losing = [&](int flow) {
3047 return !st.parts[flow].packetId &&
3048 llvm::any_of(st.circuitHops[flow], [](const Edge &e) {
3049 const SwitchboxConnect::Cell &c = e.sb->at(e.i, e.j);
3050 return c.usedCapacity > maxCircuitStreamCapacity &&
3051 c.packetGroupId < 0;
3052 });
3053 };
3054 bool moved = false;
3055 for (auto &[_, group] : st.groupedFlows) {
3056 moved |= llvm::any_of(group, losing);
3057 std::stable_partition(group.begin(), group.end(), losing);
3058 }
3059 reorderedStall += moved;
3060 }
3061 // Each stall period without a legal routing, the packet trees drop their
3062 // id splits: the routing that faulted them may be gone, and the routing
3063 // check adds back any still needed.
3064 if (sinceFewest >= stallIterations && sinceFewest % stallIterations == 0) {
3065 LLVM_DEBUG(llvm::dbgs() << "Drop the id splits after " << sinceFewest
3066 << " stalled iterations\n");
3067 for (auto &splits : st.splitsOf)
3068 splits.clear();
3069 }
3070
3071 // A routing that fits the fabric can still be one the caller cannot use;
3072 // steer away from the connections it names as if they were overused. One
3073 // it rejects naming nothing to move is as far as steering gets, leaving
3074 // the usable routing found, if any, or the rejection.
3075 bool stuck = false;
3076 llvm::Error unmoved =
3077 illegalEdges != 0 || !constraints.check
3078 ? llvm::Error::success()
3079 : llvm::handleErrors(
3080 constraints.check(st.routing),
3081 [&](std::unique_ptr<RoutingFailure> rejected) -> llvm::Error {
3082 LLVM_DEBUG(llvm::dbgs() << "Routing rejected: "
3083 << rejected->reason << '\n');
3084 int lessons = st.lessons, pinnedOnly = 0;
3085 int faulted =
3086 applyRoutingFaults(st, rejected->faults, pinnedOnly);
3087 illegalEdges += faulted;
3088 if (illegalEdges < fewestRejected || st.lessons > lessons) {
3089 fewestRejected = std::min(fewestRejected, illegalEdges);
3090 sinceFewestRejected = 0;
3091 } else {
3092 sinceFewestRejected++;
3093 }
3094 LLVM_DEBUG(llvm::dbgs() << "Rejected-routing stall "
3095 << sinceFewestRejected << '\n');
3096 priorityFaults = rejected->faults.onlyPriorityMasters
3097 ? priorityFaults + 1
3098 : 0;
3099 // Penalties on connections only pinned trees take move
3100 // nothing, so such faults are as stuck as none.
3101 stuck = faulted == pinnedOnly && st.lessons == lessons;
3102 LLVM_DEBUG(
3103 if (stuck && pinnedOnly) llvm::dbgs()
3104 << "\t\tPathfinder: the routing check names only "
3105 "connections pinned trees take ("
3106 << pinnedOnly << ") after " << iterationCount
3107 << " iterations\n");
3108 if (rejected->isA(DeadlockProneRouting::classID())) {
3109 if (!usable) {
3110 usable = st.routing;
3111 usableAt = iterationCount;
3112 }
3113 return llvm::Error::success();
3114 }
3115 if (stuck)
3116 return llvm::Error(std::move(rejected));
3117 checkReason = std::move(rejected->reason);
3118 return llvm::Error::success();
3119 });
3120
3121 LLVM_DEBUG({
3122 for (const auto &[src, settings] : st.routing.settings)
3123 llvm::dbgs() << "\t\t\tFlow starting at (" << src.coords.col << ","
3124 << src.coords.row << "):\t" << settings;
3125 // total path length, across switchboxes
3126 int totalPathLength = 0;
3127 for (const auto &[_, sb] : graph)
3128 if (!sb.isCrossbar)
3129 for (const SwitchboxConnect::Cell &c : sb.cells)
3130 totalPathLength += c.usedCapacity;
3131 llvm::dbgs() << "\t\t---End findPaths iteration #" << iterationCount
3132 << " , illegal edges count = " << illegalEdges
3133 << ", total path length = " << totalPathLength << "---\n";
3134 });
3135 if (trajectory)
3136 trajectory->push_back(hashRouting(st.routing));
3137 if (stuck && usable) {
3138 llvm::consumeError(std::move(unmoved));
3139 return std::move(*usable);
3140 }
3141 if (unmoved)
3142 return std::move(unmoved);
3143 if (priorityFaults >= maxPriorityFaults) {
3144 LLVM_DEBUG(llvm::dbgs() << "\t\tPathfinder: the routing check rejects "
3145 "only master sets of the prioritized flows ("
3146 << priorityFaults << " routings in a row)\n");
3147 if (usable)
3148 return std::move(*usable);
3149 packetsFailed = false;
3150 return explainNoRouting(st);
3151 }
3152 // continue iterations until a legal routing is found
3153 } while (illegalEdges > 0);
3154
3155 LLVM_DEBUG(llvm::dbgs() << "\t---End Pathfinder::findPaths---\n");
3156 return std::move(st.routing);
3157}
STATISTIC(numReplaysSkipped, "Attempts skipped as replays of an earlier one")
virtual uint32_t getNumSourceShimMuxConnections(int col, int row, WireBundle bundle) const =0
Return the number of sources of connections inside a shimmux.
virtual bool isLegalTileConnection(int col, int row, WireBundle srcBundle, int srcChan, WireBundle dstBundle, int dstChan) const =0
virtual uint32_t getNumDestShimMuxConnections(int col, int row, WireBundle bundle) const =0
Return the number of destinations of connections inside a shimmux.
virtual uint32_t getNumDestSwitchboxConnections(int col, int row, WireBundle bundle) const =0
Return the number of destinations of connections inside a switchbox.
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 ...
virtual uint32_t getNumSourceSwitchboxConnections(int col, int row, WireBundle bundle) const =0
Return the number of sources of connections inside a switchbox.
ShimMuxOp getShimMux(mlir::OpBuilder &builder, int col)
SwitchboxOp getSwitchbox(mlir::OpBuilder &builder, int col, int row)
SwitchboxOp lookupSwitchbox(TileID tile) const
TileOp getTile(mlir::OpBuilder &builder, int col, int row)
llvm::Error runAnalysis(DeviceOp &device)
ShimMuxOp lookupShimMux(int col) const
std::vector< std::pair< TileID, Port > > avoidedPorts
void avoidPort(TileID coords, Port port)
std::vector< PathfinderAttempt > * attempts
llvm::Expected< Routing > findPaths(int maxIterations)
void excludeTile(TileID coords)
void addFlow(TileID srcCoords, Port srcPort, TileID dstCoords, Port dstPort, std::optional< int > packetId, bool isPriorityFlow, std::optional< mlir::Location > loc=std::nullopt)
void initialize(int maxCol, int maxRow, const AIETargetModel &targetModel)
mlir::LogicalResult addFixedConnection(SwitchboxOp switchboxOp)
void log(llvm::raw_ostream &os) const override
std::string joinNames(llvm::ArrayRef< std::string > names, size_t shown=4)
Lists names as "A, B and C", the first shown of them followed by "N more" if there are more.
int shimMuxChannelTo(Port dst)
std::string describePrioritized(llvm::ArrayRef< std::string > sources)
Says that the packet flows from sources keep the route they take alone, as a control-packet reload of...
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
std::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)
std::tuple< bool, int, bool > boundaryOf(TileID a, TileID b)
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
constexpr llvm::StringLiteral kNoLegalRouting
std::string describePort(Port port)
Names a port the way diagnostics do, e.g. "DMA:1".
WireBundle getConnectingBundle(WireBundle dir)
bool operator<(const IdSplit &other) const
std::vector< SmallVector< int, 4 > > prioritySets
std::set< std::pair< int, int > > noJoin
std::vector< llvm::DenseMap< int, std::pair< int, Edge > > > treeOf
std::map< std::pair< int, int >, int > meetFaults
void splitOwnIds(const std::pair< PathEndPoint, PathEndPoint > &pair)
std::vector< SmallVector< Edge, 8 > > circuitHops
std::set< std::pair< int, int > > reordered
std::vector< std::set< std::pair< TileID, int > > > partSplits
std::vector< uint32_t > processedStamp
std::vector< SmallVector< std::pair< int, Edge >, 8 > > joinedHops
std::set< std::pair< std::pair< PathEndPoint, PathEndPoint >, std::set< int > > > meetSplits
std::set< std::pair< int, int > > spared
std::vector< llvm::BitVector > conflicting
std::vector< SmallVector< int, 4 > > treeDsts
std::vector< std::set< IdSplit > > splitsOf
std::set< std::pair< int, int > > met
std::set< std::pair< PathEndPoint, PathEndPoint > > togetherSources
std::set< std::pair< PathEndPoint, PathEndPoint > > meetBlocked
bool reorder(int later, int earlier, bool again=false)
std::vector< std::set< int > > flowIds
llvm::MapVector< int, SmallVector< int, 8 > > groupedFlows
bool isPinned(const Flow &f) const
std::set< std::pair< PathEndPoint, PathEndPoint > > apartSources
std::set< std::pair< int, int > > unmet
std::map< std::pair< int, int >, PathEndPoint > meetingPorts
std::set< std::pair< int, IdSplit > > splitsTaught
bool mayLeave(ArrayRef< int > masters, int next) const
std::set< std::pair< int, int > > trunked
int splitPart(int flow, const std::set< int > &ids)
std::vector< SmallVector< int, 4 > > sameId
SmallVector< int, 4 > idsTo(int flow, int dstState) const
std::map< PathEndPoint, SmallVector< int, 2 > > partsOf
TreeBuilder(Pathfinder &pf, RouteState &st, int flow)
llvm::MapVector< int, SmallVector< int, 4 > > sharedDsts
SmallVector< PathEndPoint, 4 > pending
llvm::DenseSet< int > trunkOff(int dst) const
llvm::MapVector< int, SmallVector< int, 4 > > blockedDsts
void search(const llvm::DenseSet< int > &drop, ArrayRef< int > targets, const llvm::DenseSet< int > &off={})
const std::vector< TreeHop > * pinned
SmallVector< double, 16 > seedCosts
std::optional< PathEndPoint > first
SmallVector< std::pair< int, std::pair< int, Edge > >, 8 > pinnedJoins
int dstState(const PathEndPoint &p) const
llvm::MapVector< int, std::pair< int, Edge > > planned
llvm::DenseMap< int, SmallVector< int, 2 > > joinOwners
llvm::DenseMap< int, llvm::BitVector > branchAvoid
bool joinable(int at, ArrayRef< int > dsts) const
llvm::MapVector< int, std::pair< SmallVector< int, 4 >, std::set< int > > > blockedIds
SmallVector< std::pair< int, const SmallVector< int, 4 > * >, 2 > joinedAt
bool join(int state, int predId, const Edge &e)
llvm::DenseSet< int > splitOff(int dst) const
llvm::DenseMap< int, SmallVector< int, 4 > > joins
llvm::DenseMap< int, int > children
std::vector< PathEndPoint > dsts
std::optional< int > packetId
std::vector< std::string > flows
std::vector< llvm::BitVector > circuitOnly
std::vector< llvm::hash_code > trajectory
std::unique_ptr< RoutingFailure > prototype
llvm::DenseSet< TileID > crowdedTiles
std::optional< Routing > routing
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
std::vector< Port > dsts
std::vector< Port > srcs
llvm::SmallDenseMap< int, int, 2 > packetIds
std::vector< Port > dstPorts
std::vector< Port > srcPorts
void addToUnit(int j, int flow)
Cell & at(size_t i, size_t j)
void bumpDemand(size_t i, size_t j)
std::vector< Cell > cells
std::optional< PathEndPoint > apart