MLIR-AIE 1.4.6.dev
AIEExpandLoadPdi.cpp
Go to the documentation of this file.
1//===- AIEExpandLoadPdi.cpp -------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2025 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// This pass expands `npu.load_pdi` operations that reference a device. There
9// are two output modes, controlled by the `ctrl-pkt` option:
10//
11// 1. Default (ctrl-pkt=false): replaces each `load_pdi @device` with
12// a. an empty device PDI load (`load_pdi @empty_N`), which causes the
13// firmware to reset the device, and
14// b. an `aiex.npu.write_config @device`, whose register writes the NPU
15// translation emits (or, with inline-config, those writes as ops).
16// c. with teardown, an `aiex.npu.write_teardown @device` where it ends.
17// 2. With ctrl-pkt=true: replaces each `load_pdi @device` with
18// a. a `load_pdi @ctrl_pkt_overlay`, which configures the NPU to stream
19// further configuration as control packets, and
20// b. a sequence of `aiex.npu.control_packet` ops carrying the device's
21// configuration.
22//
23//===----------------------------------------------------------------------===//
24
30
31#include "mlir/Dialect/Arith/IR/Arith.h"
32#include "mlir/Dialect/MemRef/IR/MemRef.h"
33#include "mlir/Pass/Pass.h"
34
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/MapVector.h"
37#include "llvm/ADT/StringRef.h"
38#include "llvm/Support/FormatVariadic.h"
39#include "llvm/Support/raw_ostream.h"
40
41#include <array>
42#include <map>
43#include <set>
44
45namespace xilinx::AIEX {
46#define GEN_PASS_DEF_AIEEXPANDLOADPDI
47#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
48} // namespace xilinx::AIEX
49
50#define DEBUG_TYPE "aie-expand-load-pdi"
51
52using namespace mlir;
53using namespace xilinx;
54using namespace xilinx::AIEX;
55using namespace xilinx::AIE;
56
57namespace {
58
59static AIE::DeviceOp controlOverlayOf(AIE::DeviceOp device) {
60 auto ref = device.getOverlayAttr();
61 return ref ? device->getParentOfType<ModuleOp>().lookupSymbol<AIE::DeviceOp>(
62 ref)
63 : AIE::DeviceOp{};
64}
65
66using OverlayCopies = llvm::DenseMap<AIE::DeviceOp, AIE::DeviceOp>;
67
68// Firmware caches the last PDI address, so consecutive resets alternate copies.
69static AIE::DeviceOp overlayPreload(AIE::DeviceOp overlay, unsigned parity,
70 OverlayCopies &copies) {
71 if (!parity)
72 return overlay;
73 auto [it, inserted] = copies.try_emplace(overlay);
74 if (!inserted)
75 return it->second;
76 auto copy = cast<AIE::DeviceOp>(overlay->clone());
77 copy.setSymName((overlay.getSymName() + "_copy").str());
78 SymbolTable(overlay->getParentOfType<ModuleOp>()).insert(copy);
79 return it->second = copy;
80}
81
82// A control-packet reload reaches a tile only if `overlay` routes control
83// packets to its TileControl port. `packets` are the reload's.
84static LogicalResult
85verifyOverlayReachesTiles(NpuLoadPdiOp loadPdiOp, AIE::DeviceOp overlay,
86 iterator_range<Block::iterator> packets) {
87 std::set<AIE::TileID> reached;
88 overlay.walk([&](AIE::SwitchboxOp sb) {
89 for (Operation &op : sb.getConnections().front()) {
90 std::optional<AIE::Port> dest;
91 if (auto master = dyn_cast<AIE::MasterSetOp>(op))
92 dest = master.destPort();
93 else if (auto connect = dyn_cast<AIE::ConnectOp>(op))
94 dest = connect.destPort();
95 if (dest == AIE::Port{AIE::WireBundle::TileControl, 0})
96 reached.insert({sb.colIndex(), sb.rowIndex()});
97 }
98 });
99 for (Operation &op : packets) {
100 auto packet = dyn_cast<NpuControlPacketOp>(op);
101 if (!packet)
102 continue;
103 AIE::TileID tile{static_cast<int>(packet.getColumnFromAddr()),
104 static_cast<int>(packet.getRowFromAddr())};
105 if (reached.count(tile))
106 continue;
107 return loadPdiOp.emitError()
108 << "a control-packet reload configures tile (" << tile.col << ", "
109 << tile.row << "), but @" << overlay.getSymName()
110 << " routes no control packets to it";
111 }
112 return success();
113}
114
115// The empty device whose PDI load makes the firmware reset the array. `parity`
116// alternates so that two consecutive loads never name the same PDI (see
117// transformLoadPdi).
118static AIE::DeviceOp getOrCreateEmptyDevice(ModuleOp moduleOp,
119 AIE::AIEDevice deviceType,
120 unsigned parity, Location loc) {
121 std::string emptyName = "empty_" + std::to_string(parity);
122 if (auto existing = moduleOp.lookupSymbol<AIE::DeviceOp>(emptyName)) {
123 // Shared reset PDIs retain every load and trailing sequence's provenance.
124 loc = FusedLoc::get(moduleOp.getContext(), {existing.getLoc(), loc});
125 existing->setLoc(loc);
126 existing.getRegion().front().getTerminator()->setLoc(loc);
127 return existing;
128 }
129
130 OpBuilder builder(moduleOp.getContext());
131 builder.setInsertionPointToStart(moduleOp.getBody());
132 auto emptyDevice = AIE::DeviceOp::create(
133 builder, loc, deviceType, builder.getStringAttr(emptyName), nullptr);
134 emptyDevice.getRegion().emplaceBlock();
135 builder.setInsertionPointToEnd(&emptyDevice.getRegion().front());
136 AIE::EndOp::create(builder, loc);
137 return emptyDevice;
138}
139
140// A control-packet reload: the load_pdi it replaces, the device it streams,
141// and the overlay load ahead of it.
142struct CtrlPktReload {
143 NpuLoadPdiOp load;
144 AIE::DeviceOp device;
145 NpuLoadPdiOp preload;
146 AIE::DeviceOp overlay;
147};
148
149// The ops of `block` strictly between `after` and `end`, where null means the
150// block's start or end.
151static iterator_range<Block::iterator>
152opsBetween(Block *block, Operation *after, Operation *end) {
153 return llvm::make_range(after ? std::next(after->getIterator())
154 : block->begin(),
155 end ? end->getIterator() : block->end());
156}
157
158// Set `builder` at the next load_pdi, or at the block's end if there is none.
159static void setInsertionPointToSegmentEnd(OpBuilder &builder,
160 NpuLoadPdiOp loadPdiOp) {
161 Operation *op = loadPdiOp->getNextNode();
162 while (op && !isa<NpuLoadPdiOp>(op) && !op->hasTrait<OpTrait::IsTerminator>())
163 op = op->getNextNode();
164 if (op)
165 builder.setInsertionPoint(op);
166 else
167 builder.setInsertionPointToEnd(loadPdiOp->getBlock());
168}
169
170// Helper to transform a single load_pdi operation. Without `keepPreload` the
171// reset or overlay load is left out. With `teardown` the configuration's
172// teardown goes where it ends. A control packet configuration under teardown
173// goes in here, its writes from `configData` and its teardown's from
174// `teardownData`, in program order, since masked writes fold onto the control
175// packets before them. Without teardown, control packets go in once every
176// load_pdi is known (`ctrlPktReloads`), so a sequence's loads share them.
177static LogicalResult transformLoadPdi(
178 NpuLoadPdiOp loadPdiOp, ModuleOp moduleOp, unsigned index,
179 AIEX::ExpandMode defaultMode, bool keepPreload, bool teardown,
180 AIEX::BlockwriteData *configData, AIEX::BlockwriteData *teardownData,
181 SmallVectorImpl<CtrlPktReload> &ctrlPktReloads, OverlayCopies &copies) {
182 OpBuilder builder(loadPdiOp);
183
184 // Only process load_pdi ops that reference a device
185 auto deviceRefAttr = loadPdiOp.getDeviceRefAttr();
186 if (!deviceRefAttr) {
187 return success();
188 }
189
190 // Per-op annotation takes precedence; fall back to pass default
191 AIEX::ExpandMode mode = loadPdiOp.getExpandMode().value_or(defaultMode);
192 if (mode == AIEX::ExpandMode::none)
193 return success();
194 bool ctrlPkt = (mode == AIEX::ExpandMode::ctrlpkt);
195
196 auto referencedDevice = moduleOp.lookupSymbol<AIE::DeviceOp>(deviceRefAttr);
197 if (!referencedDevice) {
198 loadPdiOp.emitError("Referenced symbol '")
199 << deviceRefAttr.getValue() << "' is not a device";
200 return failure();
201 }
202
203 AIE::DeviceOp overlay;
204 if (ctrlPkt) {
205 overlay = controlOverlayOf(referencedDevice);
206 if (!overlay)
207 return referencedDevice.emitOpError(
208 "requires an overlay symbol reference for control-packet "
209 "configuration");
210 }
211
212 // Consecutive preloads alternate between two PDIs with the same contents,
213 // since the firmware skips a load of the PDI it loaded last.
214 if (keepPreload) {
215 FlatSymbolRefAttr preloadRef;
216 if (ctrlPkt) {
217 preloadRef = FlatSymbolRefAttr::get(
218 overlayPreload(overlay, index % 2, copies).getSymNameAttr());
219 } else {
220 AIE::DeviceOp emptyDevice =
221 getOrCreateEmptyDevice(moduleOp, referencedDevice.getDevice(),
222 index % 2, loadPdiOp.getLoc());
223 preloadRef = FlatSymbolRefAttr::get(emptyDevice.getSymNameAttr());
224 }
225 auto expandNone =
226 AIEX::ExpandModeAttr::get(builder.getContext(), AIEX::ExpandMode::none);
227 if (ctrlPkt)
228 NpuLoadPdiOp::create(builder, loadPdiOp.getLoc(), preloadRef,
229 /*id=*/nullptr, /*size=*/nullptr,
230 /*address=*/nullptr, expandNone);
231 else
232 NpuLoadPdiOp::create(builder, loadPdiOp.getLoc(), preloadRef,
233 loadPdiOp.getIdAttr(), loadPdiOp.getSizeAttr(),
234 loadPdiOp.getAddressAttr(), expandNone);
235 }
236 Operation *beforeConfig = loadPdiOp->getPrevNode();
237
238 if (!ctrlPkt) {
239 NpuWriteConfigOp::create(builder, loadPdiOp.getLoc(), deviceRefAttr);
240 if (teardown) {
241 setInsertionPointToSegmentEnd(builder, loadPdiOp);
242 NpuWriteTeardownOp::create(builder, loadPdiOp.getLoc(), deviceRefAttr);
243 }
244 loadPdiOp.erase();
245 return success();
246 }
247 if (!teardown) {
248 ctrlPktReloads.push_back({loadPdiOp, referencedDevice,
249 cast<NpuLoadPdiOp>(beforeConfig), overlay});
250 return success();
251 }
252
255 builder, referencedDevice, *configData, /*clElfDir=*/"", outputType,
256 /*skipCtrlPktOverlay=*/true))) {
257 loadPdiOp.emitError("Failed to generate configuration operations");
258 return failure();
259 }
260 auto config = opsBetween(loadPdiOp->getBlock(), beforeConfig, loadPdiOp);
261 if (failed(verifyOverlayReachesTiles(loadPdiOp, overlay, config)))
262 return failure();
263 builder.setInsertionPoint(loadPdiOp->getBlock(), config.begin());
264 SetDeviceOp::create(builder, loadPdiOp.getLoc(), deviceRefAttr);
265
266 // Erase the load_pdi before inserting the teardown, so the teardown's masked
267 // writes fold onto the configuration's writes instead of stopping at it.
268 Location loc = loadPdiOp.getLoc();
269 setInsertionPointToSegmentEnd(builder, loadPdiOp);
270 loadPdiOp.erase();
272 builder, referencedDevice, *teardownData, outputType,
273 /*skipCtrlPktOverlay=*/true))) {
274 emitError(loc, "Failed to generate teardown operations");
275 return failure();
276 }
277 ControlPacketBarrierOp::create(builder, loc);
278 return success();
279}
280
281// Both expansions rely on a PDI load to reset the array, which AIE4 does
282// not do.
283static LogicalResult
284verifyPdiLoadResets(ModuleOp module, ArrayRef<NpuLoadPdiOp> loadPdiOps,
285 function_ref<AIEX::ExpandMode(NpuLoadPdiOp)> expandMode) {
286 for (NpuLoadPdiOp loadPdiOp : loadPdiOps) {
287 if (expandMode(loadPdiOp) == AIEX::ExpandMode::none)
288 continue;
289 auto dev = module.lookupSymbol<AIE::DeviceOp>(loadPdiOp.getDeviceRefAttr());
290 if (dev && isa<AIE::AIE4TargetModel>(dev.getTargetModel()))
291 return loadPdiOp.emitOpError()
292 << "cannot be expanded on "
293 << AIE::stringifyAIEArch(dev.getTargetModel().getTargetArch())
294 << ": a PDI load does not reset the array";
295 }
296 return success();
297}
298
299// The checks that need no expansion, so the pass fails before it changes the
300// IR.
301static LogicalResult
302verifyExpansion(ModuleOp module, ArrayRef<NpuLoadPdiOp> loadPdiOps,
303 function_ref<AIEX::ExpandMode(NpuLoadPdiOp)> expandMode,
304 ArrayRef<bool> keepPreloads, bool teardown, bool initEntry) {
305 if (initEntry && !teardown)
306 return module.emitError(
307 "aie-expand-load-pdi: init-entry requires teardown");
308 if (initEntry)
309 for (auto device : module.getOps<AIE::DeviceOp>())
310 if (Operation *existing = device.lookupSymbol(initEntrySequenceName))
311 return existing->emitOpError()
312 << "is named '" << initEntrySequenceName
313 << "', which aie-expand-load-pdi reserves under init-entry";
314 // A load left alone is a PDI load; an expanded one resets only through the
315 // preload it gets.
316 llvm::MapVector<AIE::RuntimeSequenceOp, SmallVector<AIEX::ConfigStep>> steps;
317 for (auto [load, keepPreload] : llvm::zip_equal(loadPdiOps, keepPreloads)) {
318 NpuLoadPdiOp loadPdiOp = load;
319 if (auto seq = loadPdiOp->getParentOfType<AIE::RuntimeSequenceOp>()) {
320 FlatSymbolRefAttr ref = loadPdiOp.getDeviceRefAttr();
321 bool expanded = expandMode(loadPdiOp) != AIEX::ExpandMode::none;
322 steps[seq].push_back(
323 {loadPdiOp, expanded ? NpuLoadPdiOp() : loadPdiOp,
324 expanded && keepPreload,
325 ref ? module.lookupSymbol<AIE::DeviceOp>(ref) : nullptr});
326 }
327 }
328 for (auto &[seq, seqSteps] : steps)
329 if (failed(AIEX::checkResidentsSurvive(seq, seqSteps)))
330 return failure();
331 if (!teardown)
332 return success();
333 for (NpuLoadPdiOp loadPdiOp : loadPdiOps) {
334 // A configuration is torn down before its block's next load_pdi, which a
335 // load in a loop or branch may skip or repeat.
336 Operation *parent = loadPdiOp->getParentOp();
337 if (!isa<AIE::RuntimeSequenceOp>(parent))
338 return loadPdiOp.emitOpError("with teardown, must be in the runtime "
339 "sequence's body, not inside ")
340 << parent->getName();
341 if (expandMode(loadPdiOp) == AIEX::ExpandMode::none)
342 continue;
343 // write_teardown's verifier checks this too, but inline-config leaves no
344 // write_teardown to verify.
345 auto dev = module.lookupSymbol<AIE::DeviceOp>(loadPdiOp.getDeviceRefAttr());
346 if (Operation *start = dev ? AIEX::findShimDmaStart(dev) : nullptr)
347 return start->emitOpError(
348 "starts a shim DMA channel, which teardown cannot stop");
349 }
350 return success();
351}
352
353struct AIEExpandLoadPdiPass
354 : public xilinx::AIEX::impl::AIEExpandLoadPdiBase<AIEExpandLoadPdiPass> {
355 using AIEExpandLoadPdiBase::AIEExpandLoadPdiBase;
356
357 void getDependentDialects(DialectRegistry &registry) const override {
358 registry.insert<arith::ArithDialect, memref::MemRefDialect, AIE::AIEDialect,
359 AIEX::AIEXDialect>();
360 }
361
362 void runOnOperation() override {
363 auto module = getOperation();
364
365 // Collect all load_pdi operations in program order;
366 // need to collect once, then transform all collected ops;
367 // since the transform inserts a new preload load_pdi, we can't transform
368 // as we walk or it'd infinitely recurse.
369 SmallVector<NpuLoadPdiOp> loadPdiOps;
370
371 module.walk(
372 [&](NpuLoadPdiOp loadPdiOp) { loadPdiOps.push_back(loadPdiOp); });
373
374 // Map the legacy bool option to the new ExpandMode enum.
375 AIEX::ExpandMode defaultMode =
376 clCtrlPkt ? AIEX::ExpandMode::ctrlpkt : AIEX::ExpandMode::write32;
377
378 auto expandMode = [&](NpuLoadPdiOp loadPdiOp) {
379 return loadPdiOp.getDeviceRefAttr()
380 ? loadPdiOp.getExpandMode().value_or(defaultMode)
381 : AIEX::ExpandMode::none;
382 };
383 if (failed(verifyPdiLoadResets(module, loadPdiOps, expandMode)))
384 return signalPassFailure();
385
386 // Per enclosing runtime sequence, the parity of the FIRST and LAST of its
387 // empty-device resets and of its overlay loads, plus the device type, and
388 // the kind of its last load, which leaves the array as the next dispatch
389 // finds it. `transformLoadPdi` picks the preload as `index % 2` over the
390 // module-wide op order, and that order includes ops this pass skips, so a
391 // sequence's first preload is not necessarily the even one and its parity
392 // cannot be recovered from a count. Captured BEFORE transforming, which
393 // erases the ops.
394 using ArrayState = std::pair<AIEX::ExpandMode, FlatSymbolRefAttr>;
395 struct PreloadParity {
396 unsigned firstParity = 0;
397 unsigned lastParity = 0;
398 bool seen = false;
399 AIE::AIEDevice device = {};
400 AIE::DeviceOp firstOverlay, lastOverlay;
401 };
402 struct SequenceLoads {
403 std::array<PreloadParity, 2> preloads;
404 ArrayState last = {AIEX::ExpandMode::none, {}};
405 };
406 llvm::MapVector<AIE::RuntimeSequenceOp, SequenceLoads> sequences;
407 for (auto [index, loadPdiOp] : llvm::enumerate(loadPdiOps)) {
408 auto seq = loadPdiOp->getParentOfType<AIE::RuntimeSequenceOp>();
409 if (!seq)
410 continue;
411 SequenceLoads &loads = sequences[seq];
412 AIEX::ExpandMode mode = expandMode(loadPdiOp);
413 loads.last = {mode, {}};
414 if (mode == AIEX::ExpandMode::none)
415 continue;
416 auto dev =
417 module.lookupSymbol<AIE::DeviceOp>(loadPdiOp.getDeviceRefAttr());
418 if (!dev)
419 continue;
420 auto overlay = mode == AIEX::ExpandMode::ctrlpkt ? controlOverlayOf(dev)
421 : AIE::DeviceOp{};
422 if (mode == AIEX::ExpandMode::ctrlpkt && !overlay) {
423 dev.emitOpError("requires an overlay symbol reference for "
424 "control-packet configuration");
425 return signalPassFailure();
426 }
427 loads.last.second = overlay ? dev.getOverlayAttr() : FlatSymbolRefAttr{};
428 auto &entry = loads.preloads[mode == AIEX::ExpandMode::ctrlpkt];
429 if (!entry.seen) {
430 entry.firstParity = index % 2;
431 entry.seen = true;
432 entry.firstOverlay = overlay;
433 }
434 entry.lastParity = index % 2;
435 entry.lastOverlay = overlay;
436 entry.device = dev.getDevice();
437 }
438
439 // Teardown leaves the array ready for the next configuration of the same
440 // kind, so only a sequence's first load, or one after a load of another
441 // kind, needs its preload. A load this pass leaves alone sets up a
442 // configuration no teardown undoes, so the load after it keeps its preload.
443 // The host may dispatch a device's sequences in any order, so with an init
444 // entry they start without a preload only if each ends torn down by the
445 // same kind, and `reconfig_init` holds that kind's preload.
446 llvm::MapVector<AIE::DeviceOp, ArrayState> initEntries;
447 if (clInitEntry) {
448 for (auto &[seq, loads] : sequences)
449 initEntries.try_emplace(seq->getParentOfType<AIE::DeviceOp>(),
450 loads.last);
451 for (auto &[seq, loads] : sequences) {
452 auto device = seq->getParentOfType<AIE::DeviceOp>();
453 auto *it = initEntries.find(device);
454 if (it != initEntries.end() &&
455 (loads.last.first == AIEX::ExpandMode::none ||
456 loads.last != it->second))
457 initEntries.erase(it);
458 }
459 }
460
461 // A load gets a reset or overlay preload unless a teardown of the same kind
462 // left the array ready for it.
463 SmallVector<bool> keepPreloads;
464 llvm::DenseMap<Operation *, std::optional<ArrayState>> arrayState;
465 for (NpuLoadPdiOp loadPdiOp : loadPdiOps) {
466 auto seq = loadPdiOp->getParentOfType<AIE::RuntimeSequenceOp>();
467 std::optional<ArrayState> start;
468 if (seq)
469 if (auto *it = initEntries.find(seq->getParentOfType<AIE::DeviceOp>());
470 it != initEntries.end())
471 start = it->second;
472 std::optional<ArrayState> &state =
473 arrayState.try_emplace(seq, start).first->second;
474 auto dev =
475 loadPdiOp.getDeviceRefAttr()
476 ? module.lookupSymbol<AIE::DeviceOp>(loadPdiOp.getDeviceRefAttr())
477 : AIE::DeviceOp();
478 auto mode = expandMode(loadPdiOp);
479 ArrayState next = {mode, dev && mode == AIEX::ExpandMode::ctrlpkt
480 ? dev.getOverlayAttr()
481 : FlatSymbolRefAttr{}};
482 keepPreloads.push_back(!clTeardown || state != next);
483 state = next;
484 }
485
486 if (failed(verifyExpansion(module, loadPdiOps, expandMode, keepPreloads,
487 clTeardown, clInitEntry)))
488 return signalPassFailure();
489
490 OverlayCopies copies;
491 SmallVector<CtrlPktReload> ctrlPktReloads;
492 llvm::DenseMap<AIE::DeviceOp, AIEX::BlockwriteData> configData,
493 teardownData;
494 for (auto [idx, loadPdiOp] : llvm::enumerate(loadPdiOps)) {
495 bool keepPreload = keepPreloads[idx];
496 AIEX::BlockwriteData *config = nullptr, *teardown = nullptr;
497 if (clTeardown && expandMode(loadPdiOp) == AIEX::ExpandMode::ctrlpkt) {
498 auto device = loadPdiOp->getParentOfType<AIE::DeviceOp>();
499 config =
500 &configData.try_emplace(device, device, "loadpdi_").first->second;
501 teardown = &teardownData.try_emplace(device, device, "teardown_")
502 .first->second;
503 }
504 if (failed(transformLoadPdi(loadPdiOp, module, idx, defaultMode,
505 keepPreload, clTeardown, config, teardown,
506 ctrlPktReloads, copies))) {
507 signalPassFailure();
508 return;
509 }
510 }
511 SmallVector<std::pair<Operation *, AIE::DeviceOp>> ctrlPktSites;
512 for (CtrlPktReload &reload : ctrlPktReloads)
513 ctrlPktSites.emplace_back(reload.load, reload.device);
514 if (failed(AIE::insertConfigOps(
516 signalPassFailure();
517 return;
518 }
519 for (CtrlPktReload &reload : ctrlPktReloads) {
520 auto config =
521 opsBetween(reload.load->getBlock(), reload.preload, reload.load);
522 if (failed(
523 verifyOverlayReachesTiles(reload.load, reload.overlay, config))) {
524 signalPassFailure();
525 return;
526 }
527 OpBuilder builder(reload.load->getBlock(), config.begin());
528 SetDeviceOp::create(
529 builder, reload.load.getLoc(),
530 FlatSymbolRefAttr::get(reload.device.getSymNameAttr()));
531 reload.load.erase();
532 }
533 for (auto [device, kind] : initEntries) {
534 FlatSymbolRefAttr preloadRef =
535 kind.first == AIEX::ExpandMode::ctrlpkt
536 ? kind.second
537 : FlatSymbolRefAttr::get(
538 getOrCreateEmptyDevice(module, device.getDevice(), 0,
539 device.getLoc())
540 .getSymNameAttr());
541 OpBuilder builder(device.getContext());
542 builder.setInsertionPoint(
543 *device.getOps<AIE::RuntimeSequenceOp>().begin());
544 auto init = AIE::RuntimeSequenceOp::create(
545 builder, device.getLoc(),
546 builder.getStringAttr(initEntrySequenceName), BoolAttr{},
547 AIE::TraceBufferAttr{}, ArrayAttr{}, ArrayAttr{});
548 builder.setInsertionPointToStart(&init.getBody().emplaceBlock());
549 NpuLoadPdiOp::create(builder, device.getLoc(), preloadRef,
550 /*id=*/nullptr, /*size=*/nullptr,
551 /*address=*/nullptr,
552 /*expand_mode=*/
553 AIEX::ExpandModeAttr::get(builder.getContext(),
554 AIEX::ExpandMode::none));
555 }
556
557 if (clInlineConfig && failed(AIE::inlineWriteConfigs(module)))
558 return signalPassFailure();
559
560 // Under teardown a skipped preload follows only torn-down configurations
561 // (write_config's verifier checks this for resets), so nothing needs the
562 // append.
563 if (clTeardown)
564 return;
565
566 // The `index % 2` alternation above keeps two consecutive preloads on
567 // different PDIs WITHIN a sequence. But the host re-runs the whole sequence
568 // on every dispatch, so the alternation has to hold across that boundary
569 // too. When a sequence's last preload lands on the same PDI as its first,
570 // the firmware caches the address and no-ops the next dispatch's first
571 // load, and the configuration that follows lands on a device that was never
572 // reset. That is silent -- the first dispatch is correct and later ones
573 // return non-deterministic garbage.
574 //
575 // Append one more preload, of the parity opposite the last one, so the
576 // sequence ends somewhere its own start will not repeat. The empty PDI is a
577 // few hundred bytes, so the cost is negligible next to the configuration it
578 // guards.
579 for (auto &[seq, loads] : sequences) {
580 for (auto [ctrlPkt, info] : llvm::enumerate(loads.preloads)) {
581 if (!info.seen || info.firstParity != info.lastParity ||
582 info.firstOverlay != info.lastOverlay)
583 continue;
584 unsigned parity = 1 - info.lastParity;
585 FlatSymbolRefAttr preloadRef;
586 if (ctrlPkt) {
587 preloadRef = FlatSymbolRefAttr::get(
588 overlayPreload(info.lastOverlay, parity, copies)
589 .getSymNameAttr());
590 } else {
591 AIE::DeviceOp emptyDevice =
592 getOrCreateEmptyDevice(module, info.device, parity, seq.getLoc());
593 preloadRef = FlatSymbolRefAttr::get(emptyDevice.getSymNameAttr());
594 }
595 OpBuilder builder(seq.getContext());
596 Block &body = seq.getBody().front();
597 if (!body.empty() && body.back().hasTrait<OpTrait::IsTerminator>())
598 builder.setInsertionPoint(&body.back());
599 else
600 builder.setInsertionPointToEnd(&body);
601 NpuLoadPdiOp::create(builder, seq.getLoc(), preloadRef,
602 /*id=*/nullptr, /*size=*/nullptr,
603 /*address=*/nullptr,
604 /*expand_mode=*/
605 AIEX::ExpandModeAttr::get(seq.getContext(),
606 AIEX::ExpandMode::none));
607 }
608 }
609 }
610};
611
612} // namespace
613
614std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
616 return std::make_unique<AIEExpandLoadPdiPass>();
617}
constexpr llvm::StringLiteral initEntrySequenceName
Name of the runtime sequence aie-expand-load-pdi{init-entry} adds.
Definition AIEXPasses.h:113
mlir::Operation * findShimDmaStart(AIE::DeviceOp device)
LogicalResult checkResidentsSurvive(AIE::RuntimeSequenceOp seq, ArrayRef< ConfigStep > steps)
Definition AIEUtils.cpp:396
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createAIEExpandLoadPdiPass()
mlir::LogicalResult insertConfigOps(llvm::ArrayRef< std::pair< mlir::Operation *, xilinx::AIE::DeviceOp > > sites, AIEToConfigurationOutputType outputType)
mlir::LogicalResult inlineWriteConfigs(mlir::ModuleOp module)
mlir::LogicalResult generateAndInsertConfigOps(mlir::OpBuilder &builder, xilinx::AIE::DeviceOp device, xilinx::AIEX::BlockwriteData &blockwriteData, llvm::StringRef clElfDir="", AIEToConfigurationOutputType outputType=AIEToConfigurationOutputType::Transaction, bool skipCtrlPktOverlay=false)
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
mlir::LogicalResult generateAndInsertTeardownOps(mlir::OpBuilder &builder, xilinx::AIE::DeviceOp device, xilinx::AIEX::BlockwriteData &blockwriteData, AIEToConfigurationOutputType outputType=AIEToConfigurationOutputType::Transaction, bool skipCtrlPktOverlay=false)
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