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"
29#define DEBUG_TYPE "aie-pathfinder"
31STATISTIC(numReplaysSkipped,
"Attempts skipped as replays of an earlier one");
32STATISTIC(numReplaysVerified,
"Attempts routed and verified to replay one");
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));
41static llvm::hash_code hashRouting(
const Routing &routing) {
42 llvm::hash_code h = llvm::hash_value(routing.
settings.size());
44 for (
const auto &[tile, s] : ss) {
45 h = llvm::hash_combine(h, tile.col, tile.row, s.srcs.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);
54 h = llvm::hash_combine(h, e.coords.col, e.coords.row, e.port.bundle,
57 for (
const auto &[src, ss] : routing.
settings) {
61 for (
const auto &[key, ss] : routing.
idSettings) {
63 h = llvm::hash_combine(h, key.second);
66 for (
const auto &[src, hops] : routing.
packetTrees) {
68 for (
const TreeHop &hop : hops) {
71 h = llvm::hash_combine(h, hop.joined, hop.isCrossbar);
81constexpr double overCapacityCoeff = 0.1;
82constexpr double usedCapacityCoeff = 0.02;
83constexpr double demandBase = 1.0;
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;
93constexpr double avoidedPortDemand = 100.0;
95constexpr int routingCheckPenalty = 5;
97constexpr int maxSteers = 16;
101constexpr int maxPriorityFaults = 16;
104constexpr int maxMeetFaults = 4;
106constexpr double conflictSharePenalty = 4;
110constexpr int packetFanoutCap = 2;
115constexpr double treeSeedFactor = 0.9;
117constexpr double rerouteMinSaving = 1e-6;
120constexpr int stallIterations = 50;
123constexpr int maxReorderedStall = 300;
127constexpr int maxOverusedStall = 400;
131constexpr int maxRejectedStall = 600;
134constexpr int stallHistory = 4;
139 c.demand = (demandBase + overCapacityCoeff * c.overCapacity) *
140 (demandBase + usedCapacityCoeff * c.usedCapacity) +
161 LLVM_DEBUG(llvm::dbgs() <<
"\t---Begin DynamicTileAnalysis Constructor---\n");
163 maxCol = device.getTargetModel().columns();
164 maxRow = device.getTargetModel().rows();
166 pathfinder.initialize(maxCol, maxRow, device.getTargetModel());
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;
179 for (Operation &Op : b.getOperations()) {
180 if (
auto pktSource = dyn_cast<PacketSourceOp>(Op)) {
181 auto srcTile = cast<TileOp>(pktSource.getTile().getDefiningOp());
183 {{srcTile.colIndex(), srcTile.rowIndex()}, pktSource.port()});
187 bool priorityFlow = pktFlowOp.getPriorityRoute().value_or(
false);
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
203 pathfinder.addFlow(srcCoords, srcPort, dstCoords, dstPort,
204 pktFlowOp.IDInt(), priorityFlow,
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
225 pathfinder.addFlow(srcCoords, srcPort, dstCoords, dstPort,
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()),
247 llvm::Expected<Routing> found =
pathfinder.findPaths(maxIterations);
249 return found.takeError();
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;
261 for (
auto switchboxOp : device.getOps<SwitchboxOp>()) {
262 [[maybe_unused]]
bool fresh =
264 .try_emplace({switchboxOp.colIndex(), switchboxOp.rowIndex()},
269 for (
auto shimmuxOp : device.getOps<ShimMuxOp>()) {
270 [[maybe_unused]]
bool fresh =
272 .try_emplace({shimmuxOp.colIndex(), shimmuxOp.rowIndex()},
278 LLVM_DEBUG(llvm::dbgs() <<
"\t---End DynamicTileAnalysis Constructor---\n");
279 return llvm::Error::success();
283 TileOp &tileOp = coordToTile[{col, row}];
285 tileOp = TileOp::create(
287 cast<DeviceOp>(builder.getInsertionBlock()->getParentOp()).getLoc(),
293 return getTile(builder, tileId.col, tileId.row);
302 auto tileOp =
getTile(builder, col, row);
303 auto switchboxOp = SwitchboxOp::create(builder, tileOp.getLoc(), tileOp);
304 SwitchboxOp::ensureTerminator(switchboxOp.getConnections(), builder,
306 coordToSwitchbox[{col, row}] = switchboxOp;
314 auto tileOp =
getTile(builder, col, 0);
316 auto shimMuxOp = ShimMuxOp::create(builder, tileOp.getLoc(), tileOp);
317 ShimMuxOp::ensureTerminator(shimMuxOp.getConnections(), builder,
319 coordToShimMux[{col, 0}] = shimMuxOp;
341 wireEdgesBegin.clear();
348 std::map<WireBundle, int> maxChannels;
349 auto intraconnect = [&](
int col,
int row) {
350 TileID coords = {col, row};
352 graph.try_emplace(crossbarKey(coords), coords).first->second;
354 for (
int i = 0, e = getMaxEnumValForWireBundle() + 1; i < e; ++i) {
355 WireBundle bundle = symbolizeWireBundle(i).value();
359 if (channels == 0 && targetModel.
hasShimMux(col, row)) {
363 for (
int channel = 0; channel < channels; channel++) {
368 if (channels == 0 && targetModel.
hasShimMux(col, row)) {
372 for (
int channel = 0; channel < channels; channel++) {
375 maxChannels[bundle] = channels;
379 auto isMuxed = [&](
Port p) {
382 {WireBundle::DMA, WireBundle::NOC, WireBundle::PLIO},
385 for (
auto [i, pIn] : llvm::enumerate(sb.
srcPorts))
386 for (
auto [j, pOut] : llvm::enumerate(sb.
dstPorts))
389 pOut.bundle, pOut.channel) ||
390 isMuxed(pIn) || isMuxed(pOut);
393 auto interconnect = [&](
int col,
int row,
int targetCol,
int targetRow,
394 WireBundle srcBundle, WireBundle dstBundle) {
395 TileID src = {col, row}, dst = {targetCol, targetRow};
397 graph.try_emplace(wireKey(src, dst), src, dst).first->second;
399 for (
int channel = 0; channel < maxChannels[srcBundle]; channel++) {
404 for (
size_t i = 0; i < sb.
srcPorts.size(); i++)
408 for (
int row = 0; row <= maxRow; row++) {
409 for (
int col = 0; col <= maxCol; col++) {
412 intraconnect(col, row);
417 interconnect(col, row, col, row - 1, WireBundle::South,
422 interconnect(col, row, col, row + 1, WireBundle::North,
427 interconnect(col, row, col - 1, row, WireBundle::West,
432 interconnect(col, row, col + 1, row, WireBundle::East,
442 Port dstPort, std::optional<int> packetId,
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);
450 isPriorityFlow &= constraints.prioritize;
452 flowLocs[{srcCoords, srcPort}].try_emplace({dstCoords, dstPort}, *loc);
454 auto &ids = packetIdsTo[{{srcCoords, srcPort}, {dstCoords, dstPort}}];
455 if (!llvm::is_contained(ids, *packetId))
456 ids.push_back(*packetId);
458 priorityIds[{srcCoords, srcPort}].insert(*packetId);
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()) {
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);
471 flow->dsts.push_back(dst);
477std::optional<mlir::Location>
479 auto locs = flowLocs.find(src);
480 if (locs == flowLocs.end())
482 auto it = dst ? locs->second.find(*dst) : locs->second.begin();
483 if (it == locs->second.end())
488bool Pathfinder::shareAllChannels() {
489 shareChannels =
true;
493bool Pathfinder::capCrowdedFanOut() {
494 size_t capped = cappedTiles.size();
495 cappedTiles.insert(crowdedTiles.begin(), crowdedTiles.end());
496 return cappedTiles.size() > capped;
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());
506bool Pathfinder::routeIdsApart() {
510 shareChannels =
false;
512 return llvm::any_of(idsBySource(),
513 [](
const auto &s) {
return s.second.size() > 1; });
516bool Pathfinder::splitSharedIds() {
520 shareChannels =
false;
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); }))
536bool Pathfinder::stopMeeting() {
541 shareChannels =
false;
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());
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))
560 if (++shared[
id] > 1)
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))
571 std::vector<SmallVector<PathEndPoint, 4>> members(clusters.getNumClasses());
572 for (
auto [i, src] : llvm::enumerate(srcs))
573 members[clusters[i]].push_back(src);
577 for (
const auto &cluster : members)
578 if (leadStep < cluster.size())
579 leads.insert(cluster[leadStep]);
580 return !leads.empty();
587bool Pathfinder::meetAhead() {
595enum class RelaxStep {
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;
617 if (!packetsFailed) {
618 LLVM_DEBUG(llvm::dbgs() <<
"No packet stream crosses an overused link\n");
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");
629 case RelaxStep::CapCrowdedTiles:
630 if (capCrowdedFanOut()) {
631 LLVM_DEBUG(llvm::dbgs() <<
"Relax: cap crowded tiles\n");
635 case RelaxStep::RouteIdsApart:
636 if (routeIdsApart()) {
637 LLVM_DEBUG(llvm::dbgs() <<
"Relax: route ids apart\n");
642 relaxStep = rotateLeadsStep;
644 case RelaxStep::SplitSharedIds:
645 if (splitSharedIds()) {
646 LLVM_DEBUG(llvm::dbgs() <<
"Relax: split shared ids\n");
649 relaxStep = rotateLeadsStep;
651 case RelaxStep::RotateLeads:
656 LLVM_DEBUG(llvm::dbgs()
657 <<
"Relax: route cluster member " << leadStep <<
" first\n");
661 case RelaxStep::MeetAhead:
663 LLVM_DEBUG(llvm::dbgs() <<
"Relax: meet ahead of same-id partners\n");
667 case RelaxStep::StopMeeting:
669 LLVM_DEBUG(llvm::dbgs() <<
"Relax: stop meeting\n");
681 for (
auto &flow : flows)
682 llvm::sort(flow.dsts);
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)
692 auto [it, fresh] = firstTo.try_emplace(dst, k);
694 groups.join(k, it->second);
697 llvm::DenseMap<unsigned, int> groupOf;
698 for (
auto [k, flow] : llvm::enumerate(flows))
699 if (flow.packetGroupId >= 0)
703 : groupOf.try_emplace(groups.findLeader(k), groupOf.size())
706 auto flowRank = [](
const Flow &flow) {
707 if (flow.isPriorityFlow)
709 if (flow.packetGroupId >= 0)
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);
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;
730 if (dst.bundle == WireBundle::DMA)
731 return dst.channel == 0 ? 2 : 3;
732 if (dst.bundle == WireBundle::NOC)
733 return dst.channel + 2;
738 int col = switchboxOp.colIndex();
739 int row = switchboxOp.rowIndex();
740 TileID coords = {col, row};
741 auto &sb = graph[crossbarKey(coords)];
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());
753 if (srcIdx < 0 || dstIdx < 0 || !sb.at(srcIdx, dstIdx).available ||
754 !claimedDsts.insert(dstIdx).second) {
757 reserved.emplace_back(srcIdx, dstIdx);
766 llvm::SmallVector<int, 8> reservedMasterDsts;
767 for (MasterSetOp masterSetOp : switchboxOp.getOps<MasterSetOp>()) {
768 int dstIdx = sb.dstIndex(masterSetOp.destPort());
771 if (dstIdx < 0 || !claimedDsts.insert(dstIdx).second) {
775 if (masterSetOp.getDestBundle() == WireBundle::TileControl &&
776 AIEDialect::IsCtrlPktOverlayAttrHelper(masterSetOp.getContext())
777 .isAttrPresent(masterSetOp))
778 sb.packetJoinDst.set(dstIdx);
780 reservedMasterDsts.push_back(dstIdx);
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;
795 for (
int dstIdx : reservedMasterDsts)
796 for (
size_t i = 0; i < sb.srcPorts.size(); i++)
797 sb.at(i, dstIdx).available =
false;
801 auto isMuxed = [](
Port p) {
802 return llvm::is_contained(
803 {WireBundle::DMA, WireBundle::NOC, WireBundle::PLIO}, p.bundle);
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]) &&
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]) &&
820 for (
size_t j = 0; j < sb.dstPorts.size(); j++)
821 sb.at(i, j).available =
false;
823 for (PacketRulesOp rulesOp : switchboxOp.getOps<PacketRulesOp>()) {
824 int srcIdx = sb.srcIndex(rulesOp.sourcePort());
827 sb.packetOnlySrc.set(srcIdx);
833 auto it = graph.find(crossbarKey(coords));
834 if (it == graph.end())
837 for (
size_t i = 0; i < sb.
srcPorts.size(); i++)
838 for (
size_t j = 0; j < sb.
dstPorts.size(); j++)
843 auto it = graph.find(crossbarKey(coords));
844 if (it == graph.end())
850 for (
size_t i = 0; i < sb.
srcPorts.size(); i++)
854static constexpr double INF = std::numeric_limits<double>::max();
857enum Color : int8_t { WHITE = 0, GRAY = 1, BLACK = 2 };
860int Pathfinder::getOrAddNodeId(
const PathEndPoint &pep) {
861 auto it = nodeIds.find(pep);
862 if (it != nodeIds.end())
864 int id =
static_cast<int>(nodes.size());
866 nodes.push_back(pep);
876void Pathfinder::buildRoutingGraph() {
880 for (
auto &f : flows) {
881 getOrAddNodeId(f.src);
882 for (
auto &d : f.dsts)
888 for (
size_t id = 0;
id < nodes.size();
id++) {
889 PathEndPoint src = nodes[id];
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});
901 std::pair<TileID, Port> neighbors[] = {
903 {WireBundle::North, src.
port.channel}},
905 {WireBundle::East, src.
port.channel}},
907 {WireBundle::South, src.
port.channel}},
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() &&
914 llvm::is_contained(nIt->second.dstPorts, neighborPort))
915 dests.push_back({{neighborCoords, neighborPort}, &nIt->second});
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);
922 std::vector<Edge> edges;
923 edges.reserve(dests.size());
924 for (
auto &[dest, link] : dests) {
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});
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();
940 if (adjacency.size() < nodes.size())
941 adjacency.resize(nodes.size());
942 adjacency[id] = std::move(edges);
944 size_t n = nodes.size();
945 if (adjacency.size() < n)
947 wireEdgesBegin.resize(n);
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});
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);
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;
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});
990 using MutableQueue = d_ary_heap_indirect<
992 std::vector<uint64_t> &,
993 std::vector<double> &,
995 MutableQueue Q(distance, indexInHeap);
997 for (
auto [seed, cost] : llvm::zip_equal(seeds, seedCosts)) {
998 distance[seed] = cost;
1003 SmallVector<int, 8> unsettled(targets);
1004 while (!Q.empty()) {
1007 if (llvm::is_contained(unsettled, s)) {
1008 llvm::erase(unsettled, s);
1009 if (unsettled.empty())
1012 if (stops && stops->count(s)) {
1020 const bool sIsOut = (s & 1) == Out;
1021 const llvm::BitVector *avoidBranch =
nullptr;
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]))
1034 int dst = stateId(e.dst, isIntra ? Out : In);
1035 if (colors[dst] == BLACK || (isIntra && mayCross && !mayCross(s, dst)))
1037 double w = edgeWeight(e, packetId, avoid, avoidBranch);
1038 if (distance[s] + w >= distance[dst])
1040 distance[dst] = distance[s] + w;
1043 if (colors[dst] == WHITE) {
1059 SmallVector<int, 4>
idsTo(
int flow,
int dstState)
const;
1061 int splitPart(
int flow,
const std::set<int> &ids);
1072 std::map<PathEndPoint, SmallVector<int, 2>>
partsOf;
1087 std::set<std::pair<std::pair<PathEndPoint, PathEndPoint>, std::set<int>>>
1094 std::vector<llvm::DenseMap<int, std::pair<int, Edge>>>
treeOf;
1112 std::tie(other.
at, other.
a, other.
b, other.
apart);
1138 std::set<std::pair<int, int>>
met;
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);
1163 for (
auto [k, f] : llvm::enumerate(
parts)) {
1165 flowDsts.insert(f.dsts.begin(), f.dsts.end());
1167 for (
auto [k, f] : llvm::enumerate(
parts))
1169 for (
const auto &[ends, ids] :
pf.packetIdsTo)
1170 flowIds[
partsOf.at(ends.first).front()].insert(ids.begin(), ids.end());
1175 for (
size_t k = 0, n =
parts.size(); k < n; k++) {
1176 if (!isPinned(parts[k]))
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)
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)
1190 if (!others.empty())
1191 splitPart(k, others);
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));
1200 for (
auto &[_, set] : sets) {
1211 if (!again && (
reordered.count({earlier, later}) ||
1212 !
reordered.insert({later, earlier}).second))
1215 if (!llvm::is_contained(group, earlier))
1217 group.erase(llvm::find(group, later));
1218 group.insert(llvm::find(group, earlier), later);
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);
1231 std::set<int> otherIds;
1232 for (
int k : otherParts->second)
1234 for (
int k : SmallVector<int, 2>(srcParts->second)) {
1237 if (!otherIds.count(
id))
1239 if (!
parts[k].isPriorityFlow && !own.empty() &&
1240 own.size() <
flowIds[k].size())
1250 llvm::none_of(masters, [&](
int m) { return priorityMasters.count(m); }))
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);
1268 int dstState)
const {
1269 SmallVector<int, 4> ids;
1271 pf.packetIdsTo.find({
parts[flow].src,
pf.nodes[stateNode(dstState)]});
1272 if (it !=
pf.packetIdsTo.end())
1273 for (
int id : it->second)
1282 for (
size_t a = 0; a <
parts.size(); a++)
1283 for (
size_t b = 0; b <
parts.size(); b++) {
1285 bool same = llvm::any_of(
flowIds[a],
1286 [&](
int id) {
return flowIds[b].count(
id); });
1289 if (a < b &&
parts[a].packetId &&
parts[b].packetId &&
1292 (
pf.constraints.conflict &&
1302 int part =
parts.size();
1305 llvm::dbgs() <<
"\t\tRouting ids";
1307 llvm::dbgs() <<
' ' << id;
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); });
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); });
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);
1334 parts[flow].isPriorityFlow = prioritized(
flowIds[flow]);
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});
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)) {
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++) {
1370 if (xbar == graph.end())
1376 for (
size_t row = 0; row < x.
srcPorts.size(); row++)
1383llvm::Error Pathfinder::explainNoRouting(
const RouteState &st)
const {
1389 return c.usedCapacity > maxCircuitStreamCapacity;
1393 return llvm::formatv(
"from tile ({0}, {1}) to ({2}, {3})", sb.
srcCoords.col,
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))
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>(
1406 ", and it holds a channel " + link(*hop.second.sb) +
1407 " the other flows need.");
1409 if (!hop.second.sb->isCrossbar)
1410 held.insert(hop.second.sb);
1413 if (prioritized && llvm::any_of(graph, [&](
const auto &entry) {
1414 return overused(entry.second);
1416 return llvm::make_error<PinnedRoutingFailure>(
1419 ", and the router found no routing for the other flows around the "
1420 "channels it holds " +
1422 llvm::map_range(llvm::make_pointee_range(held), link))) +
1426 if (!checkReason.empty())
1427 return llvm::make_error<RoutingFailure>(checkReason);
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++) {
1441 roomless = !hasRoom(sb);
1443 if (rank > worstRank) {
1452 return llvm::make_error<RoutingFailure>(
"");
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())
1459 const SwitchSetting &s = it->second;
1461 for (
size_t k = 0; k < s.
dsts.size() && !uses; k++)
1470 crossbar ? llvm::formatv(
"the connection from {0} to {1} at tile ({2}, "
1476 :
"the links " + link(*worst);
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.");
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};
1491llvm::Error Pathfinder::cutOverflow()
const {
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())
1504 std::tuple<bool, int, bool> cut =
boundaryOf(a, b);
1513 llvm::any_of(llvm::seq<size_t>(0, x.
srcPorts.size()),
1514 [&](
size_t i) { return x.at(i, k).available; }))
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;
1536 if (packets && constraints.apartAcross && available > circuits.size())
1537 apart = constraints.apartAcross(low, up, available - circuits.size());
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)
1545 int from = up ? below : below + 1, to = up ? below + 1 : below;
1546 auto channel = [](
size_t n) {
return n == 1 ?
"channel" :
"channels"; };
1548 circuits.empty() ?
"" :
"the circuit flows from " +
joinNames(circuits);
1549 if (apart.
flows.size() > 1)
1551 ", no two of which can share an arbiter,";
1554 circuits.empty() ?
"the packet flows" : who +
", with packet flows,";
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));
1563 return llvm::Error::success();
1573 return stateId(
pf.nodeIds.at(p), Out);
1575 bool isPending(
int state)
const;
1576 void reach(ArrayRef<int> dsts);
1577 bool joinable(
int at, ArrayRef<int> dsts)
const;
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();
1590 bool join(
int state,
int predId,
const Edge &e);
1600 const std::vector<TreeHop> *
pinned =
nullptr;
1609 llvm::MapVector<int, std::pair<int, Edge>>
planned;
1624 llvm::DenseMap<int, SmallVector<int, 4>>
joins;
1635 llvm::MapVector<int, std::pair<SmallVector<int, 4>, std::set<int>>>
1647 SmallVector<std::pair<int, const SmallVector<int, 4> *>, 2>
joinedAt;
1660 int srcId =
pf.nodeIds.at(
part.src);
1661 tree.push_back(stateId(srcId, In));
1663 st.processedStamp[
tree.front()] = ++
st.curStamp;
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; })) {
1681 for (
auto it = st.
trunked.lower_bound({flow, 0});
1685 SmallVector<int, 4> shared;
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());
1693 for (
const auto &[state, _] : st.
treeOf[other])
1694 if ((state & 1) == Out && pf.nodes[stateNode(state)].coords == at)
1695 partOff.insert(state);
1707 return llvm::is_contained(dsts,
dstState(p));
1715 llvm::all_of(dsts, [&](
int dst) {
return isPending(dst); });
1719 auto shared = [&](ArrayRef<int> ids,
int other) {
1720 std::set<int> common;
1722 if (
st.flowIds[other].count(
id))
1726 for (
int other :
st.sameId[
flow]) {
1728 const Flow &o =
st.parts[other];
1730 if (!
st.treeDsts[other].empty() && llvm::is_contained(o.
dsts, o.
src) &&
1733 for (
int dst :
st.treeDsts[other]) {
1734 std::set<int> common = shared(
st.idsTo(other, dst),
flow);
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]));
1754 if (canJoin && !agree &&
isPending(dst) &&
1755 !
pf.constraints.conflict(
part.src, common, o.
src, common))
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)
1765 if (!llvm::is_contained(
joins[up], dst))
1766 joins[up].push_back(dst);
1767 if (!llvm::is_contained(
joinOwners[up], other))
1777 if (!
part.packetId ||
part.isPriorityFlow)
1779 llvm::DenseSet<int> sameIdDsts;
1780 for (
int other :
st.sameId[
flow]) {
1787 for (
auto [other, o] : llvm::enumerate(
st.parts)) {
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}))
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)
1799 if (!
st.conflicting[
flow].test(k)) {
1806 std::set<int> meeting, rest;
1807 for (
int dst : dsts)
1808 for (
int id :
st.idsTo(
flow, dst))
1810 for (
int id :
st.flowIds[
flow])
1811 if (!meeting.count(
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)};
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);
1839 auto mustMeet = [&](
int other) {
1840 return spans(flow, sharedDsts[other]) && spans(other, sharedDsts[other]);
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();
1857 for (
int owner : owners) {
1858 llvm::erase_if(sharedDsts[owner], [&](
int dst) {
return !isPending(dst); });
1859 if (mustMeet(owner))
1865 st.unmet.insert({
flow, owner});
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);
1872 SmallVector<SmallVector<int, 16>, 4> paths;
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)
1881 std::reverse(path.begin(), path.end());
1884 while (llvm::all_of(paths, [&](
const auto &path) {
1885 return trunk + 1 < path.size() && path[trunk] == paths[0][trunk];
1890 SmallVector<std::pair<int, Edge>, 4> hops;
1894 SmallVector<Meeting, 8> meetings;
1895 SmallVector<int, 8> targets;
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});
1904 for (
size_t k = 0; k < trunk; k++) {
1905 int at = paths[0][k];
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) {
1915 auto taken = [&](
int s) {
1916 return st.processedStamp[s] ==
st.curStamp ||
stops.count(s) ||
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) ||
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);
1933 TileID tile =
pf.nodes[stateNode(at)].coords;
1934 auto sb =
pf.graph.find(crossbarKey(tile));
1935 if (sb ==
pf.graph.end())
1938 auto node =
pf.nodeIds.find({tile, port});
1939 if (node ==
pf.nodeIds.end())
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)))
1946 Meeting m{in, {}, 0, k};
1948 for (
const Edge &e :
pf.adjacency[node->second])
1949 if (e.dst == stateNode(s) && e.sb == &sb->second &&
1951 m.hops.push_back({s, e});
1952 m.cost +=
pf.edgeWeight(e,
part.packetId,
avoid,
nullptr);
1955 if (m.hops.size() == next.size()) {
1956 meetings.push_back(std::move(m));
1957 targets.push_back(in);
1961 if (meetings.empty())
1963 llvm::DenseSet<int> off;
1965 for (
const auto &[s, _] : below(0))
1967 search({}, targets, off);
1968 const Meeting *best =
nullptr;
1969 for (
const Meeting &m : meetings)
1970 if (
pf.distance[m.in] < INF &&
1972 pf.distance[m.in] + m.cost <
pf.distance[best->in] + best->cost))
1974 if (!best || !
trace(best->in))
1976 st.unmet.erase({
flow, owner});
1977 st.meetingPorts.try_emplace({owner, best->in},
part.src);
1978 st.met.insert({
flow, owner});
1980 auto add = [&](
int s,
int from,
const Edge &e,
int depth) {
1981 planned.insert({s, {from, e}});
1983 st.processedStamp[s] =
st.curStamp;
1987 for (
const auto &[s, e] : best->hops) {
1988 add(s, best->in, e, hops);
1990 st.joinedHops[
flow].push_back({owner, e});
1998 const SmallVector<int, 4> &dsts =
joins[s];
2005 for (
const auto &[s, hop] : below(best->at)) {
2006 const auto &[from, e] = hop;
2008 st.joinedHops[
flow].push_back({owner, e});
2019 ArrayRef<int> targets,
2020 const llvm::DenseSet<int> &off) {
2022 llvm::DenseMap<int, llvm::BitVector> onArbiter;
2024 for (
const auto &[state, hop] :
planned) {
2025 const auto &[from, e] = hop;
2026 if (!e.sb->isCrossbar || drop.count(state))
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)) {
2035 away |=
st.conflicting[other];
2041 away.reset(onArbiter.find(from)->second);
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);
2051 llvm::DenseSet<int> blocked;
2054 blocked.insert(off.begin(), off.end());
2056 llvm::DenseMap<int, SmallVector<int, 4>> masters;
2057 bool limited = !
st.priorityMasters.empty();
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);
2066 pf.dijkstraShortestPaths(
2068 off.empty() ? &
stops : &blocked, targets,
2069 limited ? llvm::function_ref<
bool(
int,
int)>(mayCross) :
nullptr);
2074 size_t grown =
tree.size();
2075 while (
st.processedStamp[state] !=
st.curStamp) {
2078 int pred =
pf.preds[state];
2081 planned.insert({state, {pred,
pf.predEdge[state]}});
2083 st.processedStamp[state] =
st.curStamp;
2084 tree.push_back(state);
2089 static_cast<int>(
tree.size() - grown);
2100 llvm::DenseSet<int> off =
partOff;
2101 auto carries = [&](
int d,
int id) {
2102 return llvm::is_contained(
st.idsTo(
flow, d),
id);
2104 auto only = [&](
int d,
int id,
int other) {
2105 return carries(d,
id) && !carries(d, other);
2107 for (
auto [at, a, b, apart] :
st.splitsOf[
flow])
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));
2115 SmallVector<int, 8> below;
2117 auto entersAt = [&, tile = at](
int state) {
2118 return (state & 1) == In &&
pf.nodes[stateNode(state)].coords == tile;
2120 for (
auto *hop =
planned.find(s); !entersAt(s) && hop !=
planned.end();
2123 s = hop->second.first;
2127 off.insert(below.begin(), below.end());
2137 llvm::DenseSet<int> 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;
2147 const auto *other = llvm::find_if(
reached, [&](
int d) {
2152 int exit = exitOf(*other);
2154 if (s == root || exitOf(s) != exit)
2161 for (
const auto &[from, to, joined, intra] : *
pinned) {
2162 if (
toSelf && from == to)
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)
2171 return llvm::make_error<RoutingFailure>(
2172 "the route packet flows from " +
2174 " take alone does not fit this design: it goes from " +
2177 ", which the design's own switchboxes leave no connection for.",
2179 std::pair<int, std::pair<int, Edge>> hop{
2180 stateId(toId->second, intra ? Out : In),
2181 {stateId(fromId->second, intra ? In : Out), *e}};
2196 return llvm::Error::success();
2211 SmallVector<int, 8> targets;
2214 for (
const auto &[at, dsts] :
joins)
2216 targets.push_back(at);
2223 : llvm::min_element(
2229 llvm::DenseSet<int> off =
splitOff(currId);
2230 llvm::DenseSet<int> trunk =
trunkOff(currId);
2231 off.insert(trunk.begin(), trunk.end());
2233 search({}, targets, off);
2234 if (
pf.distance[currId] == INF)
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)) {
2245 joinedAt.push_back({currId, joined});
2253 return llvm::make_error<RoutingFailure>(
2254 "no path leads from " +
2257 " through the connections the switchboxes allow and existing "
2258 "routing leaves free.",
2265 return llvm::Error::success();
2273 llvm::DenseSet<int> branch;
2275 for (
int below = 0; top !=
tree.front() &&
children.lookup(top) == below;
2278 top =
planned.find(top)->second.first;
2283 off.insert(trunk.begin(), trunk.end());
2284 search(branch, dst, off);
2287 for (
int s = dst; s != top;) {
2288 const auto &[from, e] =
planned.find(s)->second;
2292 away ==
branchAvoid.end() ?
nullptr : &away->second);
2295 if (
pf.distance[dst] + rerouteMinSaving >= cost)
2297 for (
int s : branch) {
2298 st.processedStamp[s] = 0;
2303 for (
size_t k =
tree.size(); k-- > 0;)
2304 if (branch.count(
tree[k])) {
2308 [[maybe_unused]]
bool traced =
trace(dst);
2309 assert(traced &&
"a rerouted branch reaches its destination");
2318 if (
part.packetId) {
2319 st.routing.packetTrees[
part.src].push_back(
2320 {
part.src,
part.src,
false,
true});
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) {
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;
2344 st.treeOf[
flow].try_emplace(currId, predId, e);
2346 st.circuitHops[
flow].push_back(e);
2358 auto mergeable = [&] {
2362 std::set<PathEndPoint> dsts;
2364 if (
auto ids =
pf.packetIdsTo.find({f.src, dst});
2365 ids !=
pf.packetIdsTo.end() &&
2366 llvm::is_contained(ids->second, *packetId))
2372 bool sameGroupUnseen =
2373 packetGroupId >= 0 && packetId.has_value() &&
2375 (seen == cell.
packetIds.end() || seen->second ==
flow || mergeable());
2376 if (sameGroupUnseen) {
2377 int packetIdValue = *packetId;
2383 for (
size_t k = 0; k < sb.
srcPorts.size(); k++)
2385 for (
size_t l = 0; l < sb.
dstPorts.size(); l++)
2386 if (l !=
static_cast<size_t>(j))
2404 auto [it,
first] = branchPort.try_emplace(predId, &sb, j);
2422 bool takesSource = !packetId ||
st.partsOf.at(
part.src).front() ==
flow;
2424 for (
auto &[_, link] :
pf.graph) {
2428 if (k >= 0 && !
st.flowDsts.count({link.srcCoords, link.srcPorts[k]}))
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);
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});
2450 if (!
st.treeOf[
flow].try_emplace(state, predId, e).second)
2454 st.routing.packetTrees[
part.src].push_back(
2465 for (
const auto &[joinAt, joined] :
joinedAt) {
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);
2478 for (
const auto &[state, hop] : path)
2479 if (
join(state, hop.first, hop.second))
2480 st.joinedHops[
flow].push_back({other, hop.second});
2483 st.treeDsts[
flow].append(joined->begin(), joined->end());
2486 join(state, hop.first, hop.second);
2493 if (
st.partsOf.at(src).size() == 1) {
2497 for (
int id :
st.flowIds[
flow])
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);
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();
2518 for (
auto *pairs : {&st.
unmet, &st.
met})
2519 pairs->erase(pairs->lower_bound({flow, 0}),
2520 pairs->lower_bound({flow + 1, 0}));
2522 tree.emplace(*
this, st, flow);
2524 if (llvm::Error retry = tree->grow()) {
2525 llvm::consumeError(std::move(retry));
2528 llvm::consumeError(std::move(err));
2533 if (!tree->pinned && tree->reached.size() + tree->joinedAt.size() > 1)
2538 return llvm::Error::success();
2541int Pathfinder::applyRoutingFaults(
RouteState &st,
const RoutingFaults &faults,
2543 int illegalEdges = 0;
2545 for (
const TreeSplit &split : faults.
splits) {
2546 auto src = st.partsOf.find(split.
src);
2547 if (src == st.partsOf.end())
2549 auto partWith = [&](
int id) {
2550 for (
int k : src->second)
2551 if (st.flowIds[k].count(
id))
2555 int flow = partWith(split.
a), other = partWith(split.
b);
2556 if (flow < 0 || other < 0)
2558 std::optional<int> apart;
2560 auto it = nodeIds.find(*split.
apart);
2561 if (it == nodeIds.end())
2563 apart = stateId(it->second, Out);
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))
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)
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)
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) {
2594 st.partSplits[other].insert({split.
at, flow});
2595 }
else if (st.splitsOf[flow]
2596 .insert({split.at, split.a, split.b, apart})
2599 st.splitsTaught.insert({flow, {split.
at, split.
a, split.
b, apart}})
2601 LLVM_DEBUG(llvm::dbgs()
2602 <<
"Split ids " << split.
a <<
" and " << split.
b <<
" from "
2604 <<
" at tile (" << split.
at.col <<
", " << split.
at.row
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)
2615 LLVM_DEBUG(llvm::dbgs()
2622 st.splitOwnIds(pair);
2624 for (
const auto &pair : faults.
together) {
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);
2633 st.lessons += st.noJoin.insert({x, y}).second;
2634 st.noJoin.insert({y, x});
2636 if (!st.togetherSources.insert(pair).second)
2639 LLVM_DEBUG(llvm::dbgs()
2640 <<
"Route together: "
2645 st.splitOwnIds(pair);
2652 for (
const PathEndPoint &src : faults.
untrunk)
2653 if (st.untrunked.insert(src).second) {
2654 LLVM_DEBUG(llvm::dbgs()
2660 std::set<std::pair<int, int>> faulted;
2661 bool unjoined =
false;
2662 for (
const auto &[tile, conn] : faults.
connections) {
2664 auto it = graph.find(crossbarKey(tile));
2665 if (it == graph.end())
2667 SwitchboxConnect &sb = it->second;
2673 auto takes = [&](
const Edge &e) {
2674 return e.sb == &sb && e.i == i && e.j == j;
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);
2683 pinnedTakesAll &= st.isPinned(part);
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 &&
2691 faulted.insert({
static_cast<int>(flow), other});
2694 unjoined |= !joined;
2698 for (
auto [flow, other] : faulted)
2699 if (unjoined && st.spared.insert({flow, other}).second)
2701 else if (st.met.count({flow, other}) &&
2702 ++st.meetFaults[{std::min(flow, other), std::max(flow, other)}] <=
2704 st.reorder(flow, other,
true);
2706 st.lessons += st.noJoin.insert({flow, other}).second;
2707 return illegalEdges;
2717 LLVM_DEBUG(llvm::dbgs() <<
"\t---Begin Pathfinder::findPaths---\n");
2718 checkReason.clear();
2719 packetsFailed =
true;
2723 buildRoutingGraph();
2724 if (llvm::Error err = cutOverflow()) {
2725 packetsFailed =
false;
2726 return std::move(err);
2728 crowdedTiles.clear();
2731 for (
auto &[_, sb] : graph) {
2733 for (
auto [j, port] : llvm::enumerate(sb.
dstPorts))
2735 port.channel >= packetFanoutCap &&
2744 return negotiate(maxIterations,
nullptr);
2753 for (
const auto &[_, sb] : graph)
2756 auto sameFlow = [](
const Flow &a,
const Flow &b) {
2758 a.
packetId) == std::tie(b.packetGroupId, b.isPriorityFlow,
2759 b.src, b.dsts, b.packetId);
2762 return llvm::equal(a.flows, now.
flows, sameFlow) &&
2764 !any((a.values ^ settings) & a.consulted);
2766 auto replayed = llvm::find_if(*
attempts, replays);
2767 if (replayed !=
attempts->end() && !clVerifyReplays) {
2768 LLVM_DEBUG(llvm::dbgs() <<
"\tPathfinder: this attempt replays attempt "
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));
2781 llvm::Expected<Routing> found =
2782 negotiate(maxIterations, clVerifyReplays ? &now.
trajectory :
nullptr);
2787 bool replayable =
static_cast<bool>(found);
2790 llvm::Error failure =
2791 found ? llvm::Error::success()
2792 : llvm::handleErrors(
2794 [&](std::unique_ptr<RoutingFailure> f) -> llvm::Error {
2798 now.reason = f->reason;
2799 now.faults = f->faults;
2801 now.prototype = f->clone(f->reason, f->faults, f->loc);
2802 return llvm::Error(std::move(f));
2805 bool sameFailureType =
2806 static_cast<bool>(replayed->prototype) ==
2808 (!now.
prototype || replayed->prototype->dynamicClassID() ==
2810 bool same = replayed->trajectory == now.
trajectory &&
2811 replayed->routing.has_value() == now.
routing.has_value() &&
2812 (!now.
routing || hashRouting(*replayed->routing) ==
2814 sameFailureType && replayed->reason == now.
reason &&
2819 llvm::report_fatal_error(llvm::Twine(
"aie-pathfinder-verify-replays: "
2822 " does not replay attempt " +
2823 llvm::Twine(replayed -
attempts->begin()));
2824 LLVM_DEBUG(llvm::dbgs() <<
"\tPathfinder: this attempt replays attempt "
2826 <<
" of the ladder, as verified\n");
2827 ++numReplaysVerified;
2828 }
else if (replayable) {
2829 attempts->push_back(std::move(now));
2832 return std::move(failure);
2836llvm::Expected<Routing>
2837Pathfinder::negotiate(
const int maxIterations,
2838 std::vector<llvm::hash_code> *trajectory) {
2839 RouteState st(*
this);
2841 int iterationCount = -1;
2842 int illegalEdges = 0;
2843 std::optional<Routing> usable;
2845 int fewestIllegal = std::numeric_limits<int>::max(), sinceFewest = 0;
2847 int reorderedStall = 0;
2848 int priorityFaults = 0;
2851 int fewestRejected = std::numeric_limits<int>::max(), sinceFewestRejected = 0;
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);
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
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");
2884 std::set<std::tuple<bool, int, bool>> full;
2885 for (
const auto &[_, sb] : graph)
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) ||
2896 return explainNoRouting(st);
2899 LLVM_DEBUG(llvm::dbgs() <<
"\t\t---Begin findPaths iteration #"
2900 << iterationCount <<
"---\n");
2902 for (
auto &[_, sb] : graph) {
2909 for (
auto &[_, sb] : graph) {
2910 for (SwitchboxConnect::Cell &c : sb.
cells) {
2918 for (
auto &tree : st.treeOf)
2920 for (
auto &hops : st.circuitHops)
2922 for (
auto &dsts : st.treeDsts)
2924 for (
auto &hops : st.joinedHops)
2928 st.meetingPorts.clear();
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);
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;
2962 for (
const auto &pair : st.meetBlocked)
2963 if (st.togetherSources.insert(pair).second) {
2964 LLVM_DEBUG(llvm::dbgs()
2965 <<
"Route together to meet: "
2970 st.splitOwnIds(pair);
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});
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() &&
2984 [&](
int id) { return st.flowIds[k].count(id); })) {
2985 LLVM_DEBUG(llvm::dbgs()
2986 <<
"Route apart to meet: "
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});
2999 st.meetSplits.clear();
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);
3016 LLVM_DEBUG(llvm::dbgs()
3017 <<
"\t\t\tToo much capacity on (" << sb.
srcCoords.col
3022 << sb.
dstPorts[j].channel <<
", used_capacity = "
3024 <<
", over_capacity_count = " << c.
overCapacity <<
"\n");
3032 if (illegalEdges < fewestIllegal) {
3033 fewestIllegal = illegalEdges;
3034 sinceFewest = reorderedStall = 0;
3040 if (fewestIllegal == 0 && illegalEdges > 0) {
3041 sinceFewestRejected++;
3042 LLVM_DEBUG(llvm::dbgs()
3043 <<
"Rejected-routing stall " << sinceFewestRejected <<
'\n');
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;
3055 for (
auto &[_, group] : st.groupedFlows) {
3056 moved |= llvm::any_of(group, losing);
3057 std::stable_partition(group.begin(), group.end(), losing);
3059 reorderedStall += moved;
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)
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;
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;
3092 sinceFewestRejected++;
3094 LLVM_DEBUG(llvm::dbgs() <<
"Rejected-routing stall "
3095 << sinceFewestRejected <<
'\n');
3096 priorityFaults = rejected->faults.onlyPriorityMasters
3097 ? priorityFaults + 1
3101 stuck = faulted == pinnedOnly && st.lessons == lessons;
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())) {
3110 usable = st.routing;
3111 usableAt = iterationCount;
3113 return llvm::Error::success();
3116 return llvm::Error(std::move(rejected));
3117 checkReason = std::move(rejected->reason);
3118 return llvm::Error::success();
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;
3126 int totalPathLength = 0;
3127 for (
const auto &[_, sb] : graph)
3129 for (
const SwitchboxConnect::Cell &c : sb.
cells)
3131 llvm::dbgs() <<
"\t\t---End findPaths iteration #" << iterationCount
3132 <<
" , illegal edges count = " << illegalEdges
3133 <<
", total path length = " << totalPathLength <<
"---\n";
3136 trajectory->push_back(hashRouting(st.routing));
3137 if (stuck && usable) {
3138 llvm::consumeError(std::move(unmoved));
3139 return std::move(*usable);
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");
3148 return std::move(*usable);
3149 packetsFailed =
false;
3150 return explainNoRouting(st);
3153 }
while (illegalEdges > 0);
3155 LLVM_DEBUG(llvm::dbgs() <<
"\t---End Pathfinder::findPaths---\n");
3156 return std::move(st.routing);
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
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::optional< int > apart
std::set< PathEndPoint > flowDsts
std::vector< SmallVector< int, 4 > > prioritySets
std::set< std::pair< int, int > > noJoin
std::set< PathEndPoint > untrunked
std::vector< llvm::DenseMap< int, std::pair< int, Edge > > > treeOf
llvm::DenseSet< int > priorityMasters
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::vector< Flow > parts
RouteState(const Pathfinder &pf)
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
int groupOf(const Flow &f) const
TreeBuilder(Pathfinder &pf, RouteState &st, int flow)
llvm::MapVector< int, SmallVector< int, 4 > > sharedDsts
bool isPending(int state) const
SmallVector< PathEndPoint, 4 > pending
SwitchSettings switchSettings
SmallVector< int, 4 > pinnedJoinDsts
llvm::DenseSet< int > foreign
llvm::DenseSet< int > stops
llvm::DenseSet< int > trunkOff(int dst) const
SmallVector< int, 16 > treeHops
llvm::MapVector< int, SmallVector< int, 4 > > blockedDsts
SmallVector< int, 16 > seeds
SmallVector< int, 4 > met
void reach(ArrayRef< int > dsts)
void search(const llvm::DenseSet< int > &drop, ArrayRef< int > targets, const llvm::DenseSet< int > &off={})
const std::vector< TreeHop > * pinned
SmallVector< double, 16 > seedCosts
llvm::DenseSet< int > unjoinable
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
SmallVector< int, 16 > tree
llvm::DenseSet< int > partOff
llvm::DenseMap< int, SmallVector< int, 2 > > joinOwners
SmallVector< int, 4 > reached
llvm::DenseMap< int, llvm::BitVector > branchAvoid
llvm::DenseSet< int > disagree
llvm::Error placePinned()
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::DenseSet< int > trunkDsts
const llvm::BitVector * avoid
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< Flow > flows
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
llvm::SmallDenseMap< int, int, 2 > packetIds
std::vector< Port > dstPorts
std::vector< Port > srcPorts
int srcIndex(Port p) const
void addToUnit(int j, int flow)
llvm::BitVector circuitOnlyDst
Cell & at(size_t i, size_t j)
void bumpDemand(size_t i, size_t j)
std::vector< Cell > cells
int dstIndex(Port p) const
void joinUnits(int j, int k)
std::optional< PathEndPoint > apart