MLIR-AIE 1.4.6.dev
AIENpuToCert.cpp
Go to the documentation of this file.
1//===- AIENpuToCert.cpp ----------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2025 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
12
13#include "mlir/Dialect/Arith/IR/Arith.h"
14#include "mlir/Dialect/MemRef/IR/MemRef.h"
15#include "mlir/IR/IRMapping.h"
16#include "mlir/IR/Matchers.h"
17#include "mlir/IR/SymbolTable.h"
18#include "mlir/Pass/Pass.h"
19#include "mlir/Transforms/DialectConversion.h"
20#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/StringMap.h"
23
24#include <bitset>
25#include <map>
26#include <set>
27#include <type_traits>
28#include <utility>
29#include <vector>
30
31namespace xilinx::AIEX {
32#define GEN_PASS_DEF_AIENPUTOCERT
33#define GEN_PASS_DEF_AIECERTPAGES
34#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
35} // namespace xilinx::AIEX
36
37using namespace mlir;
38using namespace xilinx;
39
40#define DEBUG_TYPE "npu-to-cert"
41
42namespace {
43
44// Trigger splitting below the 8 KB page limit to allow for estimated padding.
45// An unsplittable page is an error only if it exceeds cert_page_limit.
46static constexpr uint32_t cert_page_size = 8000;
47static constexpr uint32_t cert_page_limit = 8192;
48
49// Per-job control-code overhead: START_JOB (ISA_OPSIZE_START_JOB = 0x08) plus
50// END_JOB (ISA_OPSIZE_END_JOB = 0x04), emitted around every job's body by
51// emitJob.
52static constexpr uint32_t cert_job_start_cost = 8;
53static constexpr uint32_t cert_job_end_cost = 4;
54
55// True if `seq` holds its device's generated configuration, i.e. carries the
56// aie.generated_configure tag, either from convert-aie-to-transaction or from
57// tagConfigureByName.
58static bool isGeneratedConfigure(AIE::RuntimeSequenceOp seq) {
59 return AIE::AIEDialect::GeneratedConfigureAttrHelper(seq.getContext())
60 .isAttrPresent(seq);
61}
62
63// Hand-written IR may have no tag: there the sequence named `configure` is the
64// configuration. Tag it, unless a sequence of the device is already tagged (the
65// generated one was then named `configure0`, and `configure` is the user's).
66// Runs on every device before any sequence is converted, so the choice does
67// not depend on conversion order.
68static void tagConfigureByName(AIE::DeviceOp device) {
69 auto seqs = device.getBody()->getOps<AIE::RuntimeSequenceOp>();
70 if (llvm::any_of(seqs, isGeneratedConfigure))
71 return;
72 for (auto seq : seqs)
73 if (seq.getSymName() == "configure") {
74 AIE::AIEDialect::GeneratedConfigureAttrHelper(device.getContext())
75 .setAttr(seq, UnitAttr::get(device.getContext()));
76 return;
77 }
78}
79
80// The generated configuration sequence of `device`, or null if it has none.
81static AIE::RuntimeSequenceOp findGeneratedConfigure(AIE::DeviceOp device) {
82 for (auto seq : device.getBody()->getOps<AIE::RuntimeSequenceOp>())
83 if (isGeneratedConfigure(seq))
84 return seq;
85 return nullptr;
86}
87
88// Returns the PDI id to use for a cert.load_pdi that references `deviceSymName`
89// within `parentDevice`. If a load_pdi for that symbol already exists, its id
90// is reused so repeated loads of the same PDI share an id; otherwise a fresh id
91// (1-based, one past the current maximum) is assigned.
92static uint32_t getOrAssignPdiId(AIE::DeviceOp parentDevice,
93 StringRef deviceSymName) {
94 uint32_t pdiId = 1;
95 bool foundExisting = false;
96 parentDevice.walk([&](AIEX::CertLoadPdiOp loadPdiOp) {
97 if (loadPdiOp.getSymbol() == deviceSymName) {
98 pdiId = loadPdiOp.getPdiId();
99 foundExisting = true;
100 } else if (!foundExisting) {
101 pdiId = std::max(pdiId, loadPdiOp.getPdiId() + 1);
102 }
103 });
104 return pdiId;
105}
106
107struct RuntimeSequenceToCertJob : OpConversionPattern<AIE::RuntimeSequenceOp> {
108 using OpConversionPattern::OpConversionPattern;
109
110 RuntimeSequenceToCertJob(MLIRContext *context, PatternBenefit benefit = 1)
111 : OpConversionPattern(context, benefit) {}
112
113 LogicalResult
114 matchAndRewrite(AIE::RuntimeSequenceOp op, OpAdaptor adaptor,
115 ConversionPatternRewriter &rewriter) const override {
116
117 bool isConfigure = isGeneratedConfigure(op);
118 uint32_t newJobId = 1;
119 if (!isConfigure) {
120 uint32_t maxJobId = 1;
121 op->getParentOp()->walk([&](AIEX::CertJobOp certJobOp) {
122 maxJobId = std::max(maxJobId, certJobOp.getJobId());
123 });
124 newJobId = maxJobId + 1;
125 }
126
127 // Replace the runtime sequence with a job directly inside aie.device.
128 // CertJobOp lists DeviceOp as an allowed parent in its ParentOneOf trait.
129 // cert-legalize-pages later groups contiguous jobs into implicit pages.
130 rewriter.setInsertionPoint(op);
131 auto jobOp = AIEX::CertJobOp::create(rewriter, op.getLoc(), newJobId);
132
133 // Tag the implicit configuration job so a later step can force it to be the
134 // first page on uC0 and keep it out of user implicit pages.
135 if (isConfigure)
136 jobOp->setAttr("cert.configure", rewriter.getUnitAttr());
137
138 // Clone runtime sequence body into job
139 // Note: This preserves block arguments from the runtime sequence, which
140 // will be present in the MLIR IR but are not emitted in the final assembly
141 IRMapping remap;
142 op.getRegion().cloneInto(&jobOp.getBody(), remap);
143 AIEX::CertJobOp::ensureTerminator(jobOp.getBody(), rewriter, op->getLoc());
144
145 // Erase the original runtime sequence
146 rewriter.eraseOp(op);
147
148 return success();
149 }
150};
151
152// Tile coordinates replace the upper bits of a tile-relative address. Warn
153// when the given address has upper bits of its own that disagree.
154static void warnOnMismatchedTileBits(Operation *op, uint32_t address,
155 uint32_t col, uint32_t row) {
156 const auto &tm = AIE::getTargetModel(op);
157 uint32_t expectedUpperBits = tm.getTileAddress(col, row);
158 uint32_t upperBits = address & ~0xfffff;
159 if (upperBits != 0 && upperBits != expectedUpperBits)
160 op->emitWarning() << "address upper bits (0x" << llvm::utohexstr(upperBits)
161 << ") don't match row=" << row << " col=" << col
162 << " computed bits (0x"
163 << llvm::utohexstr(expectedUpperBits) << ")";
164}
165
166struct NpuWrite32ToCertWrite32 : OpConversionPattern<AIEX::NpuWrite32Op> {
167 using OpConversionPattern::OpConversionPattern;
168
169 LogicalResult
170 matchAndRewrite(AIEX::NpuWrite32Op op, OpAdaptor adaptor,
171 ConversionPatternRewriter &rewriter) const override {
172
173 std::optional<uint32_t> address =
174 AIEX::getConstantIntOperand(op.getAddress());
175 std::optional<uint32_t> value = AIEX::getConstantIntOperand(op.getValue());
176 if (!address || !value)
177 return op.emitOpError(
178 "cannot lower to cert.write32 with non-constant address or value");
179
180 // Get the absolute address, which properly handles row/col if present
181 std::optional<uint32_t> absAddress = op.getAbsoluteAddress();
182 if (!absAddress)
183 return failure();
184
185 uint32_t absoluteAddr = *absAddress;
186
187 // An address that became constant only after resolveRelativeAddresses,
188 // by folding or run inlining, still carries its tile coordinates.
189 std::optional<uint32_t> col = op.getColumn();
190 std::optional<uint32_t> row = op.getRow();
191 if (col && row)
192 warnOnMismatchedTileBits(op, *address, *col, *row);
193
194 rewriter.replaceOpWithNewOp<AIEX::CertWrite32Op>(op, absoluteAddr, *value);
195 return success();
196 }
197};
198
199struct NpuMaskWrite32ToCertMaskWrite32
200 : OpConversionPattern<AIEX::NpuMaskWrite32Op> {
201 using OpConversionPattern::OpConversionPattern;
202
203 LogicalResult
204 matchAndRewrite(AIEX::NpuMaskWrite32Op op, OpAdaptor adaptor,
205 ConversionPatternRewriter &rewriter) const override {
206
207 std::optional<uint32_t> address =
208 AIEX::getConstantIntOperand(op.getAddress());
209 std::optional<uint32_t> mask = AIEX::getConstantIntOperand(op.getMask());
210 std::optional<uint32_t> value = AIEX::getConstantIntOperand(op.getValue());
211 if (!address || !mask || !value)
212 return op.emitOpError(
213 "cannot lower to cert.maskwrite32 with non-constant "
214 "address, mask, or value");
215
216 // Get the absolute address, which properly handles row/col if present
217 std::optional<uint32_t> absAddress = op.getAbsoluteAddress();
218 if (!absAddress)
219 return failure();
220
221 uint32_t absoluteAddr = *absAddress;
222
223 std::optional<uint32_t> col = op.getColumn();
224 std::optional<uint32_t> row = op.getRow();
225 if (col && row)
226 warnOnMismatchedTileBits(op, *address, *col, *row);
227
228 rewriter.replaceOpWithNewOp<AIEX::CertMaskWrite32Op>(op, absoluteAddr,
229 *mask, *value);
230 return success();
231 }
232};
233
234struct NpuMaskPollToCertMaskPoll32 : OpConversionPattern<AIEX::NpuMaskPollOp> {
235 using OpConversionPattern::OpConversionPattern;
236
237 LogicalResult
238 matchAndRewrite(AIEX::NpuMaskPollOp op, OpAdaptor adaptor,
239 ConversionPatternRewriter &rewriter) const override {
240 std::optional<uint32_t> address =
241 AIEX::getConstantIntOperand(op.getAddress());
242 std::optional<uint32_t> mask = AIEX::getConstantIntOperand(op.getMask());
243 std::optional<uint32_t> value = AIEX::getConstantIntOperand(op.getValue());
244 if (!address || !mask || !value)
245 return op.emitOpError("cannot lower to cert.maskpoll32 with non-constant "
246 "address, mask, or value");
247
248 std::optional<uint32_t> absAddress = op.getAbsoluteAddress();
249 if (!absAddress)
250 return failure();
251
252 rewriter.replaceOpWithNewOp<AIEX::CertMaskPoll32Op>(op, *absAddress, *mask,
253 *value);
254 return success();
255 }
256};
257
258struct NpuBlockWriteToCertUcDma : OpConversionPattern<AIEX::NpuBlockWriteOp> {
259 // nextChainId is owned by the caller and shared by every rewrite in one
260 // conversion, so each name search resumes after the last name allocated.
261 // symbolTable is the device's; each new chain is added to it.
262 NpuBlockWriteToCertUcDma(MLIRContext *ctx, unsigned &nextChainId,
263 SymbolTable &symbolTable)
264 : OpConversionPattern(ctx), nextChainId(nextChainId),
265 symbolTable(symbolTable) {}
266
267 LogicalResult
268 matchAndRewrite(AIEX::NpuBlockWriteOp op, OpAdaptor adaptor,
269 ConversionPatternRewriter &rewriter) const override {
270
271 memref::GetGlobalOp dataOperand =
272 dyn_cast_or_null<memref::GetGlobalOp>(op.getData().getDefiningOp());
273 if (!dataOperand)
274 return failure();
275 MemRefType dataType = cast<MemRefType>(dataOperand.getResult().getType());
276 uint32_t dataSize = dataType.getNumElements();
277 // An empty copy is a no-op, and AIEBU rejects a descriptor whose payload
278 // label has no data.
279 if (dataSize == 0) {
280 rewriter.eraseOp(op);
281 return success();
282 }
283
284 std::string symbolName = "chain_" + std::to_string(nextChainId++);
285 while (symbolTable.lookup(symbolName))
286 symbolName = "chain_" + std::to_string(nextChainId++);
287
288 // Create a new uc_dma_write_des_sync operation
289 rewriter.replaceOpWithNewOp<AIEX::CertUcDmaWriteDesSyncOp>(op, symbolName);
290
291 // Create the uc_dma_chain operation
292 // Find the nearest device to insert the chain
293 auto parentDevice = op->getParentOfType<AIE::DeviceOp>();
294 if (!parentDevice) {
295 // No parent device - this shouldn't happen but handle gracefully
296 return failure();
297 }
298
299 // Insert after the last existing uc_dma_chain (before any pages/jobs),
300 // preserving the order of blockwrite ops. Globals are allowed to precede
301 // the chains, so skip over them too. The previous chain ends that leading
302 // run, so resume the scan there instead of at the start of the body.
303 Block *deviceBody = parentDevice.getBody();
304 Operation *insertAfter = nullptr;
305 Block::iterator it = deviceBody->begin();
306 if (lastChain && lastChain->getBlock() == deviceBody) {
307 insertAfter = lastChain;
308 it = std::next(Block::iterator(lastChain));
309 }
310 for (; it != deviceBody->end() &&
311 isa<AIEX::CertUcDmaChainOp, memref::GlobalOp>(*it);
312 ++it)
313 insertAfter = &*it;
314 if (insertAfter)
315 rewriter.setInsertionPointAfter(insertAfter);
316 else
317 rewriter.setInsertionPointToStart(deviceBody);
318
319 auto symbolAttr = rewriter.getStringAttr(symbolName);
320 auto chainOp =
321 AIEX::CertUcDmaChainOp::create(rewriter, op.getLoc(), symbolAttr);
322 symbolTable.insert(chainOp);
323 lastChain = chainOp;
324
325 Block *bb = new Block();
326 chainOp.getRegion().push_back(bb);
327 rewriter.setInsertionPointToStart(bb);
328 AIEX::CertUcDmaBdOp::create(rewriter, op.getLoc(), dataOperand.getName(),
329 op.getAddress(), dataSize, false);
330
331 AIEX::CertUcDmaChainOp::ensureTerminator(chainOp.getBody(), rewriter,
332 op->getLoc());
333 return success();
334 }
335
336 unsigned &nextChainId;
337 SymbolTable &symbolTable;
338 mutable Operation *lastChain = nullptr;
339};
340
341struct NpuSyncToCertWaitTCTS : OpConversionPattern<AIEX::NpuSyncOp> {
342 using OpConversionPattern::OpConversionPattern;
343
344 LogicalResult
345 matchAndRewrite(AIEX::NpuSyncOp op, OpAdaptor adaptor,
346 ConversionPatternRewriter &rewriter) const override {
347 std::optional<uint32_t> rowOpt = AIEX::getConstantIntOperand(op.getRow());
348 std::optional<uint32_t> colOpt =
349 AIEX::getConstantIntOperand(op.getColumn());
350 std::optional<uint32_t> channelOpt =
351 AIEX::getConstantIntOperand(op.getChannel());
352 std::optional<uint32_t> directionOpt =
353 AIEX::getConstantIntOperand(op.getDirection());
354 if (!rowOpt || !colOpt || !channelOpt || !directionOpt)
355 return op.emitOpError(
356 "cannot lower to cert.wait_tcts with non-constant sync parameters");
357 uint32_t row = *rowOpt;
358 uint32_t col = *colOpt;
359
360 // These are the shift amounts from the tct packet format in the
361 // architecture spec. The firmware expects the row and column packed and
362 // shifted down to zero.
363 const int row_id_shift = 16;
364 const int col_id_shift = 21;
365 uint16_t tile_id = col << (col_id_shift - row_id_shift) | row;
366 uint32_t channel = *channelOpt;
367 uint32_t direction = *directionOpt;
368
369 const std::vector<int> chan2actor_shim_s2mm = {0, 2, 3, 4};
370 const std::vector<int> chan2actor_shim_mm2s = {6, 7, 8, 9, 10, 11, 12, 13};
371 const std::vector<int> chan2actor_mem_s2mm = {1, 2, 3, 4, 5, 6, 7};
372 const std::vector<int> chan2actor_mem_mm2s = {16, 17, 18, 19, 20,
373 22, 23, 24, 25, 26};
374 const std::vector<int> chan2actor_tile_s2mm = {0, 1};
375 const std::vector<int> chan2actor_tile_mm2s = {6};
376
377 const auto &tm = AIE::getTargetModel(op);
378 const bool isS2MM =
379 direction == static_cast<std::underlying_type_t<AIE::DMAChannelDir>>(
380 AIE::DMAChannelDir::S2MM);
381
382 const std::vector<int> *chan2actor = nullptr;
383 if (tm.isCoreTile(col, row))
384 chan2actor = isS2MM ? &chan2actor_tile_s2mm : &chan2actor_tile_mm2s;
385 else if (tm.isMemTile(col, row))
386 chan2actor = isS2MM ? &chan2actor_mem_s2mm : &chan2actor_mem_mm2s;
387 else
388 chan2actor = isS2MM ? &chan2actor_shim_s2mm : &chan2actor_shim_mm2s;
389
390 size_t chanIdx = static_cast<size_t>(channel);
391 if (chanIdx >= chan2actor->size()) {
392 op.emitError("invalid DMA channel ")
393 << channel << " for " << (isS2MM ? "S2MM" : "MM2S")
394 << " direction in NpuSyncToCertWaitTCTS conversion";
395 return failure();
396 }
397
398 uint8_t actor_id = static_cast<uint8_t>((*chan2actor)[chanIdx]);
399 uint8_t num_tcts = 1;
400 rewriter.replaceOpWithNewOp<AIEX::CertWaitTCTSOp>(op, tile_id, actor_id,
401 num_tcts);
402 return success();
403 }
404};
405
406struct NpuLoadPdiToCertLoadPdi : OpConversionPattern<AIEX::NpuLoadPdiOp> {
407 using OpConversionPattern::OpConversionPattern;
408
409 LogicalResult
410 matchAndRewrite(AIEX::NpuLoadPdiOp op, OpAdaptor adaptor,
411 ConversionPatternRewriter &rewriter) const override {
412 // Get the device reference
413 auto deviceRef = op.getDeviceRef();
414 if (!deviceRef)
415 return failure();
416
417 StringRef deviceSymName = *deviceRef;
418
419 // Find parent device to get unique PDI ID
420 auto parentDevice = op->getParentOfType<AIE::DeviceOp>();
421 if (!parentDevice)
422 return failure();
423
424 // Assign a PDI ID, reusing an existing one for this device if present.
425 uint32_t pdiId = getOrAssignPdiId(parentDevice, deviceSymName);
426
427 // Replace with cert.load_pdi
428 rewriter.replaceOpWithNewOp<AIEX::CertLoadPdiOp>(
429 op, rewriter.getUI32IntegerAttr(pdiId),
430 FlatSymbolRefAttr::get(rewriter.getContext(), deviceSymName));
431
432 return success();
433 }
434};
435
436struct RunOpInlining : OpRewritePattern<AIEX::RunOp> {
437 using OpRewritePattern::OpRewritePattern;
438
439 LogicalResult matchAndRewrite(AIEX::RunOp op,
440 PatternRewriter &rewriter) const override {
441 // Get the callee runtime sequence
442 AIE::RuntimeSequenceOp calleeRuntimeSequence =
443 op.getCalleeRuntimeSequenceOp();
444 if (!calleeRuntimeSequence)
445 return failure();
446
447 // Get the callee body region
448 Region &calleeBody = calleeRuntimeSequence.getBody();
449
450 // Create argument mapping from run op arguments to callee parameters
451 IRMapping argMap;
452 ValueRange values = op.getArgs();
453 if (values.size() != calleeBody.getNumArguments()) {
454 op.emitError("number of run op arguments (")
455 << values.size()
456 << ") does not match number of callee runtime sequence "
457 "arguments ("
458 << calleeBody.getNumArguments() << ")";
459 return failure();
460 }
461 for (unsigned i = 0, n = calleeBody.getNumArguments(); i < n; i++) {
462 BlockArgument arg = calleeBody.getArgument(i);
463 Value val = values[i];
464 argMap.map(arg, val);
465 }
466
467 // Clone operations from callee into current location
468 rewriter.setInsertionPoint(op);
469 for (Operation &o : calleeBody.front().getOperations()) {
470 // Skip the terminator
471 if (isa<AIE::EndOp>(o))
472 continue;
473 rewriter.clone(o, argMap);
474 }
475
476 // Erase the run op
477 rewriter.eraseOp(op);
478
479 return success();
480 }
481};
482
483struct ConfigureOpToCertSection : OpRewritePattern<AIEX::ConfigureOp> {
484 using OpRewritePattern::OpRewritePattern;
485
486 // Clone the configure body at the rewriter's insertion point. The body is
487 // an optional region, so `aiex.configure @device {}` has no block to clone.
488 static void cloneConfigureBody(AIEX::ConfigureOp op,
489 PatternRewriter &rewriter) {
490 if (op.getRegion().empty())
491 return;
492 IRMapping bodyMapper;
493 for (Operation &o : op.getRegion().front().getOperations()) {
494 if (isa<AIE::EndOp>(o))
495 continue;
496 rewriter.clone(o, bodyMapper);
497 }
498 }
499
500 LogicalResult matchAndRewrite(AIEX::ConfigureOp op,
501 PatternRewriter &rewriter) const override {
502 // A run resolves its callee through the enclosing configure, so the
503 // configure is lowered only once RunOpInlining has expanded its runs.
504 if (!op.getRegion().getOps<AIEX::RunOp>().empty())
505 return failure();
506
507 // Get the referenced device
508 AIE::DeviceOp referencedDevice = op.getReferencedDeviceOp();
509 if (!referencedDevice)
510 return failure();
511
512 // Get the device's symbol name for the section
513 StringRef deviceSymName = referencedDevice.getSymName();
514
515 // Find the parent DeviceOp to insert the section into
516 auto parentDevice = op->getParentOfType<AIE::DeviceOp>();
517 if (!parentDevice)
518 return failure();
519
520 // Check if section already exists (avoid creating duplicates)
521 auto existingSection = dyn_cast_if_present<AIEX::CertSectionOp>(
522 parentDevice.lookupSymbol(deviceSymName));
523 if (existingSection) {
524 // Section already exists, just create load_pdi at call site, reusing the
525 // PDI ID already assigned to this section (or assigning a new one).
526 uint32_t pdiId = getOrAssignPdiId(parentDevice, deviceSymName);
527
528 rewriter.setInsertionPoint(op);
529 AIEX::CertLoadPdiOp::create(
530 rewriter, op.getLoc(), rewriter.getUI32IntegerAttr(pdiId),
531 FlatSymbolRefAttr::get(rewriter.getContext(), deviceSymName));
532
533 // Clone configure body operations after the load_pdi
534 cloneConfigureBody(op, rewriter);
535
536 rewriter.eraseOp(op);
537 return success();
538 }
539
540 // Create cert.section with the device symbol name
541 rewriter.setInsertionPoint(parentDevice.getBody()->getTerminator());
542 auto sectionOp = AIEX::CertSectionOp::create(
543 rewriter, op.getLoc(), rewriter.getStringAttr(deviceSymName));
544
545 // Create the section body with a page containing a job
546 Block *sectionBlock = new Block();
547 sectionOp.getBody().push_back(sectionBlock);
548 rewriter.setInsertionPointToStart(sectionBlock);
549
550 // Create page within section
551 auto pageOp = AIEX::CertPageOp::create(rewriter, op.getLoc());
552 Block *pageBlock = new Block();
553 pageOp.getBody().push_back(pageBlock);
554 rewriter.setInsertionPointToStart(pageBlock);
555
556 // Create job within page - assign unique job ID across all devices
557 // Find the maximum job ID in the parent device
558 uint32_t maxJobId = 0;
559 parentDevice.walk([&](AIEX::CertJobOp certJobOp) {
560 maxJobId = std::max(maxJobId, certJobOp.getJobId());
561 });
562 uint32_t sectionJobId = maxJobId + 1;
563
564 auto jobOp = AIEX::CertJobOp::create(rewriter, op.getLoc(), sectionJobId);
565 Block *jobBlock = new Block();
566 jobOp.getBody().push_back(jobBlock);
567 rewriter.setInsertionPointToStart(jobBlock);
568
569 // Find the "configure" sequence content from the referenced device
570 // It could be either:
571 // 1. Still the generated configuration sequence (if that device hasn't
572 // been processed yet)
573 // 2. Already converted to cert.page/cert.job (if that device was processed
574 // first)
575
576 AIE::RuntimeSequenceOp configureSeq =
577 findGeneratedConfigure(referencedDevice);
578
579 if (configureSeq) {
580 // Clone operations from the "configure" runtime_sequence. An empty
581 // sequence (`{}`) has no block, and leaves the section job empty.
582 IRMapping mapper;
583 if (!configureSeq.getRegion().empty()) {
584 for (Operation &o : configureSeq.getRegion().front().getOperations()) {
585 if (isa<AIE::EndOp>(o))
586 continue;
587 rewriter.clone(o, mapper);
588 }
589 }
590 } else {
591 // "configure" was already converted - find the first cert.page
592 // (configuration page)
593 AIEX::CertPageOp configPage = nullptr;
594 for (auto &op : referencedDevice.getBody()->getOperations()) {
595 if (auto page = dyn_cast<AIEX::CertPageOp>(op)) {
596 configPage = page;
597 break; // Take first page (configure)
598 }
599 }
600
601 if (configPage) {
602 // Clone operations from the config page's job
603 IRMapping mapper;
604 for (auto &op : configPage.getBody().front().getOperations()) {
605 if (auto job = dyn_cast<AIEX::CertJobOp>(op)) {
606 for (Operation &jobOp : job.getBody().front().getOperations()) {
607 if (isa<AIE::EndOp>(jobOp))
608 continue;
609 rewriter.clone(jobOp, mapper);
610 }
611 break; // Only clone first job
612 }
613 }
614 }
615 }
616
617 // Ensure terminators
618 AIEX::CertJobOp::ensureTerminator(jobOp.getBody(), rewriter, op.getLoc());
619 AIEX::CertPageOp::ensureTerminator(pageOp.getBody(), rewriter, op.getLoc());
620 AIEX::CertSectionOp::ensureTerminator(sectionOp.getBody(), rewriter,
621 op.getLoc());
622
623 // At the configure call site, replace with load_pdi, reusing the PDI ID
624 // already assigned to this device if present (or assigning a new one).
625 uint32_t pdiId = getOrAssignPdiId(parentDevice, deviceSymName);
626
627 rewriter.setInsertionPoint(op);
628 AIEX::CertLoadPdiOp::create(
629 rewriter, op.getLoc(), rewriter.getUI32IntegerAttr(pdiId),
630 FlatSymbolRefAttr::get(rewriter.getContext(), deviceSymName));
631
632 // Clone configure body operations after the load_pdi
633 // Operations that reference external values were not cloned into the
634 // section, so we clone them here into the main control flow
635 cloneConfigureBody(op, rewriter);
636
637 // Erase the original configure op
638 rewriter.eraseOp(op);
639 return success();
640 }
641};
642
643// The blockwrite that loads the BD an address_patch patches: the nearest
644// preceding blockwrite, when it targets the patched BD.
645static AIEX::NpuBlockWriteOp
646findPatchedBlockWrite(AIEX::NpuAddressPatchOp patch) {
647 const auto &tm = AIE::getTargetModel(patch);
648 uint32_t addr = patch.getAddr();
649 int col = tm.getColumnFromAddress(addr);
650 int row = tm.getRowFromAddress(addr);
651 if (!tm.isValidTile({col, row}))
652 return {};
653 for (Block::iterator it(patch); it != patch->getBlock()->begin();) {
654 auto blockWrite = dyn_cast<AIEX::NpuBlockWriteOp>(*--it);
655 if (!blockWrite)
656 continue;
657 if (blockWrite.getAddress() + tm.getDmaBdAddressOffset(col, row) != addr)
658 return {};
659 return blockWrite;
660 }
661 return {};
662}
663
664// apply_offset_57 names an argument by its first 32-bit register, 2 * arg_idx,
665// in a 16-bit field, and reserves the index 0xFFFF for the control code's own
666// address. So the largest usable arg_idx is the one whose double still fits.
667static constexpr uint32_t kMaxApplyOffsetArgIdx = 0x7FFF;
668
669// An address_patch writes buffer address + arg_plus into a BD register, but
670// cert.apply_offset_57 adds the buffer address to the BD template in memory.
671// So before conversion the patched template word must hold arg_plus, and the
672// template must belong to its blockwrite alone: dma-to-npu shares identical
673// templates between BDs, and a shared one would accumulate every BD's address.
674static LogicalResult prepareAddressPatchTemplates(AIE::DeviceOp device) {
675 LogicalResult result = success();
676 SymbolTable symbols(device);
677 // Count each global's symbol uses once, then keep the counts current as
678 // getters are added and erased. Asking SymbolTable per patch walks the whole
679 // device each time, which is quadratic in the number of patched BDs. With no
680 // counts (an op with unknown symbol uses), every patched template is copied.
681 std::optional<llvm::DenseMap<StringAttr, unsigned>> symbolUseCounts;
682 if (auto uses = SymbolTable::getSymbolUses(&device.getRegion())) {
683 symbolUseCounts.emplace();
684 for (const SymbolTable::SymbolUse &use : *uses)
685 ++(*symbolUseCounts)[use.getSymbolRef().getRootReference()];
686 }
687 SmallVector<AIEX::NpuAddressPatchOp> patches;
688 device.walk([&](AIEX::NpuAddressPatchOp patch) { patches.push_back(patch); });
689 for (AIEX::NpuAddressPatchOp patch : patches) {
690 std::optional<uint32_t> argIdx = patch.getArgIdx();
691 if (argIdx && *argIdx > kMaxApplyOffsetArgIdx) {
692 patch.emitError("arg_idx ")
693 << *argIdx << " does not fit apply_offset_57's 16-bit argument "
694 << "offset; the largest is " << kMaxApplyOffsetArgIdx;
695 result = failure();
696 continue;
697 }
698 AIEX::NpuBlockWriteOp blockWrite = findPatchedBlockWrite(patch);
699 if (!blockWrite)
700 continue;
701 auto getGlobal = dyn_cast_or_null<memref::GetGlobalOp>(
702 blockWrite.getData().getDefiningOp());
703 if (!getGlobal)
704 continue;
705 auto global = symbols.lookup<memref::GlobalOp>(getGlobal.getName());
706 if (!global)
707 continue;
708 std::optional<Attribute> initialValue = global.getInitialValue();
709 auto words = initialValue ? dyn_cast<DenseIntElementsAttr>(*initialValue)
710 : DenseIntElementsAttr();
711 if (!words)
712 continue;
713
714 if (!patch.getArgIdx()) {
715 patch.emitError("cert lowering requires an address_patch with arg_idx");
716 result = failure();
717 continue;
718 }
719 APInt argPlus;
720 if (!matchPattern(patch.getArgPlus(), m_ConstantInt(&argPlus))) {
721 patch.emitError("cert lowering requires a constant arg_plus: "
722 "apply_offset_57 cannot add a runtime offset");
723 result = failure();
724 continue;
725 }
726 // An i32 arg_plus is unsigned, so any value fits; a negative i64 has 64
727 // active bits and is rejected.
728 if (argPlus.getActiveBits() > 32) {
729 patch.emitError("arg_plus ")
730 << argPlus.getSExtValue()
731 << " does not fit the BD's 32-bit address word";
732 result = failure();
733 continue;
734 }
735 unsigned word = (patch.getAddr() - blockWrite.getAddress()) / 4;
736 if (word >= words.getNumElements())
737 continue;
738
739 // Give this blockwrite a private template if anything else uses it,
740 // whether through another getter or through this one (after CSE).
741 if (!symbolUseCounts ||
742 symbolUseCounts->lookup(global.getSymNameAttr()) != 1 ||
743 !getGlobal->hasOneUse()) {
744 OpBuilder builder(global);
745 auto copy = cast<memref::GlobalOp>(builder.clone(*global));
746 // insert renames the copy, so count it under its new name.
747 StringAttr copyName = symbols.insert(copy);
748 OpBuilder atBlockWrite(blockWrite);
749 auto privateGet =
750 memref::GetGlobalOp::create(atBlockWrite, getGlobal.getLoc(),
751 getGlobal.getType(), copy.getSymName());
752 blockWrite.getDataMutable().assign(privateGet);
753 if (symbolUseCounts)
754 (*symbolUseCounts)[copyName] = 1;
755 if (getGlobal->use_empty()) {
756 if (symbolUseCounts)
757 --(*symbolUseCounts)[global.getSymNameAttr()];
758 getGlobal->erase();
759 }
760 global = copy;
761 }
762
763 auto values = llvm::to_vector(words.getValues<APInt>());
764 values[word] = argPlus.zextOrTrunc(values[word].getBitWidth());
765 global.setInitialValueAttr(
766 DenseIntElementsAttr::get(words.getType(), values));
767 }
768 return result;
769}
770
771struct NpuAddressPatchToCertApplyOffset57
772 : OpConversionPattern<AIEX::NpuAddressPatchOp> {
773 using OpConversionPattern::OpConversionPattern;
774
775 LogicalResult
776 matchAndRewrite(AIEX::NpuAddressPatchOp op, OpAdaptor adaptor,
777 ConversionPatternRewriter &rewriter) const override {
778 AIEX::NpuBlockWriteOp blockWriteOp = findPatchedBlockWrite(op);
779 std::optional<uint32_t> argIdx = op.getArgIdx();
780 if (!blockWriteOp || !argIdx)
781 return failure();
782 auto getGlobalOp =
783 dyn_cast<memref::GetGlobalOp>(blockWriteOp.getData().getDefiningOp());
784 if (!getGlobalOp)
785 return failure();
786 rewriter.setInsertionPoint(blockWriteOp);
787 rewriter.replaceOpWithNewOp<AIEX::CertApplyOffset57Op>(
788 op, getGlobalOp.getName(), 1, *argIdx);
789 return success();
790 }
791};
792
793struct MergeConsecutiveCertUcDmaWriteDesSyncOps
794 : OpRewritePattern<AIEX::CertUcDmaWriteDesSyncOp> {
795 // symbolTable is the device's. useCounts holds the symbol uses in the device,
796 // counted once up front: a merge erases the earlier chain and its one
797 // enqueue and moves no other chain reference.
798 MergeConsecutiveCertUcDmaWriteDesSyncOps(
799 MLIRContext *context, SymbolTable &symbolTable,
800 llvm::DenseMap<StringAttr, unsigned> &useCounts)
801 : OpRewritePattern(context), symbolTable(symbolTable),
802 useCounts(useCounts) {}
803
804 LogicalResult matchAndRewrite(AIEX::CertUcDmaWriteDesSyncOp op,
805 PatternRewriter &rewriter) const override {
806 // Fusing the two enqueues sinks the earlier one to the later one's position
807 // in the job, so every op scanned over is an op the earlier DMA is moved
808 // past. Only ops with no architectural effect at all may be crossed; this
809 // is an allowlist rather than a denylist so a cert op added to this dialect
810 // later blocks the merge by default instead of silently becoming
811 // reorderable with respect to a DMA enqueue. cert.nop is the only such op
812 // today: it emits padding and carries no ordering, sync or side effect.
813 auto isTransparentToMerge = [](Operation *o) {
814 return isa<AIEX::CertNopOp>(o);
815 };
816
817 // Get the previous operation in the block
818 Block::iterator it(op);
819 AIEX::CertUcDmaWriteDesSyncOp prevWriteDesSync = nullptr;
820 while (it != op->getBlock()->begin() && !prevWriteDesSync) {
821 --it;
822 Operation *prevOp = &*it;
823 prevWriteDesSync = dyn_cast<AIEX::CertUcDmaWriteDesSyncOp>(prevOp);
824 if (!prevWriteDesSync && !isTransparentToMerge(prevOp))
825 return failure();
826 }
827 if (!prevWriteDesSync)
828 return failure();
829
830 // find the uc_dma_chain
831 StringRef sym_name = op.getSymbol();
832 StringRef prev_sym_name = prevWriteDesSync.getSymbol();
833 auto chain = symbolTable.lookup<AIEX::CertUcDmaChainOp>(sym_name);
834 auto prevChain = symbolTable.lookup<AIEX::CertUcDmaChainOp>(prev_sym_name);
835 if (!chain || !prevChain)
836 return failure();
837
838 // The merge rewrites @chain's BD list in place and deletes @prevChain, so
839 // both symbols must be private to this pair of enqueues. Cert IR that is
840 // hand-authored rather than lowered from npu ops may enqueue one chain from
841 // several places: folding into a shared @chain would silently change those
842 // other enqueues, and erasing a shared @prevChain would leave a dangling
843 // symbol reference that neither the verifier nor the page cost model
844 // notices. Decline the merge instead.
845 auto isSingleUse = [&](AIEX::CertUcDmaChainOp c) {
846 return useCounts.lookup(c.getSymNameAttr()) == 1;
847 };
848 if (!isSingleUse(chain) || !isSingleUse(prevChain))
849 return failure();
850
851 // Compute the size of the current and previous chains. If their combined
852 // data size is greater than the cert page size, then we cannot merge them.
853 //
854 // A chain costs 16 bytes of descriptor per BD on top of the BD's payload --
855 // the same accounting updateCostForOp (the page splitter's authoritative
856 // cost model) uses. Charging payload only under-reports a chain by 16 bytes
857 // per BD, which for many small BDs is most of its real size.
858 auto chainSize = [](AIEX::CertUcDmaChainOp c) {
859 uint32_t size = 0;
860 for (auto bdOp : c.getBody().front().getOps<AIEX::CertUcDmaBdOp>())
861 size += bdOp.getLength() * sizeof(int) + 16; // payload + bd descriptor
862 return size;
863 };
864 if ((chainSize(chain) + chainSize(prevChain)) >= cert_page_size)
865 return failure();
866
867 IRMapping map;
868 rewriter.setInsertionPointToStart(&chain.getBody().front());
869 for (auto &o : prevChain.getBody().front().getOperations()) {
870 auto bdOp = dyn_cast<AIEX::CertUcDmaBdOp>(o);
871 if (!bdOp)
872 continue;
873 AIEX::CertUcDmaBdOp::create(
874 rewriter, bdOp.getLoc(), bdOp.getRemoteAddress(),
875 bdOp.getLocalAddress(), bdOp.getLength(), true);
876 }
877 useCounts.erase(prevChain.getSymNameAttr());
878 symbolTable.remove(prevChain);
879 rewriter.eraseOp(prevChain);
880 rewriter.eraseOp(prevWriteDesSync);
881 return success();
882 }
883
884 SymbolTable &symbolTable;
885 llvm::DenseMap<StringAttr, unsigned> &useCounts;
886};
887
888struct SplitNpuBlockWriteOpPattern : OpRewritePattern<AIEX::NpuBlockWriteOp> {
889 // The pattern runs over the module, so it keeps a table per device and adds
890 // the globals it creates to it.
891 SplitNpuBlockWriteOpPattern(MLIRContext *context,
892 SymbolTableCollection &symbolTables)
893 : OpRewritePattern(context), symbolTables(symbolTables) {}
894
895 LogicalResult matchAndRewrite(AIEX::NpuBlockWriteOp op,
896 PatternRewriter &rewriter) const override {
897
898 memref::GetGlobalOp dataOperand =
899 dyn_cast_or_null<memref::GetGlobalOp>(op.getData().getDefiningOp());
900 if (!dataOperand)
901 return failure();
902
903 MemRefType dataType = cast<MemRefType>(dataOperand.getResult().getType());
904 uint32_t dataSize = dataType.getNumElements();
905
906 uint32_t dataSizeBytes = dataSize * sizeof(int);
907 if (dataSizeBytes < cert_page_size)
908 return failure();
909
910 auto loc = op.getLoc();
911
912 // Calculate split point (split roughly in half)
913 uint32_t splitElements = dataSize / 2;
914 uint32_t firstChunkSize = splitElements;
915 uint32_t secondChunkSize = dataSize - splitElements;
916
917 // Find the original memref.global operation
918 auto deviceOp = op->getParentOfType<AIE::DeviceOp>();
919 SymbolTable &symbolTable = symbolTables.getSymbolTable(deviceOp);
920 auto originalGlobal =
921 symbolTable.lookup<memref::GlobalOp>(dataOperand.getName());
922 if (!originalGlobal)
923 return failure();
924
925 // Get the original data attribute
926 auto originalData = originalGlobal.getInitialValue();
927 if (!originalData)
928 return failure();
929
930 auto denseData = dyn_cast<DenseIntElementsAttr>(*originalData);
931 if (!denseData)
932 return failure();
933
934 // Split the data into two chunks
935 auto dataValues = denseData.getValues<APInt>();
936 std::vector<APInt> firstChunkData(dataValues.begin(),
937 dataValues.begin() + firstChunkSize);
938 std::vector<APInt> secondChunkData(dataValues.begin() + firstChunkSize,
939 dataValues.end());
940
941 // Create new global operations for the split data
942 auto elementType = rewriter.getI32Type();
943 auto firstChunkType = MemRefType::get({firstChunkSize}, elementType);
944 auto secondChunkType = MemRefType::get({secondChunkSize}, elementType);
945 TensorType firstTensorType =
946 RankedTensorType::get({firstChunkSize}, elementType);
947 TensorType secondTensorType =
948 RankedTensorType::get({secondChunkSize}, elementType);
949
950 auto firstChunkAttr =
951 DenseIntElementsAttr::get(firstTensorType, firstChunkData);
952 auto secondChunkAttr =
953 DenseIntElementsAttr::get(secondTensorType, secondChunkData);
954
955 // Generate unique names for the new globals
956 std::string firstName = dataOperand.getName().str() + "_split_0";
957 std::string secondName = dataOperand.getName().str() + "_split_1";
958
959 // Ensure unique names
960 int counter = 0;
961 while (symbolTable.lookup(firstName)) {
962 firstName =
963 dataOperand.getName().str() + "_split_0_" + std::to_string(counter++);
964 }
965 counter = 0;
966 while (symbolTable.lookup(secondName)) {
967 secondName =
968 dataOperand.getName().str() + "_split_1_" + std::to_string(counter++);
969 }
970
971 // Create the new global operations
972 rewriter.setInsertionPoint(originalGlobal);
973 auto firstGlobal = memref::GlobalOp::create(
974 rewriter, loc, firstName, rewriter.getStringAttr("private"),
975 firstChunkType, firstChunkAttr, true, nullptr);
976 symbolTable.insert(firstGlobal);
977
978 auto secondGlobal = memref::GlobalOp::create(
979 rewriter, loc, secondName, rewriter.getStringAttr("private"),
980 secondChunkType, secondChunkAttr, true, nullptr);
981 symbolTable.insert(secondGlobal);
982
983 // Create get_global operations for the new data
984 rewriter.setInsertionPoint(op);
985
986 auto firstGetGlobal =
987 memref::GetGlobalOp::create(rewriter, loc, firstChunkType, firstName);
988 auto secondGetGlobal =
989 memref::GetGlobalOp::create(rewriter, loc, secondChunkType, secondName);
990
991 uint32_t baseAddr = op.getAddress();
992
993 AIEX::NpuBlockWriteOp::create(rewriter, loc, baseAddr,
994 firstGetGlobal.getResult(), nullptr, nullptr,
995 nullptr);
996
997 AIEX::NpuBlockWriteOp::create(rewriter, loc, baseAddr + firstChunkSize * 4,
998 secondGetGlobal.getResult(), nullptr, nullptr,
999 nullptr);
1000
1001 // Replace the original operation
1002 rewriter.eraseOp(op);
1003
1004 LLVM_DEBUG(llvm::outs()
1005 << "Split NpuBlockWriteOp with data size: " << dataSizeBytes
1006 << " bytes into chunks of " << firstChunkSize << " and "
1007 << secondChunkSize << " elements\n");
1008
1009 return success();
1010 }
1011
1012 SymbolTableCollection &symbolTables;
1013};
1014
1015// Rewrite each tile- or buffer-relative write32, maskwrite32, maskpoll and
1016// blockwrite to the absolute address it targets, so that splitting,
1017// address_patch matching and lowering all use the raw address. This runs before
1018// configure sequences are cloned into another device, where the buffer symbol
1019// would no longer resolve.
1020static LogicalResult resolveRelativeAddresses(AIE::DeviceOp device) {
1021 AIE::NamedOpTable names(device);
1022 LogicalResult result = success();
1023 auto isRelative = [](auto op) {
1024 return op.getBuffer() || (op.getColumn() && op.getRow());
1025 };
1026 auto dropRelative = [](auto op) {
1027 op.removeBufferAttr();
1028 op.removeColumnAttr();
1029 op.removeRowAttr();
1030 };
1031 // These take the address as an operand. A runtime address is left to the
1032 // lowering, which rejects it.
1033 auto resolveOperand = [&](auto op, bool warnOnTileBits) {
1034 if (!isRelative(op))
1035 return;
1036 std::optional<uint32_t> offset =
1037 AIEX::getConstantIntOperand(op.getAddress());
1038 if (!offset)
1039 return;
1040 std::optional<uint32_t> address = op.getAbsoluteAddress(&names);
1041 if (!address) {
1042 result = failure();
1043 return;
1044 }
1045 std::optional<uint32_t> col = op.getColumn();
1046 std::optional<uint32_t> row = op.getRow();
1047 if (warnOnTileBits && col && row)
1048 warnOnMismatchedTileBits(op, *offset, *col, *row);
1049 OpBuilder builder(op);
1050 Value absolute = arith::ConstantOp::create(
1051 builder, op.getLoc(),
1052 builder.getI32IntegerAttr(static_cast<int32_t>(*address)));
1053 op.getAddressMutable().set(absolute);
1054 dropRelative(op);
1055 };
1056 device.walk([&](Operation *op) {
1057 if (auto write = dyn_cast<AIEX::NpuWrite32Op>(op)) {
1058 resolveOperand(write, /*warnOnTileBits=*/true);
1059 } else if (auto write = dyn_cast<AIEX::NpuMaskWrite32Op>(op)) {
1060 resolveOperand(write, /*warnOnTileBits=*/true);
1061 } else if (auto poll = dyn_cast<AIEX::NpuMaskPollOp>(op)) {
1062 resolveOperand(poll, /*warnOnTileBits=*/false);
1063 } else if (auto write = dyn_cast<AIEX::NpuBlockWriteOp>(op)) {
1064 if (!isRelative(write))
1065 return;
1066 std::optional<uint32_t> address = write.getAbsoluteAddress(&names);
1067 if (!address) {
1068 result = failure();
1069 return;
1070 }
1071 write.setAddress(*address);
1072 dropRelative(write);
1073 }
1074 });
1075 return result;
1076}
1077
1078struct AIENpuToCertPass
1079 : xilinx::AIEX::impl::AIENpuToCertBase<AIENpuToCertPass> {
1080 void runOnOperation() override {
1081 auto moduleOp = getOperation();
1082 if (failed(AIE::inlineWriteConfigs(moduleOp)))
1083 return signalPassFailure();
1084
1085 // Collect all devices
1086 llvm::SmallVector<AIE::DeviceOp, 4> devices;
1087 for (auto &op : moduleOp.getBody()->getOperations()) {
1088 if (auto deviceOp = dyn_cast<AIE::DeviceOp>(op)) {
1089 devices.push_back(deviceOp);
1090 }
1091 }
1092
1093 bool resolved = true;
1094 for (auto dev : devices)
1095 resolved &= succeeded(resolveRelativeAddresses(dev));
1096 if (!resolved)
1097 return signalPassFailure();
1098
1099 for (auto dev : devices)
1100 tagConfigureByName(dev);
1101
1102 // Process main device first (named "main" or specified by --device-name)
1103 // so referenced devices' "configure" sequences can be found before they
1104 // get converted to cert.job
1105 AIE::DeviceOp mainDevice = nullptr;
1106 for (auto dev : devices) {
1107 if (dev.getSymName() == deviceName) {
1108 mainDevice = dev;
1109 break;
1110 }
1111 }
1112
1113 if (!mainDevice) {
1114 moduleOp.emitError("no device found matching --device-name \"")
1115 << deviceName << "\"";
1116 signalPassFailure();
1117 return;
1118 }
1119
1120 migrateGlobalsIntoMainDevice(mainDevice, devices);
1121 processDevice(mainDevice);
1122
1123 // Then process other devices
1124 for (auto dev : devices) {
1125 if (dev != mainDevice) {
1126 processDevice(dev);
1127 }
1128 }
1129
1130 // Remove absorbed devices (keep only main device)
1131 // Referenced devices have been absorbed as cert.sections, so remove them
1132 llvm::SmallVector<AIE::DeviceOp, 4> devicesToRemove;
1133 for (auto dev : devices) {
1134 if (dev != mainDevice) {
1135 devicesToRemove.push_back(dev);
1136 }
1137 }
1138
1139 for (auto dev : devicesToRemove) {
1140 dev.erase();
1141 }
1142 }
1143
1144 // Move globals into the surviving device and rename payload references before
1145 // cloning configure bodies. Reserve device names for sections, including when
1146 // renaming the main device's globals: processDevice skips names that resolve.
1147 void migrateGlobalsIntoMainDevice(AIE::DeviceOp mainDevice,
1148 ArrayRef<AIE::DeviceOp> devices) {
1149 auto isDeviceName = [&](StringRef candidate) {
1150 return llvm::any_of(devices, [&](AIE::DeviceOp device) {
1151 return device.getSymName() == candidate;
1152 });
1153 };
1154
1155 // Names and payload uses are indexed once per device and kept current
1156 // below; scanning the device per global is quadratic in the globals.
1157 DeviceNames mainNames = collectNames(mainDevice);
1158 std::optional<PayloadUses> mainUses;
1159 for (auto global : llvm::to_vector(mainDevice.getOps<memref::GlobalOp>())) {
1160 StringRef oldName = global.getSymName();
1161 if (!isDeviceName(oldName))
1162 continue;
1163 std::string newName;
1164 unsigned counter = 0;
1165 do
1166 newName = oldName.str() + "_" + std::to_string(counter++);
1167 while (mainNames.contains(newName) || isDeviceName(newName));
1168 if (!mainUses)
1169 mainUses = collectPayloadUses(mainDevice);
1170 renamePayloadUses(*mainUses, oldName, newName);
1171 removeName(mainNames, oldName);
1172 ++mainNames[newName];
1173 global.setSymName(newName);
1174 }
1175
1176 for (auto dev : devices) {
1177 if (dev == mainDevice)
1178 continue;
1179 DeviceNames devNames = collectNames(dev);
1180 PayloadUses devUses = collectPayloadUses(dev);
1181 auto globals = llvm::to_vector(dev.getOps<memref::GlobalOp>());
1182 for (auto global : globals) {
1183 StringRef oldName = global.getSymName();
1184 std::string newName = oldName.str();
1185 unsigned counter = 0;
1186 // Avoid a temporary collision with another source global: rewriting
1187 // its uses later would otherwise redirect both payloads to one symbol.
1188 auto taken = [&](StringRef candidate) {
1189 return mainNames.contains(candidate) || isDeviceName(candidate) ||
1190 (candidate != oldName && devNames.contains(candidate));
1191 };
1192 while (taken(newName))
1193 newName = oldName.str() + "_" + std::to_string(counter++);
1194 if (newName != oldName) {
1195 renamePayloadUses(devUses, oldName, newName);
1196 global.setSymName(newName);
1197 }
1198 removeName(devNames, oldName);
1199 ++mainNames[newName];
1200 global->moveBefore(mainDevice.getBody(), mainDevice.getBody()->begin());
1201 }
1202 }
1203 }
1204
1205 // The sym_names of a device's body ops, with their counts. The device
1206 // verifier rejects duplicates among all of them, including SSA ops such as
1207 // aie.buffer that the symbol table does not index.
1208 using DeviceNames = llvm::StringMap<unsigned>;
1209 static DeviceNames collectNames(AIE::DeviceOp dev) {
1210 DeviceNames names;
1211 for (Operation &op : dev.getBody()->getOperations())
1212 if (auto symName =
1213 op.getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()))
1214 ++names[symName.getValue()];
1215 return names;
1216 }
1217 static void removeName(DeviceNames &names, StringRef name) {
1218 auto it = names.find(name);
1219 if (it != names.end() && --it->second == 0)
1220 names.erase(it);
1221 }
1222
1223 // The ops that reference a payload global, by the name they reference. A
1224 // generic symbol-use rewrite would also rename same-named device references,
1225 // such as load_pdi's device_ref, which resolve against the module. Nested
1226 // symbol tables resolve their own names, so their uses are left alone.
1227 using PayloadUses = llvm::StringMap<SmallVector<Operation *>>;
1228 static PayloadUses collectPayloadUses(AIE::DeviceOp dev) {
1229 PayloadUses uses;
1230 dev.walk<WalkOrder::PreOrder>([&](Operation *op) {
1231 if (op != dev && op->hasTrait<OpTrait::SymbolTable>())
1232 return WalkResult::skip();
1233 if (auto get = dyn_cast<memref::GetGlobalOp>(op))
1234 uses[get.getName()].push_back(op);
1235 else if (auto bd = dyn_cast<AIEX::CertUcDmaBdOp>(op))
1236 uses[bd.getRemoteAddress()].push_back(op);
1237 else if (auto patch = dyn_cast<AIEX::CertApplyOffset57Op>(op))
1238 uses[patch.getSymbol()].push_back(op);
1239 return WalkResult::advance();
1240 });
1241 return uses;
1242 }
1243
1244 // Point the indexed references to `oldName` at `newName`.
1245 static void renamePayloadUses(PayloadUses &uses, StringRef oldName,
1246 StringRef newName) {
1247 auto it = uses.find(oldName);
1248 if (it == uses.end())
1249 return;
1250 SmallVector<Operation *> ops = std::move(it->second);
1251 uses.erase(it);
1252 for (Operation *op : ops) {
1253 auto newRef = FlatSymbolRefAttr::get(op->getContext(), newName);
1254 if (auto get = dyn_cast<memref::GetGlobalOp>(op))
1255 get.setNameAttr(newRef);
1256 else if (auto bd = dyn_cast<AIEX::CertUcDmaBdOp>(op))
1257 bd.setRemoteAddressAttr(newRef);
1258 else if (auto patch = dyn_cast<AIEX::CertApplyOffset57Op>(op))
1259 patch.setSymbolAttr(newRef);
1260 }
1261 llvm::append_range(uses[newName], ops);
1262 }
1263
1264 // Absorb each device that an npu.load_pdi in `currentDevice` names as a
1265 // same-named cert.section built from the device's configuration.
1266 LogicalResult absorbLoadedDevices(AIE::DeviceOp currentDevice,
1267 ModuleOp moduleOp) {
1268 // Collect npu.load_pdi operations, before they become cert.load_pdi. An
1269 // absorbed configuration can load further devices, so its loads are
1270 // collected too.
1271 llvm::SmallVector<AIEX::NpuLoadPdiOp, 4> loads;
1272 auto collectLoads = [&](Operation *root) {
1273 root->walk([&](AIEX::NpuLoadPdiOp loadPdiOp) {
1274 if (loadPdiOp.getDeviceRef())
1275 loads.push_back(loadPdiOp);
1276 });
1277 };
1278 collectLoads(currentDevice);
1279
1280 OpBuilder builder(&getContext());
1281 // Worklist in collection order: absorbing a device appends its loads, so
1282 // `loads` can grow (and reallocate) while it is being walked.
1283 size_t next = 0;
1284 while (next < loads.size()) {
1285 AIEX::NpuLoadPdiOp load = loads[next++];
1286 std::optional<StringRef> deviceRef = load.getDeviceRef();
1287 if (!deviceRef)
1288 continue;
1289 StringRef refSymName = *deviceRef;
1290 // Skip if section already exists
1291 Operation *existing = AIE::lookupNamedOpIn(currentDevice, refSymName);
1292 if (isa_and_present<AIEX::CertSectionOp>(existing))
1293 continue;
1294
1295 // Find referenced device
1296 AIE::DeviceOp refDevice = nullptr;
1297 for (auto &op : moduleOp.getBody()->getOperations()) {
1298 if (auto dev = dyn_cast<AIE::DeviceOp>(op)) {
1299 if (dev.getSymName() == refSymName) {
1300 refDevice = dev;
1301 break;
1302 }
1303 }
1304 }
1305
1306 if (!refDevice)
1307 continue;
1308
1309 // Find the generated configuration sequence
1310 AIE::RuntimeSequenceOp configureSeq = findGeneratedConfigure(refDevice);
1311
1312 if (!configureSeq)
1313 continue;
1314
1315 // Any other symbol of that name would leave the load without its
1316 // section.
1317 if (existing) {
1318 load.emitError("cannot absorb device @")
1319 << refSymName << " as a cert.section: @" << refSymName
1320 << " is already defined by '" << existing->getName() << "'";
1321 return failure();
1322 }
1323
1324 // Create cert.section in current device
1325 builder.setInsertionPoint(currentDevice.getBody()->getTerminator());
1326 auto sectionOp = AIEX::CertSectionOp::create(
1327 builder, configureSeq.getLoc(), builder.getStringAttr(refSymName));
1328
1329 Block *sectionBlock = new Block();
1330 sectionOp.getBody().push_back(sectionBlock);
1331 builder.setInsertionPointToStart(sectionBlock);
1332
1333 // Create page
1334 auto pageOp = AIEX::CertPageOp::create(builder, configureSeq.getLoc());
1335 Block *pageBlock = new Block();
1336 pageOp.getBody().push_back(pageBlock);
1337 builder.setInsertionPointToStart(pageBlock);
1338
1339 // Get unique job ID
1340 uint32_t maxJobId = 0;
1341 currentDevice.walk([&](AIEX::CertJobOp certJobOp) {
1342 maxJobId = std::max(maxJobId, certJobOp.getJobId());
1343 });
1344
1345 // Create job
1346 auto jobOp =
1347 AIEX::CertJobOp::create(builder, configureSeq.getLoc(), maxJobId + 1);
1348
1349 // Clone configure sequence body into job
1350 IRMapping mapper;
1351 configureSeq.getRegion().cloneInto(&jobOp.getBody(), mapper);
1352
1353 // Ensure terminators
1354 AIEX::CertJobOp::ensureTerminator(jobOp.getBody(), builder,
1355 configureSeq.getLoc());
1356 AIEX::CertPageOp::ensureTerminator(pageOp.getBody(), builder,
1357 configureSeq.getLoc());
1358 AIEX::CertSectionOp::ensureTerminator(sectionOp.getBody(), builder,
1359 configureSeq.getLoc());
1360 collectLoads(jobOp);
1361 }
1362 return success();
1363 }
1364
1365 void processDevice(AIE::DeviceOp currentDevice) {
1366 auto moduleOp = currentDevice->getParentOfType<ModuleOp>();
1367
1368 // Inline RunOps and convert ConfigureOps to cert.section + cert.load_pdi.
1369 // ConfigureOpToCertSection waits for the runs of a configure to be inlined.
1370 RewritePatternSet p_expand(&getContext());
1371 p_expand.insert<RunOpInlining, ConfigureOpToCertSection>(&getContext());
1372 FrozenRewritePatternSet expandPatterns(std::move(p_expand));
1373
1374 // Absorbing a device can clone in run and configure ops, and expanding
1375 // those can clone in further loads. Repeat until the expansion that follows
1376 // an absorption changes nothing.
1377 bool changed = true;
1378 while (changed) {
1379 // Identify and convert referenced "configure" sequences, before the
1380 // RuntimeSequenceOp conversion runs on other devices.
1381 if (moduleOp && failed(absorbLoadedDevices(currentDevice, moduleOp)))
1382 return signalPassFailure();
1383
1384 if (failed(applyPatternsGreedily(currentDevice, expandPatterns,
1385 GreedyRewriteConfig(), &changed)))
1386 return signalPassFailure();
1387 }
1388
1389 ConversionTarget target(getContext());
1390 target.addIllegalOp<AIE::RuntimeSequenceOp>();
1391
1392 target.addLegalOp<AIEX::CertApplyOffset57Op>();
1393 target.addLegalOp<AIEX::CertJobOp>();
1394 target.addLegalOp<AIEX::CertPageOp>();
1395 target.addLegalOp<AIEX::CertSectionOp>();
1396 target.addLegalOp<AIEX::CertLoadPdiOp>();
1397 target.addLegalOp<AIEX::CertMaskWrite32Op>();
1398 target.addLegalOp<AIEX::CertMaskPoll32Op>();
1399 target.addLegalOp<AIEX::CertUcDmaWriteDesSyncOp>();
1400 target.addLegalOp<AIEX::CertUcDmaChainOp>();
1401 target.addLegalOp<AIEX::CertUcDmaBdOp>();
1402 target.addLegalOp<AIEX::CertWrite32Op>();
1403 target.addLegalOp<AIEX::CertWaitTCTSOp>();
1404 target.addLegalOp<AIEX::ConfigureOp>(); // TODO: Convert in separate pass
1405 target.addLegalDialect<AIE::AIEDialect>();
1406
1407 RewritePatternSet p0(&getContext());
1408 p0.insert<RuntimeSequenceToCertJob>(&getContext());
1409
1410 if (failed(applyPartialConversion(currentDevice, target, std::move(p0))))
1411 return signalPassFailure();
1412
1413 if (failed(prepareAddressPatchTemplates(currentDevice)))
1414 return signalPassFailure();
1415
1416 target.addIllegalOp<AIEX::NpuAddressPatchOp>();
1417
1418 // patch conversion must come before blockwrite conversion
1419 RewritePatternSet p1(&getContext());
1420 p1.insert<NpuAddressPatchToCertApplyOffset57>(&getContext());
1421
1422 if (failed(applyPartialConversion(currentDevice, target, std::move(p1))))
1423 return signalPassFailure();
1424
1425 // Split oversized NpuBlockWriteOps before lowering them to cert ops
1426 {
1427 SymbolTableCollection symbolTables;
1428 RewritePatternSet p(&getContext());
1429 p.insert<SplitNpuBlockWriteOpPattern>(&getContext(), symbolTables);
1430 if (failed(applyPatternsGreedily(getOperation(), std::move(p))))
1431 signalPassFailure();
1432 }
1433
1434 target.addIllegalOp<AIEX::NpuBlockWriteOp>();
1435 target.addIllegalOp<AIEX::NpuBlockWriteValuesOp>();
1436 target.addIllegalOp<AIEX::NpuMaskWrite32Op>();
1437 target.addIllegalOp<AIEX::NpuMaskPollOp>();
1438 target.addIllegalOp<AIEX::NpuSyncOp>();
1439 target.addIllegalOp<AIEX::NpuWrite32Op>();
1440 target.addIllegalOp<AIEX::NpuLoadPdiOp>();
1441
1442 unsigned nextChainId = 0;
1443 SymbolTable symbolTable(currentDevice);
1444 RewritePatternSet p2(&getContext());
1445 p2.insert<NpuBlockWriteToCertUcDma>(&getContext(), nextChainId,
1446 symbolTable);
1447 p2.insert<NpuMaskWrite32ToCertMaskWrite32>(&getContext());
1448 p2.insert<NpuMaskPollToCertMaskPoll32>(&getContext());
1449 p2.insert<NpuWrite32ToCertWrite32>(&getContext());
1450 p2.insert<NpuSyncToCertWaitTCTS>(&getContext());
1451 p2.insert<NpuLoadPdiToCertLoadPdi>(&getContext());
1452
1453 if (failed(applyPartialConversion(currentDevice, target, std::move(p2))))
1454 return signalPassFailure();
1455
1456 // Run the greedy driver with no patterns, purely for its DCE: p2
1457 // leaves each converted blockwrite's memref.get_global (and any constant
1458 // feeding it) dead, since the new op references the global by symbol
1459 // rather than by SSA value. CertJobOp's verifier rejects those ops
1460 RewritePatternSet cleanup(&getContext());
1461 if (failed(applyPatternsGreedily(getOperation(), std::move(cleanup))))
1462 return signalPassFailure();
1463
1464 // Convert referenced devices to cert.sections
1465 // Now that cert.load_pdi ops exist, find referenced devices and convert
1466 // their cert jobs into sections in this device
1467 {
1468 OpBuilder builder(&getContext());
1469
1470 // Find all cert.load_pdi in current device
1471 llvm::SetVector<StringRef> referencedDeviceNames;
1472 currentDevice.walk([&](AIEX::CertLoadPdiOp loadPdiOp) {
1473 StringRef refSymName = loadPdiOp.getSymbol();
1474 if (!currentDevice.lookupSymbol(refSymName))
1475 referencedDeviceNames.insert(refSymName);
1476 });
1477
1478 // For each referenced device, create a section with its cert jobs
1479 for (StringRef refSymName : referencedDeviceNames) {
1480 // Find the referenced device
1481 AIE::DeviceOp refDevice = nullptr;
1482 for (auto &op : moduleOp.getBody()->getOperations()) {
1483 if (auto dev = dyn_cast<AIE::DeviceOp>(op)) {
1484 if (dev.getSymName() == refSymName) {
1485 refDevice = dev;
1486 break;
1487 }
1488 }
1489 }
1490
1491 if (!refDevice)
1492 continue;
1493
1494 // Find all cert.page ops in the referenced device that are direct
1495 // children
1496 llvm::SmallVector<AIEX::CertPageOp, 4> certPages;
1497 for (auto &op : refDevice.getBody()->getOperations()) {
1498 if (auto pageOp = dyn_cast<AIEX::CertPageOp>(op)) {
1499 certPages.push_back(pageOp);
1500 }
1501 }
1502
1503 if (certPages.empty())
1504 continue;
1505
1506 // Create cert.section in current device
1507 builder.setInsertionPoint(currentDevice.getBody()->getTerminator());
1508 auto sectionOp = AIEX::CertSectionOp::create(
1509 builder, refDevice.getLoc(), builder.getStringAttr(refSymName));
1510
1511 Block *sectionBlock = new Block();
1512 sectionOp.getBody().push_back(sectionBlock);
1513
1514 // Clone all cert.page operations into the section
1515 IRMapping mapper;
1516 for (auto pageOp : certPages) {
1517 builder.setInsertionPointToEnd(sectionBlock);
1518 builder.clone(*pageOp.getOperation(), mapper);
1519 }
1520
1521 // Ensure section terminator
1522 AIEX::CertSectionOp::ensureTerminator(sectionOp.getBody(), builder,
1523 refDevice.getLoc());
1524 }
1525 }
1526
1527 // Clean up unused block arguments from cert.job operations
1528 currentDevice.walk([&](AIEX::CertJobOp jobOp) {
1529 Block &jobBlock = jobOp.getBody().front();
1530
1531 // Remove unused block arguments (in reverse order)
1532 for (int i = jobBlock.getNumArguments() - 1; i >= 0; --i) {
1533 BlockArgument arg = jobBlock.getArgument(i);
1534 if (arg.use_empty()) {
1535 jobBlock.eraseArgument(i);
1536 }
1537 }
1538 });
1539 }
1540};
1541
1542} // namespace
1543
1544// The chain a uC DMA push names, synchronous or not.
1545static StringRef pushedChain(Operation &o) {
1546 if (auto push = dyn_cast<AIEX::CertUcDmaWriteDesSyncOp>(o))
1547 return push.getSymbol();
1548 if (auto push = dyn_cast<AIEX::CertUcDmaWriteDesOp>(o))
1549 return push.getSymbol();
1550 return {};
1551}
1552
1553// Registers r0..r7 are local to a job. Splitting a job, or moving some of its
1554// ops into a new job, gives each part its own local registers, so a value
1555// defined in one part is gone in the other. r8..r23 are shared by all jobs and
1556// survive both.
1557static bool isLocalRegister(uint32_t r) { return r < 8; }
1558
1559// The local registers `o` reads (uses) and writes (defs).
1560static void collectLocalRegisterDefsUses(Operation &o,
1561 SmallVectorImpl<uint32_t> &uses,
1562 SmallVectorImpl<uint32_t> &defs) {
1563 auto add = [](SmallVectorImpl<uint32_t> &regs, uint32_t r) {
1564 if (isLocalRegister(r))
1565 regs.push_back(r);
1566 };
1567 if (auto op = dyn_cast<AIEX::CertUcDmaWriteDesOp>(o)) {
1568 add(defs, op.getWaitHandle());
1569 } else if (auto op = dyn_cast<AIEX::CertWaitUcDmaOp>(o)) {
1570 add(uses, op.getWaitHandle());
1571 } else if (auto op = dyn_cast<AIEX::CertRead32Op>(o)) {
1572 add(defs, op.getValue());
1573 } else if (auto op = dyn_cast<AIEX::CertRead32DOp>(o)) {
1574 add(uses, op.getAddress());
1575 add(defs, op.getValue());
1576 } else if (auto op = dyn_cast<AIEX::CertWrite32DOp>(o)) {
1577 if (op.getAddressIsReg())
1578 add(uses, op.getAddress());
1579 if (op.getValueIsReg())
1580 add(uses, op.getValue());
1581 }
1582}
1583
1584// A job touching any local register is never split, which keeps every
1585// definition and use of those registers in one job.
1586static bool jobUsesLocalRegister(AIEX::CertJobOp job) {
1587 SmallVector<uint32_t> uses, defs;
1588 for (Operation &o : job.getBody().front())
1589 collectLocalRegisterDefsUses(o, uses, defs);
1590 return !uses.empty() || !defs.empty();
1591}
1592
1593// The first local register `ops` reads before defining it: its value comes
1594// from earlier in the job, so moving `ops` into a new job would lose it.
1595static std::optional<uint32_t>
1596findLocalRegisterCrossingIn(ArrayRef<Operation *> ops) {
1597 llvm::SmallDenseSet<uint32_t> defined;
1598 SmallVector<uint32_t> uses, defs;
1599 for (Operation *o : ops) {
1600 uses.clear();
1601 defs.clear();
1602 collectLocalRegisterDefsUses(*o, uses, defs);
1603 for (uint32_t r : uses)
1604 if (!defined.contains(r))
1605 return r;
1606 defined.insert(defs.begin(), defs.end());
1607 }
1608 return std::nullopt;
1609}
1610
1611// AIEBU lays down each chain and each payload global once per page, however
1612// many pushes on that page name them, so data is charged once per page.
1614 llvm::DenseSet<Operation *> chains;
1615 llvm::DenseSet<Operation *> payloads;
1616};
1617
1618// A pushed chain's BDs and payloads, charged the first time the page names
1619// them.
1620static void addChainDataCost(StringRef sym_name, const SymbolTable &symbolTable,
1621 uint32_t &data_cost, PageDataSeen &seen) {
1622 auto chain = symbolTable.lookup<AIEX::CertUcDmaChainOp>(sym_name);
1623 if (!chain || !seen.chains.insert(chain).second)
1624 return;
1625 for (auto bdOp : chain.getBody().front().getOps<AIEX::CertUcDmaBdOp>()) {
1626 data_cost += 16; // bd op
1627 auto global = symbolTable.lookup<memref::GlobalOp>(bdOp.getRemoteAddress());
1628 if (!global || !seen.payloads.insert(global).second)
1629 continue;
1630 auto initVal = global.getInitialValue();
1631 if (!initVal)
1632 continue;
1633 auto data = dyn_cast<DenseIntElementsAttr>(*initVal);
1634 if (!data)
1635 continue;
1636 data_cost += data.getNumElements() * 4; // 4 bytes per element
1637 }
1638}
1639
1640// Instruction sizes follow the AIEBU CERT ISA specification so the running
1641// total here matches the bytes emitJob actually produces. Keep the cost model
1642// and emitter in sync when adding a cert op:
1643// an op the emitter can emit but this function ignores is counted as free,
1644// which makes the page look smaller than it is.
1645static void updateCostForOp(Operation &o, const SymbolTable &symbolTable,
1646 uint32_t &text_cost, uint32_t &data_cost,
1647 PageDataSeen &seen) {
1648 // Several distinct op kinds share an encoded instruction size below --
1649 // an instruction-size table, not a copy-paste clone.
1650 // NOLINTBEGIN(bugprone-branch-clone)
1651 if (isa<AIEX::CertLocalBarrierOp>(o)) {
1652 text_cost += 4; // ISA_OPSIZE_LOCAL_BARRIER
1653 } else if (isa<AIEX::CertRemoteBarrierOp>(o)) {
1654 text_cost += 8; // ISA_OPSIZE_REMOTE_BARRIER
1655 } else if (isa<AIEX::CertRelAcqSyncOp>(o)) {
1656 text_cost += 12; // encoded REL_ACQ_SYNC instruction size
1657 } else if (isa<AIEX::CertWaitTCTSOp>(o)) {
1658 text_cost += 8; // wait tct
1659 } else if (isa<AIEX::CertMaskWrite32Op, AIEX::CertMaskPoll32Op>(o)) {
1660 text_cost += 16; // mask write / poll
1661 } else if (isa<AIEX::CertWrite32Op>(o)) {
1662 text_cost += 12; // ISA_OPSIZE_WRITE_32
1663 } else if (isa<AIEX::CertApplyOffset57Op>(o)) {
1664 text_cost += 8; // ISA_OPSIZE_APPLY_OFFSET_57
1665 } else if (isa<AIEX::CertNopOp>(o)) {
1666 text_cost += 4; // ISA_OPSIZE_NOP
1667 } else if (isa<AIEX::CertPreemptOp>(o)) {
1668 text_cost += 8; // ISA_OPSIZE_PREEMPT
1669 } else if (isa<AIEX::CertLoadPdiOp>(o)) {
1670 text_cost += 12; // ISA_OPSIZE_LOAD_PDI
1671 // NOLINTEND(bugprone-branch-clone)
1672 } else if (auto syncOp = dyn_cast<AIEX::CertUcDmaWriteDesSyncOp>(o)) {
1673 text_cost += 4; // ISA_OPSIZE_UC_DMA_WRITE_DES_SYNC
1674 addChainDataCost(syncOp.getSymbol(), symbolTable, data_cost, seen);
1675 } else if (auto desOp = dyn_cast<AIEX::CertUcDmaWriteDesOp>(o)) {
1676 text_cost += 8; // ISA_OPSIZE_UC_DMA_WRITE_DES
1677 addChainDataCost(desOp.getSymbol(), symbolTable, data_cost, seen);
1678 } else if (isa<AIEX::CertWaitUcDmaOp>(o)) {
1679 text_cost += 4; // ISA_OPSIZE_WAIT_UC_DMA
1680 } else if (isa<AIEX::CertRead32Op>(o)) {
1681 text_cost += 8; // ISA_OPSIZE_READ_32
1682 } else if (isa<AIEX::CertRead32DOp>(o)) {
1683 text_cost += 4; // ISA_OPSIZE_READ_32_D
1684 } else if (isa<AIEX::CertWrite32DOp>(o)) {
1685 text_cost += 12; // ISA_OPSIZE_WRITE_32_D
1686 } else if (isa<AIEX::CertSaveTimestampsOp>(o)) {
1687 text_cost += 8; // ISA_OPSIZE_SAVE_TIMESTAMPS
1688 } else if (isa<AIEX::CertSaveRegisterOp>(o)) {
1689 text_cost += 12; // ISA_OPSIZE_SAVE_REGISTER
1690 }
1691}
1692
1693static uint32_t estimateCost(AIEX::CertPageOp op,
1694 const SymbolTable &symbolTable,
1695 uint32_t split_target, AIEX::CertJobOp &split_job,
1696 Block::iterator &split_iter,
1697 bool &found_split_point) {
1698 uint32_t text_cost = 32; // page header: `.align 16` padding plus `.eop`
1699 uint32_t data_cost = 0;
1700 PageDataSeen seen;
1701 found_split_point = false;
1702
1703 for (auto job : op.getBody().front().getOps<AIEX::CertJobOp>()) {
1704 // Cuts inside a job that uses local registers would lose their values.
1705 bool splittable = !jobUsesLocalRegister(job);
1706 // START_JOB precedes the body, so it is already spent at every candidate
1707 // split point inside this job; END_JOB is charged after the body below.
1708 text_cost += cert_job_start_cost;
1709 for (auto &o : job.getBody().front().getOperations()) {
1710 Block::iterator current(&o);
1711 if (splittable && !found_split_point && !isa<AIE::EndOp>(o) &&
1712 current != job.getBody().front().begin() &&
1713 (text_cost + data_cost) >= split_target) {
1714 split_job = job;
1715 split_iter = current;
1716 found_split_point = true;
1717 }
1718
1719 updateCostForOp(o, symbolTable, text_cost, data_cost, seen);
1720
1721 if (splittable && !found_split_point &&
1722 (text_cost + data_cost) >= split_target) {
1723 Block::iterator next = current;
1724 ++next;
1725 if (next != job.getBody().front().end() && !isa<AIE::EndOp>(*next)) {
1726 split_job = job;
1727 split_iter = next;
1728 found_split_point = true;
1729 } else if (!isa<AIE::EndOp>(o) &&
1730 current != job.getBody().front().begin()) {
1731 // Cutting after the last real op would leave an empty second half.
1732 // Cut before it; exclude the terminator to guarantee progress.
1733 split_job = job;
1734 split_iter = current;
1735 found_split_point = true;
1736 }
1737 }
1738 }
1739 text_cost += cert_job_end_cost;
1740 }
1741 return text_cost + data_cost;
1742}
1743
1744// A cut before flat index p separates a span [lo, hi] when lo < p <= hi.
1745// Local barrier participants must share a page (see
1746// checkLocalBarrierColocation). A payload patch must share a page with every
1747// later uC-DMA push of that payload: each page carries its own payload copy,
1748// so a push on another page would use the unpatched addresses.
1750
1755
1756// Index non-terminator ops in textual order and record indivisible spans.
1757static void computeIndivisibleSpans(AIEX::CertPageOp page,
1758 const SymbolTable &symbolTable,
1759 std::map<Operation *, int> &flatIndex,
1760 SmallVectorImpl<IndivisibleSpan> &spans) {
1761 std::map<int, std::pair<int, int>> barriers;
1762 // Patches accumulate and survive pushes, so later pushes depend on the
1763 // earliest patch of their payload.
1764 llvm::StringMap<int> firstPatch;
1765 auto payloadsOf = [&](StringRef chainSym) {
1766 SmallVector<StringRef> payloads;
1767 auto chain = symbolTable.lookup<AIEX::CertUcDmaChainOp>(chainSym);
1768 if (!chain || chain.getBody().empty())
1769 return payloads;
1770 for (auto bd : chain.getBody().front().getOps<AIEX::CertUcDmaBdOp>())
1771 payloads.push_back(bd.getRemoteAddress());
1772 return payloads;
1773 };
1774
1775 int idx = 0;
1776 for (auto job : page.getBody().front().getOps<AIEX::CertJobOp>()) {
1777 for (auto &o : job.getBody().front().getOperations()) {
1778 if (isa<AIE::EndOp>(o))
1779 continue;
1780 flatIndex[&o] = idx;
1781 if (auto bar = dyn_cast<AIEX::CertLocalBarrierOp>(o)) {
1782 int id = static_cast<int>(bar.getLocalBarrierId());
1783 auto it = barriers.find(id);
1784 if (it == barriers.end())
1785 barriers[id] = {idx, idx};
1786 else {
1787 it->second.first = std::min(it->second.first, idx);
1788 it->second.second = std::max(it->second.second, idx);
1789 }
1790 } else if (auto patch = dyn_cast<AIEX::CertApplyOffset57Op>(o)) {
1791 firstPatch.try_emplace(patch.getSymbol(), idx);
1792 } else if (StringRef pushed = pushedChain(o); !pushed.empty()) {
1793 for (StringRef payload : payloadsOf(pushed)) {
1794 auto it = firstPatch.find(payload);
1795 if (it != firstPatch.end())
1796 spans.push_back({it->second, idx, SpanKind::PatchedPayload});
1797 }
1798 }
1799 ++idx;
1800 }
1801 }
1802 for (auto &[id, span] : barriers)
1803 spans.push_back({span.first, span.second, SpanKind::LocalBarrier});
1804}
1805
1806// Return whether the cut separates a span, optionally reporting its kind.
1807static bool cutSeparatesSpan(ArrayRef<IndivisibleSpan> spans, int p,
1808 SpanKind *kind = nullptr) {
1809 const auto *it = llvm::find_if(
1810 spans, [p](const IndivisibleSpan &s) { return s.lo < p && s.hi >= p; });
1811 if (it == spans.end())
1812 return false;
1813 if (kind)
1814 *kind = it->kind;
1815 return true;
1816}
1817
1818// Choose the span-safe cut closest to split_target, allowing both interior
1819// and job-boundary cuts. Each half needs content so repeated splitting
1820// progresses.
1821static bool findLegalSplitPoint(AIEX::CertPageOp page,
1822 const SymbolTable &symbolTable,
1823 uint32_t split_target,
1824 const std::map<Operation *, int> &flatIndex,
1825 ArrayRef<IndivisibleSpan> spans,
1826 AIEX::CertJobOp &split_job,
1827 Block::iterator &split_iter) {
1828 uint32_t text_cost = 32; // page header, mirrors estimateCost
1829 uint32_t data_cost = 0;
1830 PageDataSeen seen;
1831 bool found = false;
1832 uint32_t best_delta = 0;
1833 // Whether some job already visited holds a real op, i.e. whether cutting at
1834 // the current job's first op would leave content on the earlier page.
1835 bool sawOpInEarlierJob = false;
1836 for (auto job : page.getBody().front().getOps<AIEX::CertJobOp>()) {
1837 text_cost += cert_job_start_cost; // mirrors estimateCost
1838 bool splittable = !jobUsesLocalRegister(job); // mirrors estimateCost
1839 bool sawOpInJob = false;
1840 for (auto &o : job.getBody().front().getOperations()) {
1841 if (isa<AIE::EndOp>(o))
1842 continue;
1843 Block::iterator current(&o);
1844 // Candidate: cut before `o`, legal as an interior cut when an op of this
1845 // job precedes it, or as a job-boundary cut when an earlier job does.
1846 // Admitting the latter matters for a page built of small jobs whose sizes
1847 // only sum over the limit: no job has an interior point worth cutting at,
1848 // yet a cut between two whole jobs splits it perfectly well.
1849 if (sawOpInJob ? splittable : sawOpInEarlierJob) {
1850 auto fi = flatIndex.find(&o);
1851 int p = fi == flatIndex.end() ? 0 : fi->second;
1852 if (!cutSeparatesSpan(spans, p)) {
1853 uint32_t cost = text_cost + data_cost;
1854 uint32_t delta =
1855 cost > split_target ? cost - split_target : split_target - cost;
1856 if (!found || delta < best_delta) {
1857 found = true;
1858 best_delta = delta;
1859 split_job = job;
1860 split_iter = current;
1861 }
1862 }
1863 }
1864 updateCostForOp(o, symbolTable, text_cost, data_cost, seen);
1865 sawOpInJob = true;
1866 }
1867 text_cost += cert_job_end_cost; // mirrors estimateCost
1868 sawOpInEarlierJob |= sawOpInJob;
1869 }
1870 return found;
1871}
1872
1873namespace {
1874
1875// Pattern to isolate load_pdi and preempt operations into their own job and
1876// page According to CERT spec: "load_pdi and preempt should take one whole job
1877// which in turn should take one whole page"
1878struct IsolateFullPageOpsPattern : OpRewritePattern<AIEX::CertJobOp> {
1879 // `hadError` is raised with an error diagnostic, as in
1880 // SplitCertPageOpPattern.
1881 IsolateFullPageOpsPattern(MLIRContext *context, bool *hadError)
1882 : OpRewritePattern(context), hadError(hadError) {}
1883
1884 // Create an empty, terminated cert.page directly after `after`, in the same
1885 // block. Staying in `after`'s block is what keeps a page that was moved into
1886 // a cert.attach_to_group by placement lowering on its uC.
1887 static AIEX::CertPageOp makePageAfter(PatternRewriter &rewriter,
1888 Operation *after, Location loc) {
1889 rewriter.setInsertionPointAfter(after);
1890 auto page = AIEX::CertPageOp::create(rewriter, loc);
1891 page.getBody().push_back(new Block());
1892 AIEX::CertPageOp::ensureTerminator(page.getBody(), rewriter, loc);
1893 return page;
1894 }
1895
1896 LogicalResult matchAndRewrite(AIEX::CertJobOp jobOp,
1897 PatternRewriter &rewriter) const override {
1898
1899 // Find first load_pdi or preempt in this job
1900 Operation *fullPageOp = nullptr;
1901 Block::iterator fullPageOpIter;
1902 for (Block::iterator it = jobOp.getBody().front().begin();
1903 it != jobOp.getBody().front().end(); ++it) {
1904 if (isa<AIEX::CertLoadPdiOp, AIEX::CertPreemptOp>(*it)) {
1905 fullPageOp = &*it;
1906 fullPageOpIter = it;
1907 break;
1908 }
1909 }
1910
1911 if (!fullPageOp)
1912 return failure(); // No full-page op in this job
1913
1914 auto parentPage = jobOp->getParentOfType<AIEX::CertPageOp>();
1915 if (!parentPage)
1916 return failure(); // No parent page (unusual but skip)
1917
1918 // Real ops in this job (the terminator does not count).
1919 size_t opCount = 0;
1920 for (Operation &op : jobOp.getBody().front().getOperations())
1921 if (!isa<AIE::EndOp>(op))
1922 opCount++;
1923
1924 // Pages execute in order, so the rewrite has to preserve this job's
1925 // position among its *siblings*, not just relative to the parent page:
1926 // anchoring every new page on the parent page's boundary hoists the jobs
1927 // that surround this one across the isolated load_pdi/preempt. Nothing
1928 // downstream checks op order, so that reordering is silent.
1929 SmallVector<Operation *> leadingSiblings, trailingSiblings;
1930 bool pastSelf = false;
1931 for (Operation &op : parentPage.getBody().front()) {
1932 if (isa<AIE::EndOp>(op))
1933 continue;
1934 if (&op == jobOp.getOperation()) {
1935 pastSelf = true;
1936 continue;
1937 }
1938 (pastSelf ? trailingSiblings : leadingSiblings).push_back(&op);
1939 }
1940
1941 // Already properly isolated: sole op of the sole job of its page.
1942 if (opCount == 1 && leadingSiblings.empty() && trailingSiblings.empty())
1943 return failure();
1944
1945 auto loc = jobOp.getLoc();
1946
1947 // The parent page stays where it is and keeps the leading siblings; every
1948 // page created below is chained after it, in program order.
1949 Operation *anchor = parentPage.getOperation();
1950
1951 if (opCount == 1) {
1952 // The job is exactly the full-page op: it just needs a page of its own.
1953 auto isolatedPage = makePageAfter(rewriter, anchor, loc);
1954 jobOp->moveBefore(isolatedPage.getBody().front().getTerminator());
1955 anchor = isolatedPage;
1956 } else {
1957 // Mixed job: split it into up to three jobs, each on its own page, in
1958 // source order (ops before the full-page op, it, then the ops after).
1959 auto parentDevice = jobOp->getParentOfType<AIE::DeviceOp>();
1960 uint32_t maxJobId = 0;
1961 parentDevice.walk([&](AIEX::CertJobOp certJobOp) {
1962 maxJobId = std::max(maxJobId, certJobOp.getJobId());
1963 });
1964 uint32_t beforeJobId = jobOp.getJobId();
1965 uint32_t fullPageJobId = maxJobId + 1;
1966 uint32_t afterJobId = maxJobId + 2;
1967
1968 SmallVector<Operation *> beforeOps, afterOps;
1969 for (Block::iterator it = jobOp.getBody().front().begin();
1970 it != fullPageOpIter; ++it)
1971 if (!isa<AIE::EndOp>(*it))
1972 beforeOps.push_back(&*it);
1973 Block::iterator afterStart = std::next(fullPageOpIter);
1974 for (Block::iterator it = afterStart; it != jobOp.getBody().front().end();
1975 ++it)
1976 if (!isa<AIE::EndOp>(*it))
1977 afterOps.push_back(&*it);
1978
1979 // Isolation is mandatory, so a local register written before the
1980 // full-page op and read after it cannot be kept; reject the job.
1981 if (auto crossing = findLocalRegisterCrossingIn(afterOps)) {
1982 StringRef name = fullPageOp->getName().getStringRef();
1983 *hadError = true;
1984 return jobOp.emitError()
1985 << "job " << jobOp.getJobId() << " must be split around its "
1986 << name << ", but local register r" << *crossing
1987 << " is written before it and read after it; keep that "
1988 "register's uses on one side of the "
1989 << name << ", or put them in a separate job";
1990 }
1991
1992 auto emitJobPage = [&](uint32_t jobId, ArrayRef<Operation *> ops) {
1993 auto page = makePageAfter(rewriter, anchor, loc);
1994 rewriter.setInsertionPoint(page.getBody().front().getTerminator());
1995 auto job = AIEX::CertJobOp::create(rewriter, loc, jobId);
1996 job.getBody().push_back(new Block());
1997 AIEX::CertJobOp::ensureTerminator(job.getBody(), rewriter, loc);
1998 for (Operation *op : ops)
1999 op->moveBefore(job.getBody().front().getTerminator());
2000 anchor = page;
2001 };
2002
2003 if (!beforeOps.empty())
2004 emitJobPage(beforeJobId, beforeOps);
2005 emitJobPage(fullPageJobId, {fullPageOp});
2006 if (!afterOps.empty())
2007 emitJobPage(afterJobId, afterOps);
2008
2009 rewriter.eraseOp(jobOp);
2010 }
2011
2012 // The trailing siblings cannot stay on the parent page, which now precedes
2013 // the isolated page, so they move to a page of their own behind it.
2014 if (!trailingSiblings.empty()) {
2015 auto tailPage = makePageAfter(rewriter, anchor, loc);
2016 for (Operation *op : trailingSiblings)
2017 op->moveBefore(tailPage.getBody().front().getTerminator());
2018 }
2019
2020 if (llvm::all_of(parentPage.getBody().front(),
2021 [](Operation &op) { return isa<AIE::EndOp>(op); }))
2022 rewriter.eraseOp(parentPage);
2023
2024 return success();
2025 }
2026
2027 bool *hadError;
2028};
2029
2030struct SplitCertPageOpPattern : OpRewritePattern<AIEX::CertPageOp> {
2031 // `hadError` is raised when the pattern emits an error diagnostic. A rewrite
2032 // pattern returning failure() is ordinary control flow -- it does NOT fail
2033 // the pass -- so without this the "cannot split" error below would print and
2034 // the oversized page would still reach codegen. The pass checks the flag
2035 // after applyPatternsGreedily and calls signalPassFailure().
2036 // symbolTable is the device's; splitting only clones jobs, so it stays
2037 // current.
2038 SplitCertPageOpPattern(MLIRContext *context, const SymbolTable &symbolTable,
2039 bool *hadError)
2040 : OpRewritePattern(context), symbolTable(symbolTable),
2041 hadError(hadError) {}
2042
2043 LogicalResult matchAndRewrite(AIEX::CertPageOp op,
2044 PatternRewriter &rewriter) const override {
2045
2046 constexpr uint32_t split_threshold = cert_page_size;
2047
2048 AIEX::CertJobOp split_job;
2049 Block::iterator split_iter;
2050 bool found_split_point = false;
2051 uint32_t cost = estimateCost(op, symbolTable, cert_page_size / 2, split_job,
2052 split_iter, found_split_point);
2053 LLVM_DEBUG(llvm::outs()
2054 << "Estimate cost for page: " << " is " << cost << "\n");
2055
2056 if (cost < split_threshold)
2057 return failure();
2058
2059 bool isImplicit = op->hasAttr("cert.implicit");
2060
2061 std::map<Operation *, int> flatIndex;
2062 SmallVector<IndivisibleSpan> spans;
2063 computeIndivisibleSpans(op, symbolTable, flatIndex, spans);
2064
2065 // The initial estimate can miss a job-boundary cut or an earlier candidate;
2066 // search all positions before declaring the page unsplittable. Spans are
2067 // not applied here: a page whose cuts are all blocked by a span has split
2068 // points, and the span check below reports which constraint blocks them.
2069 if (!found_split_point)
2070 found_split_point =
2071 findLegalSplitPoint(op, symbolTable, cert_page_size / 2, flatIndex,
2072 {}, split_job, split_iter);
2073
2074 // Over the split trigger but with nowhere to cut. Every cut has to leave at
2075 // least one op on each side, so a page whose bulk sits in a single one-op
2076 // job offers none. Leave the page alone -- but if it is also over the hard
2077 // limit, it will not load, so say so instead of emitting a page the
2078 // firmware will reject.
2079 if (!found_split_point) {
2080 if (cost > cert_page_limit) {
2081 auto jobs = op.getBody().front().getOps<AIEX::CertJobOp>();
2082 auto blocker = llvm::find_if(jobs, jobUsesLocalRegister);
2083 if (blocker != jobs.end())
2084 op.emitError() << "cert.page is an estimated " << cost
2085 << " bytes, over the " << cert_page_limit
2086 << "-byte microcontroller page limit, and cannot be "
2087 "split: job "
2088 << (*blocker).getJobId()
2089 << " uses local registers r0..r7, which do not "
2090 "survive a split; break it into smaller jobs "
2091 "that each keep a register's definition and "
2092 "uses together";
2093 else
2094 op.emitError() << "cert.page is an estimated " << cost
2095 << " bytes, over the " << cert_page_limit
2096 << "-byte microcontroller page limit, and offers no "
2097 "split point (a split must leave at least one op "
2098 "on each page); break the oversized job into "
2099 "smaller jobs";
2100 *hadError = true;
2101 }
2102 return failure();
2103 }
2104
2105 // Never split a local_barrier participant set, or a payload patch from a
2106 // later push of that payload, across an .eop. If the cost-chosen split
2107 // point would, retarget to a legal split point; if none exists the page
2108 // cannot be made legal, so fail the compile rather than emit something
2109 // broken. An implicit page (formed by formImplicitPages) groups jobs meant
2110 // to be cooperatively scheduled together; an explicit page is a
2111 // user-authored boundary. This governs the wording of the diagnostics
2112 // below (the remedy differs), not whether they fire.
2113 if (!spans.empty()) {
2114 auto fi = flatIndex.find(&*split_iter);
2115 int p = fi == flatIndex.end() ? 0 : fi->second;
2117 if (cutSeparatesSpan(spans, p, &kind)) {
2118 if (!findLegalSplitPoint(op, symbolTable, cert_page_size / 2, flatIndex,
2119 spans, split_job, split_iter)) {
2120 // Leave the page whole: a severed span hangs the firmware or pushes
2121 // stale addresses, so an oversized page is the better of the two.
2122 // That is only survivable while the page still fits; past
2123 // cert_page_limit, diagnose and raise `hadError` so the pass fails
2124 // rather than only this rewrite.
2125 if (cost > cert_page_limit) {
2126 bool barrier = kind == SpanKind::LocalBarrier;
2127 StringRef what = barrier
2128 ? "a local_barrier participant set"
2129 : "a cert.apply_offset_57 from a uC-DMA push "
2130 "of the payload it patches";
2131 if (isImplicit)
2132 op.emitError()
2133 << "implicit cert.page is an estimated " << cost
2134 << " bytes, over the " << cert_page_limit
2135 << "-byte microcontroller page limit, and cannot be split "
2136 "without separating "
2137 << what
2138 << " across pages; insert an explicit cert.page boundary to "
2139 << (barrier ? "co-locate the barrier participants"
2140 : "co-locate each apply_offset_57 with its "
2141 "pushes");
2142 else
2143 op.emitError()
2144 << "cert.page is an estimated " << cost << " bytes, over the "
2145 << cert_page_limit
2146 << "-byte microcontroller page limit, and cannot be split "
2147 "without separating "
2148 << what << " across pages; reduce the page's contents or "
2149 << (barrier ? "regroup its local_barrier participants"
2150 : "regroup its apply_offset_57 ops and their "
2151 "pushes")
2152 << " so that a legal split point exists";
2153 *hadError = true;
2154 }
2155 return failure();
2156 }
2157 }
2158 }
2159
2160 // splitting an implicit page turns jobs that were meant to run
2161 // cooperatively on one page into strictly sequential pages. Warn so the
2162 // user can insert an explicit boundary if the serialization is unintended.
2163 if (isImplicit)
2164 op.emitRemark()
2165 << "auto-split of implicit cert.page serializes cooperatively-"
2166 "scheduled jobs into separate sequential pages; insert an "
2167 "explicit "
2168 "cert.page boundary to control where the split occurs";
2169
2170 auto loc = op.getLoc();
2171
2172 // Preserve source order across both pages so cross-page dependencies stay
2173 // backward. A job-boundary cut moves split_job whole onto the later page.
2174 bool jobBoundaryCut = split_iter == split_job.getBody().front().begin();
2175 [[maybe_unused]] auto earlierJobHasRealOp = [&]() {
2176 for (auto job : op.getBody().front().getOps<AIEX::CertJobOp>()) {
2177 if (job == split_job)
2178 break;
2179 for (auto &o : job.getBody().front().getOperations())
2180 if (!isa<AIE::EndOp>(o))
2181 return true;
2182 }
2183 return false;
2184 };
2185 assert((!jobBoundaryCut || earlierJobHasRealOp()) &&
2186 "a job-boundary cut needs a preceding job with content, else the "
2187 "earlier page is empty and the split makes no progress");
2188
2189 // The second half of a split job takes the next ID, which may collide
2190 // with another job on its page; allocateJobIds resolves that after all
2191 // splitting is done.
2192 auto cloneJobRange = [&](AIEX::CertJobOp sourceJob, uint32_t jobId,
2193 Block::iterator begin, Block::iterator end) {
2194 auto newJobOp = AIEX::CertJobOp::create(rewriter, loc, jobId);
2195 Block *newJobBlock = new Block();
2196 newJobOp.getBody().push_back(newJobBlock);
2197
2198 IRMapping mapper;
2199 Block &sourceBlock = sourceJob.getBody().front();
2200 for (BlockArgument arg : sourceBlock.getArguments()) {
2201 BlockArgument newArg =
2202 newJobBlock->addArgument(arg.getType(), arg.getLoc());
2203 mapper.map(arg, newArg);
2204 }
2205
2206 rewriter.setInsertionPointToStart(newJobBlock);
2207 for (Block::iterator oi = begin; oi != end; ++oi) {
2208 if (!isa<AIE::EndOp>(*oi))
2209 rewriter.clone(*oi, mapper);
2210 }
2211 AIEX::CertJobOp::ensureTerminator(newJobOp.getBody(), rewriter, loc);
2212 };
2213
2214 rewriter.setInsertionPoint(op);
2215 auto newPageOp0 = AIEX::CertPageOp::create(rewriter, loc);
2216 Block *newPageBlock0 = new Block();
2217 newPageOp0.getBody().push_back(newPageBlock0);
2218
2219 auto newPageOp1 = AIEX::CertPageOp::create(rewriter, loc);
2220 Block *newPageBlock1 = new Block();
2221 newPageOp1.getBody().push_back(newPageBlock1);
2222
2223 // propagate the implicit tag so a later re-split of either fragment
2224 // still knows it came from an implicit page and diagnoses consistently.
2225 if (isImplicit) {
2226 newPageOp0->setAttr("cert.implicit", rewriter.getUnitAttr());
2227 newPageOp1->setAttr("cert.implicit", rewriter.getUnitAttr());
2228 }
2229
2230 for (auto job : op.getBody().front().getOps<AIEX::CertJobOp>()) {
2231 if (job == split_job) {
2232 if (jobBoundaryCut) {
2233 // Whole job to the later page: partitioning it at its own first op
2234 // would leave an empty half behind on the earlier page.
2235 rewriter.setInsertionPointToEnd(newPageBlock1);
2236 cloneJobRange(job, job.getJobId(), job.getBody().front().begin(),
2237 job.getBody().front().end());
2238 continue;
2239 }
2240 rewriter.setInsertionPointToEnd(newPageBlock0);
2241 cloneJobRange(job, job.getJobId(), job.getBody().front().begin(),
2242 split_iter);
2243
2244 rewriter.setInsertionPointToEnd(newPageBlock1);
2245 cloneJobRange(job, job.getJobId() + 1, split_iter,
2246 job.getBody().front().end());
2247 continue;
2248 }
2249
2250 if (job->isBeforeInBlock(split_job)) {
2251 rewriter.setInsertionPointToEnd(newPageBlock0);
2252 cloneJobRange(job, job.getJobId(), job.getBody().front().begin(),
2253 job.getBody().front().end());
2254 } else {
2255 rewriter.setInsertionPointToEnd(newPageBlock1);
2256 cloneJobRange(job, job.getJobId(), job.getBody().front().begin(),
2257 job.getBody().front().end());
2258 }
2259 }
2260
2261 AIEX::CertPageOp::ensureTerminator(newPageOp0.getBody(), rewriter, loc);
2262 AIEX::CertPageOp::ensureTerminator(newPageOp1.getBody(), rewriter, loc);
2263
2264 rewriter.eraseOp(op);
2265 return success();
2266 }
2267
2268 const SymbolTable &symbolTable;
2269 bool *hadError;
2270};
2271
2272// Explicit group 0 shares the default stream. Flatten it before page formation
2273// so it does not introduce an artificial scheduling boundary.
2274static void inlineDefaultGroup(AIE::DeviceOp dev) {
2275 Block *body = dev.getBody();
2276 SmallVector<AIEX::CertAttachToGroupOp> zeroGroups;
2277 for (auto grp : body->getOps<AIEX::CertAttachToGroupOp>())
2278 if (grp.getGroupId() == 0)
2279 zeroGroups.push_back(grp);
2280 for (auto grp : zeroGroups) {
2281 SmallVector<Operation *> inner;
2282 for (Operation &op : grp.getBody().front())
2283 if (!isa<AIE::EndOp>(op))
2284 inner.push_back(&op);
2285 for (Operation *op : inner)
2286 op->moveBefore(grp.getOperation());
2287 grp.erase();
2288 }
2289}
2290
2291// Group a block's maximal runs of contiguous top-level cert.job ops into
2292// implicit cert.page ops (only an explicit cert.page delimits; the
2293// {cert.configure} job stays isolated in its own page). Applied per uC stream.
2294static void formImplicitPagesInBlock(Block *body, OpBuilder &builder) {
2295 // Snapshot top-level ops; the body is mutated while iterating.
2296 SmallVector<Operation *> topOps;
2297 for (Operation &op : *body)
2298 topOps.push_back(&op);
2299
2300 // `cert.implicit` marks a page formed from a run of *user* jobs -- a
2301 // boundary the author could have drawn but didn't. The splitter's diagnostics
2302 // are keyed off it and all advise editing page boundaries, so it must not be
2303 // set on a page the user cannot restructure. The compiler-synthesized
2304 // @configure page is exactly that case, and it is isolated by construction,
2305 // so the tag would buy nothing there anyway.
2306 auto openPage = [&](Location loc, Operation *before,
2307 bool implicit) -> AIEX::CertPageOp {
2308 builder.setInsertionPoint(before);
2309 auto page = AIEX::CertPageOp::create(builder, loc);
2310 if (implicit)
2311 page->setAttr("cert.implicit", builder.getUnitAttr());
2312 Block *b = new Block();
2313 page.getBody().push_back(b);
2314 AIEX::CertPageOp::ensureTerminator(page.getBody(), builder, loc);
2315 return page;
2316 };
2317
2318 // The (tile, channel) actors a job wait_tcts on, keyed exactly as
2319 // AIECertVerify's G-tct check (checkWaitTctsUniqueness) keys them so the two
2320 // stay consistent.
2321 auto waitTctsActors = [](AIEX::CertJobOp job) {
2322 std::set<std::pair<int, int>> actors;
2323 job.walk([&](AIEX::CertWaitTCTSOp wait) {
2324 actors.insert({wait.getTileId(), wait.getChannelId()});
2325 });
2326 return actors;
2327 };
2328
2329 AIEX::CertPageOp currentPage; // null => no open implicit page
2330 // Actors already waited on by the jobs accumulated into `currentPage`.
2331 std::set<std::pair<int, int>> pageActors;
2332 auto closePage = [&]() {
2333 currentPage = nullptr;
2334 pageActors.clear();
2335 };
2336
2337 for (Operation *op : topOps) {
2338 if (auto job = dyn_cast<AIEX::CertJobOp>(op)) {
2339 if (job->hasAttr("cert.configure")) {
2340 // Keep the configuration job isolated in its own page. Not tagged
2341 // implicit: the user did not author this job and cannot add a boundary
2342 // inside it, so the auto-split remark would be noise on every compile
2343 // whose
2344 // config transaction is large enough to split (and it usually is).
2345 auto page = openPage(job.getLoc(), job, /*implicit=*/false);
2346 job->moveBefore(page.getBody().front().getTerminator());
2347 closePage();
2348 continue;
2349 }
2350 // G-tct: at most one job per page may wait on a given actor. Two jobs
2351 // that each legally wait on the same (tile, channel) -- an ordinary shape
2352 // for two runtime sequences sharing a shim channel -- are only legal
2353 // while they sit on separate pages, so grouping them would manufacture a
2354 // verifier error out of valid input. Cut a page boundary instead, exactly
2355 // as an over-size job would.
2356 auto actors = waitTctsActors(job);
2357 if (currentPage &&
2358 llvm::any_of(actors, [&](const std::pair<int, int> &actor) {
2359 return pageActors.count(actor);
2360 }))
2361 closePage();
2362 if (!currentPage)
2363 currentPage = openPage(job.getLoc(), job, /*implicit=*/true);
2364 job->moveBefore(currentPage.getBody().front().getTerminator());
2365 pageActors.insert(actors.begin(), actors.end());
2366 } else if (isa<AIEX::CertPageOp>(op)) {
2367 // An explicit page delimits the current implicit run.
2368 closePage();
2369 }
2370 // All other ops (structural / control containers) do not delimit a run.
2371 }
2372}
2373
2374static void formImplicitPages(AIE::DeviceOp dev) {
2375 OpBuilder builder(dev.getContext());
2376 formImplicitPagesInBlock(dev.getBody(), builder);
2377 // Each other uC (attach_to_group) forms implicit pages within its own stream,
2378 // so adjacent jobs on that uC are cooperatively co-located too.
2379 SmallVector<AIEX::CertAttachToGroupOp> groups;
2380 for (auto grp : dev.getBody()->getOps<AIEX::CertAttachToGroupOp>())
2381 groups.push_back(grp);
2382 for (auto grp : groups)
2383 formImplicitPagesInBlock(&grp.getBody().front(), builder);
2384}
2385
2386// Force the implicit configuration page to be the first page on uC0:
2387// @configure sets up the device (DMA/lock/core config), so it must strictly
2388// precede all other uC0 pages regardless of where it appeared textually. The
2389// config job is already isolated in its own page by formImplicitPages; here we
2390// just hoist that page to the front of the device body (structural ops are not
2391// control code, so position relative to them does not matter).
2392static void moveConfigPageFirst(AIE::DeviceOp dev) {
2393 Block *body = dev.getBody();
2394 AIEX::CertPageOp configPage;
2395 for (auto page : body->getOps<AIEX::CertPageOp>()) {
2396 for (auto job : page.getBody().front().getOps<AIEX::CertJobOp>()) {
2397 if (job->hasAttr("cert.configure")) {
2398 configPage = page;
2399 break;
2400 }
2401 }
2402 if (configPage)
2403 break;
2404 }
2405 if (configPage && &body->front() != configPage.getOperation())
2406 configPage->moveBefore(&body->front());
2407}
2408
2409// Move nonzero placements into their controller containers, retaining order.
2410static void lowerPagePlacementToGroups(AIE::DeviceOp dev) {
2411 Block *body = dev.getBody();
2412
2413 // Collect placed top-level pages by resolved group id, in first-seen order.
2414 std::map<int32_t, SmallVector<AIEX::CertPageOp, 4>> byGroup;
2415 for (auto page : body->getOps<AIEX::CertPageOp>()) {
2416 if (auto placement = page.getPlacementAttr()) {
2417 auto gid = static_cast<int32_t>(placement.getInt());
2418 if (gid != 0)
2419 byGroup[gid].push_back(page);
2420 }
2421 }
2422
2423 OpBuilder builder(dev.getContext());
2424 for (auto &entry : byGroup) {
2425 int32_t gid = entry.first;
2426 SmallVector<AIEX::CertPageOp, 4> &pages = entry.second;
2427
2428 // Create the group op where the first placed page currently lives (avoids
2429 // assuming anything about a device terminator).
2430 builder.setInsertionPoint(pages.front());
2431 auto grp = AIEX::CertAttachToGroupOp::create(builder, dev.getLoc(), gid);
2432 Block *grpBlock = new Block();
2433 grp.getBody().push_back(grpBlock);
2434
2435 // Move the placed pages into the group, in order, dropping the
2436 // now-redundant placement attribute (the group encodes it).
2437 for (AIEX::CertPageOp page : pages) {
2438 page->removeAttr("placement");
2439 page->moveBefore(grpBlock, grpBlock->end());
2440 }
2441 AIEX::CertAttachToGroupOp::ensureTerminator(grp.getBody(), builder,
2442 dev.getLoc());
2443 }
2444}
2445
2446// The firmware indexes job contexts by job_id % 64, and a page's jobs finish
2447// before the next page starts. Keep each page's noncolliding IDs and move the
2448// colliding ones to free slots.
2449static LogicalResult allocateJobIds(AIE::DeviceOp device) {
2450 WalkResult result = device.walk([&](AIEX::CertPageOp page) {
2451 std::bitset<AIEX::CertJobOp::NumSlots> used;
2452 SmallVector<AIEX::CertJobOp> collisions;
2453 unsigned count = 0;
2454 for (auto job : page.getBody().front().getOps<AIEX::CertJobOp>()) {
2455 unsigned slot = job.getJobId() % AIEX::CertJobOp::NumSlots;
2456 if (used.test(slot))
2457 collisions.push_back(job);
2458 used.set(slot);
2459 ++count;
2460 }
2461 if (count > AIEX::CertJobOp::NumSlots) {
2462 page.emitError() << "cert.page has " << count << " jobs, exceeding the "
2463 << AIEX::CertJobOp::NumSlots
2464 << " firmware job slots; reduce the jobs on this page";
2465 return WalkResult::interrupt();
2466 }
2467 unsigned slot = 0;
2468 for (auto job : collisions) {
2469 while (used.test(slot))
2470 ++slot;
2471 job.setJobId(slot);
2472 used.set(slot);
2473 }
2474 return WalkResult::advance();
2475 });
2476 return failure(result.wasInterrupted());
2477}
2478
2479struct AIECertPagesPass
2480 : xilinx::AIEX::impl::AIECertPagesBase<AIECertPagesPass> {
2481 void runOnOperation() override {
2482 inlineDefaultGroup(getOperation());
2483
2484 formImplicitPages(getOperation());
2485
2486 // Force the @configure page to be first on uC0.
2487 moveConfigPageFirst(getOperation());
2488
2489 // Lower cert.page placement to cert.attach_to_group BEFORE isolate
2490 // and split. Those rewrites create replacement pages adjacent to the
2491 // original (same parent block) with the no-placement builder; running the
2492 // placement grouping first means placed pages already live inside their
2493 // cert.attach_to_group, so any pages the later rewrites spawn stay in the
2494 // same group by position. (Doing this last silently dropped placement from
2495 // split/isolated pages, emitting them on group 0.)
2496 lowerPagePlacementToGroups(getOperation());
2497
2498 // The steps below look chains and payloads up many times per op. None of
2499 // them creates a symbol, and the merge removes the chains it erases.
2500 SymbolTable symbolTable(getOperation());
2501
2502 // First, isolate load_pdi and preempt operations into their own job/page
2503 bool isolateError = false;
2504 RewritePatternSet isolatePatterns(&getContext());
2505 isolatePatterns.insert<IsolateFullPageOpsPattern>(&getContext(),
2506 &isolateError);
2507 if (failed(
2508 applyPatternsGreedily(getOperation(), std::move(isolatePatterns))))
2509 signalPassFailure();
2510 if (isolateError)
2511 return signalPassFailure();
2512
2513 // Then apply the page splitting pattern. `splitError` catches diagnostics
2514 // the pattern emits while declining to split (see SplitCertPageOpPattern):
2515 // applyPatternsGreedily reports only whether the rewrite converged, so an
2516 // illegal-to-split page would otherwise print an error and still compile.
2517 bool splitError = false;
2518 RewritePatternSet p1(&getContext());
2519 p1.insert<SplitCertPageOpPattern>(&getContext(), symbolTable, &splitError);
2520 if (failed(applyPatternsGreedily(getOperation(), std::move(p1))))
2521 signalPassFailure();
2522 if (splitError)
2523 signalPassFailure();
2524
2525 if (failed(allocateJobIds(getOperation())))
2526 return signalPassFailure();
2527
2528 // Add the merge pattern for CertUcDmaWriteDesSyncOps. With an op whose
2529 // symbol uses are unknown, no use is counted and nothing merges.
2530 llvm::DenseMap<StringAttr, unsigned> useCounts;
2531 if (auto uses = SymbolTable::getSymbolUses(&getOperation().getRegion()))
2532 for (const SymbolTable::SymbolUse &use : *uses)
2533 ++useCounts[use.getSymbolRef().getRootReference()];
2534 RewritePatternSet p3(&getContext());
2535 p3.insert<MergeConsecutiveCertUcDmaWriteDesSyncOps>(&getContext(),
2536 symbolTable, useCounts);
2537 if (failed(applyPatternsGreedily(getOperation(), std::move(p3))))
2538 return signalPassFailure();
2539 }
2540};
2541
2542} // namespace
2543
2544std::unique_ptr<OperationPass<mlir::ModuleOp>> AIEX::createAIENpuToCertPass() {
2545 return std::make_unique<AIENpuToCertPass>();
2546}
2547
2548std::unique_ptr<OperationPass<AIE::DeviceOp>> AIEX::createAIECertPagesPass() {
2549 return std::make_unique<AIECertPagesPass>();
2550}
const V & get(const std::map< K, V > &pa, K k)
Definition d_ary_heap.h:70
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createAIENpuToCertPass()
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIECertPagesPass()
mlir::LogicalResult inlineWriteConfigs(mlir::ModuleOp module)
mlir::Operation * lookupNamedOpIn(mlir::Operation *symbolTableOp, mlir::StringAttr name)
const AIETargetModel & getTargetModel(mlir::Operation *op)
llvm::DenseSet< Operation * > chains
llvm::DenseSet< Operation * > payloads