MLIR-AIE 1.4.6.dev
AIECtrlPacketToDma.cpp
Go to the documentation of this file.
1//===- AIECtrlPacketToDma.cpp -----------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2024 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
11
12#include "CtrlPacketRuns.h"
13
14#include "mlir/Pass/Pass.h"
15#include "llvm/ADT/DenseSet.h"
16
17#include <optional>
18
19namespace xilinx::AIEX {
20#define GEN_PASS_DEF_AIECTRLPACKETTODMA
21#define GEN_PASS_DEF_AIECTRLPACKETINFERTILES
22#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
23} // namespace xilinx::AIEX
24
25#define DEBUG_TYPE "aie-ctrl-packet-to-dma"
26
27using namespace mlir;
28using namespace xilinx;
29using namespace xilinx::AIE;
30using namespace xilinx::AIEX;
31
32static ShimDMAAllocationOp getCtrlPktShimAlloc(DeviceOp device, int col) {
33 AIEDialect::IsCtrlPktOverlayAttrHelper overlay(device.getContext());
34 for (auto alloc : device.getOps<AIE::ShimDMAAllocationOp>())
35 if (overlay.isAttrPresent(alloc) && AIE::isMM2S(alloc.getChannelDir()) &&
36 alloc.getTileOp().colIndex() == col)
37 return alloc;
38 return {};
39}
40
43 AIECtrlPacketInferTilesPass> {
44 void runOnOperation() override {
45 DeviceOp device = getOperation();
46 const auto &targetModel = device.getTargetModel();
47 OpBuilder devBuilder = OpBuilder::atBlockBegin(device.getBody());
48
49 auto sequenceOps = device.getOps<AIE::RuntimeSequenceOp>();
50 for (auto f : sequenceOps) {
51 for (auto ctrlPktOp : f.getOps<NpuControlPacketOp>()) {
52 auto tOp = TileOp::getOrCreate(devBuilder, device,
53 (int)ctrlPktOp.getColumnFromAddr(),
54 (int)ctrlPktOp.getRowFromAddr());
55 // Assign controller id
56 auto tileIDMap = targetModel.getTileToControllerIdMap(true);
57 if (tOp->hasAttr("controller_id"))
58 continue;
59 auto pktInfoAttr = AIE::PacketInfoAttr::get(
60 tOp->getContext(), /*pkt_type*/ 0,
61 /*pkt_id*/ tileIDMap[{tOp.colIndex(), tOp.rowIndex()}]);
62 tOp->setAttr("controller_id", pktInfoAttr);
63 }
64 }
65 }
66};
67
69 : xilinx::AIEX::impl::AIECtrlPacketToDmaBase<AIECtrlPacketToDmaPass> {
70 using Base::Base;
71
72 struct BatchInfo {
74 int64_t startOffset;
75 int64_t totalSize;
76 std::string shimDmaAllocName;
77 Operation *first;
78 unsigned delivery;
79 unsigned interval;
84 std::optional<int32_t> multicast;
85 };
86
87 static DMAConfigureTaskForOp emitTask(OpBuilder &builder, Location loc,
88 Value buffer, const BatchInfo &batch) {
89 auto task = DMAConfigureTaskForOp::create(
90 builder, loc, builder.getIndexType(),
91 SymbolRefAttr::get(builder.getContext(), batch.shimDmaAllocName),
92 /*issue_token=*/true, /*repeat_count=*/0,
93 /*repeat_count_val=*/Value());
94 OpBuilder::InsertionGuard guard(builder);
95 builder.createBlock(&task.getBody());
96 AIE::DMABDOp::create(builder, loc, buffer,
97 static_cast<int>(batch.startOffset),
98 static_cast<int>(batch.totalSize));
99 AIE::EndOp::create(builder, loc);
100 return task;
101 }
102
103 void runOnOperation() override {
104 DeviceOp device = getOperation();
105 const auto &targetModel = device.getTargetModel();
106 auto *ctx = device->getContext();
107 auto loc = device->getLoc();
108 SymbolTable symbols(device);
109
110 if (targetModel.getTargetArch() == AIEArch::AIE1)
111 return; // Disable this pass for AIE1; AIE1 support NYI.
112
113 device.walk([](DMAAwaitTaskOp await) {
114 if (isa_and_nonnull<NpuControlPacketOp, ControlPacketBarrierOp>(
115 await->getNextNode()))
116 await.removeDeferCompletionAttr();
117 });
118
119 auto sequenceOps = device.getOps<AIE::RuntimeSequenceOp>();
120 for (auto f : sequenceOps) {
121 if (f.getBody().empty())
122 continue;
123 Block &entry = f.getBody().front();
124 auto controlPacketOps = f.getOps<AIEX::NpuControlPacketOp>();
125 if (controlPacketOps.empty())
126 continue;
127
128 auto ctrlPktMemrefType = MemRefType::get(
129 ShapedType::kDynamic, IntegerType::get(ctx, 32), nullptr, nullptr);
130 auto packetData = entry.addArgument(ctrlPktMemrefType, loc);
131 std::vector<BatchInfo> batches;
132
133 int64_t ddrOffset = 0;
134
135 NpuControlPacketOp previous;
136 bool previousIntervalMulticast = false;
137 for (auto [index, interval] : llvm::enumerate(packetIntervals(entry))) {
138 llvm::DenseSet<uint32_t> multicastWords;
139 llvm::DenseMap<TileID, uint32_t> multicastRoutes;
140 bool disjointMulticastRoutes = true;
141 bool disjointMulticast = interval.ordinary;
142 auto groups = controlPacketMulticasts(
143 device->getParentOfType<ModuleOp>(), interval.device);
144 if (failed(groups))
145 return signalPassFailure();
146 for (NpuControlPacketOp packet : interval.packets)
147 if (auto id = packet.getMulticastId()) {
148 if (*id >= groups->size()) {
149 packet.emitOpError("multicast_id ")
150 << *id << " has no declaration in the active overlay";
151 return signalPassFailure();
152 }
153 for (auto tile : (*groups)[*id].tiles.getAsRange<AIE::TileAttr>()) {
154 auto destination = tile.getTileID();
155 auto [found, inserted] =
156 multicastRoutes.try_emplace(destination, *id);
157 disjointMulticastRoutes &= inserted || found->second == *id;
158 uint32_t address =
159 (destination.col << targetModel.getColumnShift()) |
160 (destination.row << targetModel.getRowShift()) |
161 packet.getLocalAddress();
162 unsigned words = packet.getData() ? packet.getData()->size()
163 : *packet.getLength();
164 for (unsigned word = 0; word < words; ++word)
165 multicastWords.insert(address + 4 * word);
166 }
167 }
168 for (NpuControlPacketOp packet : interval.packets)
169 if (!packet.getMulticastId() && packet.getData())
170 for (size_t word = 0; word < packet.getData()->size(); ++word)
171 disjointMulticast &=
172 !multicastWords.contains(packet.getAddress() + 4 * word);
173 bool new_batch = !previous || previous.getOpcode() != 0 ||
174 batches.back().delivery != interval.delivery ||
175 previousIntervalMulticast;
176 for (NpuControlPacketOp ctrlPktOp : interval.packets) {
177 int col = ctrlPktOp.getColumnFromAddr();
178 int row = ctrlPktOp.getRowFromAddr();
179
180 // A read's length describes its response, not an outgoing payload.
181 int64_t ctrlPktSize = 2; // ctrl info word + packet header
182 if (auto data = ctrlPktOp.getData())
183 ctrlPktSize += data->size();
184
185 // Read requests must end their DMA transfer. A batch is one stream
186 // packet, routed by its first header, so its packets share their
187 // destination.
188 bool batchable = ctrlPktOp.getOpcode() == 0;
189 std::optional<int32_t> multicast;
190 if (auto id = ctrlPktOp.getMulticastId())
191 multicast = *id;
192 if (targetModel.getTargetArch() == AIEArch::AIE2p && batchable &&
193 !new_batch && batches.back().tileId == TileID{col, row} &&
194 batches.back().multicast == multicast) {
195 batches.back().totalSize += ctrlPktSize;
196 batches.back().interval = index;
197 batches.back().ordinary &= interval.ordinary;
198 batches.back().independent &= interval.independent;
199 batches.back().disjointMulticast &= disjointMulticast;
200 batches.back().disjointMulticastRoutes &= disjointMulticastRoutes;
201 } else {
202 ShimDMAAllocationOp alloc;
203 if (multicast) {
204 auto source = (*groups)[*multicast].allocation;
205 alloc = symbols.lookup<ShimDMAAllocationOp>(source.getSymName());
206 if (!alloc || !AIE::isMM2S(alloc.getChannelDir()) ||
207 alloc.getTileOp().getTileID() !=
208 source.getTileOp().getTileID() ||
209 alloc.getChannelIndex() != source.getChannelIndex()) {
210 ctrlPktOp.emitOpError("multicast allocation @")
211 << source.getSymName()
212 << " requires the matching imported shim DMA allocation";
213 return signalPassFailure();
214 }
215 } else {
216 alloc = getCtrlPktShimAlloc(device, col);
217 }
218 if (!alloc) {
219 ctrlPktOp.emitOpError("column ")
220 << col
221 << " has no control packet shim DMA allocation; run "
222 "-aie-generate-column-control-overlay with "
223 "configuration=true, then -aie-import-overlay first";
224 return signalPassFailure();
225 }
226 batches.push_back({TileID{col, row}, ddrOffset, ctrlPktSize,
227 alloc.getSymName().str(), ctrlPktOp,
228 interval.delivery, static_cast<unsigned>(index),
229 interval.ordinary, interval.independent,
230 disjointMulticast, disjointMulticastRoutes,
231 multicast});
232 }
233 new_batch = !batchable;
234 ddrOffset += ctrlPktSize;
235 previous = ctrlPktOp;
236 }
237 previousIntervalMulticast =
238 llvm::any_of(interval.packets, [](NpuControlPacketOp packet) {
239 return packet.getMulticastId().has_value();
240 });
241 }
242
243 auto batchIt = batches.begin();
244 bool pendingMulticast = false;
245 for (; batchIt != batches.end(); ++batchIt) {
246 OpBuilder builder(batchIt->first);
247 DMAConfigureTaskForOp task =
248 emitTask(builder, batchIt->first->getLoc(), packetData, *batchIt);
249 DMAStartTaskOp::create(builder, loc, task);
250 auto next = std::next(batchIt);
251 bool independent = next != batches.end() &&
252 ((batchIt->independent && next->independent) ||
253 (batchIt->ordinary && next->ordinary &&
254 next->interval == batchIt->interval));
255 pendingMulticast |= batchIt->multicast.has_value();
256 bool defer =
257 next != batches.end() && next->delivery == batchIt->delivery &&
258 batchIt->independent == next->independent &&
259 (batchIt->independent || next->interval == batchIt->interval) &&
260 (!pendingMulticast || next->interval == batchIt->interval) &&
261 ((!batchIt->multicast && !next->multicast) ||
262 (((batchIt->independent && next->independent) ||
263 (batchIt->ordinary && next->ordinary)) &&
264 next->interval == batchIt->interval &&
265 ((batchIt->multicast && next->multicast &&
266 batchIt->disjointMulticastRoutes) ||
267 (!next->multicast && batchIt->disjointMulticast)))) &&
268 ((chainBds && next->shimDmaAllocName == batchIt->shimDmaAllocName &&
269 (independent || next->tileId == batchIt->tileId)) ||
270 (parallelShims && independent));
271 DMAAwaitTaskOp::create(builder, loc, task,
272 defer ? builder.getUnitAttr() : UnitAttr{});
273 pendingMulticast &= defer;
274 }
275 for (NpuControlPacketOp packet :
276 llvm::make_early_inc_range(controlPacketOps))
277 packet.erase();
278 }
279 device.walk([](ControlPacketBarrierOp barrier) { barrier.erase(); });
280 }
281};
282
283std::unique_ptr<OperationPass<DeviceOp>>
285 return std::make_unique<AIECtrlPacketInferTilesPass>();
286}
287std::unique_ptr<OperationPass<DeviceOp>> AIEX::createAIECtrlPacketToDmaPass() {
288 return std::make_unique<AIECtrlPacketToDmaPass>();
289}
290std::unique_ptr<OperationPass<DeviceOp>>
291AIEX::createAIECtrlPacketToDmaPass(const AIECtrlPacketToDmaOptions &options) {
292 return std::make_unique<AIECtrlPacketToDmaPass>(options);
293}
mlir::FailureOr< llvm::SmallVector< ControlPacketMulticast > > controlPacketMulticasts(mlir::ModuleOp module, mlir::FlatSymbolRefAttr reference)
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIECtrlPacketInferTilesPass()
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIECtrlPacketToDmaPass()
llvm::SmallVector< PacketInterval > packetIntervals(mlir::Block &block)
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
bool isMM2S(DMAChannelDir dir)
True if dir moves data out of memory onto a stream (MM2S, ControlMM2S).
Definition AIEEnums.h:19
static DMAConfigureTaskForOp emitTask(OpBuilder &builder, Location loc, Value buffer, const BatchInfo &batch)