MLIR-AIE 1.4.6.dev
AIEDialect.cpp
Go to the documentation of this file.
1//===- AIEDialect.cpp -------------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2019-2022 Xilinx, Inc.
4// Copyright (C) 2022-2026 Advanced Micro Devices, Inc.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "mlir/Dialect/Arith/IR/Arith.h"
12#include "mlir/Dialect/Func/IR/FuncOps.h"
13#include "mlir/Dialect/MemRef/IR/MemRef.h"
14#include "mlir/Dialect/Utils/StaticValueUtils.h"
15#include "mlir/IR/DialectImplementation.h"
16#include "mlir/IR/Matchers.h"
17#include "mlir/IR/OpDefinition.h"
18#include "mlir/IR/SymbolTable.h"
19#include "mlir/Interfaces/FoldInterfaces.h"
20#include "mlir/Interfaces/ViewLikeInterface.h"
21#include "mlir/Transforms/InliningUtils.h"
22#include "llvm/ADT/STLExtras.h"
23
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/TypeSwitch.h"
27#include "llvm/Support/CheckedArithmetic.h"
28#include "llvm/Support/MathExtras.h"
29
30#include <limits>
31#include <map>
32#include <numeric>
33#include <optional>
34#include <string>
35#include <tuple>
36#include <utility>
37#include <vector>
38
39using namespace mlir;
40using namespace xilinx::AIE;
41
42// Add TableGen'erated dialect definitions (including constructor)
43// We implement the initialize() function further below
44#include "aie/Dialect/AIE/IR/AIEDialect.cpp.inc"
45
46#define GET_TYPEDEF_CLASSES
47#include "aie/Dialect/AIE/IR/AIETypes.cpp.inc"
48
49namespace {
50
51struct AIEInlinerInterface : DialectInlinerInterface {
52 using DialectInlinerInterface::DialectInlinerInterface;
53 // We don't have any special restrictions on what can be inlined into
54 // destination regions. Always allow it.
55 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
56 IRMapping &valueMapping) const final {
57 return true;
58 }
59
60 // Operations in aie dialect are always legal to inline since they are
61 // pure.
62 bool isLegalToInline(Operation *op, Region *, bool wouldBeCloned,
63 IRMapping &) const final {
64 return true;
65 }
66
67 // Handle the given inlined terminator by replacing it with a new operation
68 // as necessary. Required when the inlined region has more than one block.
69 void handleTerminator(Operation *op, Block *newDest) const final {}
70
71 // Handle the given inlined terminator by replacing it with a new operation
72 // as necessary. Required when the region has only one block.
73 void handleTerminator(Operation *op, ValueRange valuesToRepl) const final {}
74};
75
76struct AIEDialectFoldInterface : DialectFoldInterface {
77 using DialectFoldInterface::DialectFoldInterface;
78
79 /// Registered hook to check if the given region, which is attached to an
80 /// operation that is *not* isolated from above, should be used when
81 /// materializing constants.
82 bool shouldMaterializeInto(Region *region) const final {
83 // Materialize constants into the op that "owns" them rather than letting
84 // them hoist up to the enclosing IsolatedFromAbove aie.device:
85 // - aie.core bodies are outlined into standalone funcs, so their
86 // constants must stay local for the func to be self-contained.
87 // - aie.runtime_sequence bodies carry constant operands (e.g. the scalar
88 // fields of npu.* ops). Hoisting them to the device body lets CSE merge
89 // them with a core's identical constants, which would leave the core
90 // referencing a device-level value that is erased when the core is
91 // outlined.
92 // - Make sure SSA values for aie.use_lock operands in
93 // aie.mem/aie.memtile_dma/aie.shim_dma bodies do not get
94 // hoisted.
95 return isa<CoreOp, RuntimeSequenceOp, MemOp, MemTileDMAOp, ShimDMAOp>(
96 region->getParentOp());
97 }
98};
99
100} // end anonymous namespace
101
102void AIEDialect::initialize() {
103 addTypes<
104#define GET_TYPEDEF_LIST
105#include "aie/Dialect/AIE/IR/AIETypes.cpp.inc"
106 >();
107 addAttributes<
108#define GET_ATTRDEF_LIST
109#include "aie/Dialect/AIE/IR/AIEAttrs.cpp.inc"
110 >();
111 addOperations<
112#define GET_OP_LIST
113#include "aie/Dialect/AIE/IR/AIEOps.cpp.inc"
114 >();
115 addInterfaces<AIEInlinerInterface, AIEDialectFoldInterface>();
116}
117
118// Helper methods to retrieve the encoding associated to a burst length,
119// or to find the highest available burst length if the requested one is 0
120// (default value).
121
122static std::pair<uint32_t, uint32_t>
123getShimBurstLength(const xilinx::AIE::AIETargetModel &tm,
124 uint32_t burstLength) {
125
126 std::vector<std::pair<uint32_t, uint32_t>> bel =
128
129 // If we have the default burst length (no burst length was specified),
130 // use the highest one available on our target model
131 if (burstLength == 0) {
132 return *llvm::max_element(bel, [](auto pair1, auto pair2) {
133 return pair1.second < pair2.second;
134 });
135 }
136
137 // Note that if we are given a burst size, we are checking its existence in
138 // the pass verification already, so we can safely assume it exists.
139 return *llvm::find_if(bel, [=](auto p) { return p.second == burstLength; });
140}
141
143 uint32_t burstLength) {
144
145 return getShimBurstLength(tm, burstLength).second;
146}
147
149 uint32_t burstLength) {
150
151 return getShimBurstLength(tm, burstLength).first;
152}
153
154Operation *xilinx::AIE::lookupNamedOpIn(Operation *symbolTableOp,
155 StringAttr name) {
156 if (!symbolTableOp->hasTrait<mlir::OpTrait::SymbolTable>() ||
157 symbolTableOp->getRegion(0).empty()) {
158 return nullptr;
159 }
160 // One walk finds both kinds: a symbol op's name is its `sym_name`, and
161 // `getAttr` reads it whether it is inherent or discardable.
162 for (Operation &op : symbolTableOp->getRegion(0).front()) {
163 if (op.getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()) ==
164 name) {
165 return &op;
166 }
167 }
168 return nullptr;
169}
170
172 : context(symbolTableOp->getContext()) {
173 if (!symbolTableOp->hasTrait<mlir::OpTrait::SymbolTable>() ||
174 symbolTableOp->getRegion(0).empty()) {
175 return;
176 }
177 for (Operation &op : symbolTableOp->getRegion(0).front()) {
178 if (auto name = op.getAttrOfType<StringAttr>(
179 mlir::SymbolTable::getSymbolAttrName())) {
180 ops.try_emplace(name, &op);
181 }
182 }
183}
184
185Operation *xilinx::AIE::lookupNamedOpIn(Operation *symbolTableOp,
186 StringRef name) {
187 return lookupNamedOpIn(symbolTableOp,
188 StringAttr::get(symbolTableOp->getContext(), name));
189}
190
191Operation *xilinx::AIE::lookupNamedOp(Operation *from, StringAttr name) {
192 Operation *symbolTableOp = mlir::SymbolTable::getNearestSymbolTable(from);
193 return symbolTableOp ? lookupNamedOpIn(symbolTableOp, name) : nullptr;
194}
195
196Operation *xilinx::AIE::lookupNamedOp(Operation *from, StringRef name) {
197 return lookupNamedOp(from, StringAttr::get(from->getContext(), name));
198}
199
200std::string xilinx::AIE::NamedOpTable::uniqueName(llvm::StringRef prefix,
201 unsigned &counter) const {
202 std::string name;
203 do {
204 name = (prefix + llvm::Twine(counter++)).str();
205 } while (ops.count(StringAttr::get(context, name)));
206 return name;
207}
208
209LogicalResult
210xilinx::AIE::myVerifyOffsetSizeAndStrideOp(OffsetSizeAndStrideOpInterface op) {
211 std::array<unsigned, 3> maxRanks = op.getArrayAttrMaxRanks();
212 // Count checks FIRST, matching mlir::detail::verifyOffsetSizeAndStrideOp.
213 // getMixedOffsets()/getMixedSizes() assert that the number of dynamic
214 // operands equals the number of kDynamic sentinels in the static list, so
215 // running the rank comparison before these validates nothing and aborts on
216 // malformed input instead of diagnosing it.
217 if (failed(verifyListOfOperandsOrIntegers(
218 op, "offset", maxRanks[0], op.getStaticOffsets(), op.getOffsets())))
219 return failure();
220 if (failed(verifyListOfOperandsOrIntegers(
221 op, "size", maxRanks[1], op.getStaticSizes(), op.getSizes())))
222 return failure();
223 if (failed(verifyListOfOperandsOrIntegers(
224 op, "stride", maxRanks[2], op.getStaticStrides(), op.getStrides())))
225 return failure();
226 // Each getMixed* call rebuilds its list, so read them once.
227 const size_t numMixedOffsets = op.getMixedOffsets().size();
228 const size_t numMixedSizes = op.getMixedSizes().size();
229 if (!(numMixedOffsets == 1 && maxRanks[0] == 1) && // NOLINT
230 numMixedOffsets != numMixedSizes)
231 return op->emitError(
232 "expected mixed offsets rank to match mixed sizes rank (")
233 << numMixedOffsets << " vs " << numMixedSizes
234 << ") so the rank of the result type is well-formed.";
235 for (int64_t offset : op.getStaticOffsets())
236 if (offset < 0 && !ShapedType::isDynamic(offset))
237 return op->emitError("expected offsets to be non-negative, but got ")
238 << offset;
239 for (int64_t size : op.getStaticSizes())
240 if (size < 0 && !ShapedType::isDynamic(size))
241 return op->emitError("expected sizes to be non-negative, but got ")
242 << size;
243
244 return success();
245}
246
247static VC1902TargetModel VC1902model;
248static VE2302TargetModel VE2302model;
249static VE2802TargetModel VE2802model;
250static VE3858TargetModel VE3858model;
251static VirtualizedNPU1TargetModel NPUmodel1col(1);
252static VirtualizedNPU1TargetModel NPUmodel2col(2);
253static VirtualizedNPU1TargetModel NPUmodel3col(3);
254static VirtualizedNPU1TargetModel NPUmodel4col(4);
255static NPU2TargetModel NPU2model;
256static VirtualizedNPU2TargetModel NPU2model1col(1);
257static VirtualizedNPU2TargetModel NPU2model2col(2);
258static VirtualizedNPU2TargetModel NPU2model3col(3);
259static VirtualizedNPU2TargetModel NPU2model4col(4);
260static VirtualizedNPU2TargetModel NPU2model5col(5);
261static VirtualizedNPU2TargetModel NPU2model6col(6);
262static VirtualizedNPU2TargetModel NPU2model7col(7);
263static NPU3TargetModel NPU3model;
264static VirtualizedNPU3TargetModel NPU3model1col(1);
265static VirtualizedNPU3TargetModel NPU3model2col(2);
266
267const AIETargetModel &xilinx::AIE::getTargetModel(Operation *op) {
268 if (auto t = dyn_cast<AIETarget>(op))
269 return t.getTargetModel();
270 if (auto t = op->getParentOfType<AIETarget>())
271 return t.getTargetModel();
272
273 // For backward compatibility, return a basic device model compatible with
274 // the VCK190
275 return VC1902model;
276}
277
279 return getTargetModel(a.getOperation())
280 .getSharedMemory({a.getCol(), a.getRow()}, {b.getCol(), b.getRow()});
281}
282
284 switch (device) {
285 case AIEDevice::xcvc1902:
286 return VC1902model;
287 case AIEDevice::xcve2302:
288 return VE2302model;
289 case AIEDevice::xcve2802:
290 return VE2802model;
291 case AIEDevice::npu1:
292 return NPUmodel4col;
293 case AIEDevice::npu1_1col:
294 return NPUmodel1col;
295 case AIEDevice::npu1_2col:
296 return NPUmodel2col;
297 case AIEDevice::npu1_3col:
298 return NPUmodel3col;
299 case AIEDevice::npu2:
300 return NPU2model;
301 case AIEDevice::npu2_1col:
302 return NPU2model1col;
303 case AIEDevice::npu2_2col:
304 return NPU2model2col;
305 case AIEDevice::npu2_3col:
306 return NPU2model3col;
307 case AIEDevice::npu2_4col:
308 return NPU2model4col;
309 case AIEDevice::npu2_5col:
310 return NPU2model5col;
311 case AIEDevice::npu2_6col:
312 return NPU2model6col;
313 case AIEDevice::npu2_7col:
314 return NPU2model7col;
315 case AIEDevice::xcve3858:
316 return VE3858model;
317 case AIEDevice::npu3:
318 return NPU3model;
319 case AIEDevice::npu3_1col:
320 return NPU3model1col;
321 case AIEDevice::npu3_2col:
322 return NPU3model2col;
323 }
324 // No default: label above, so -Wswitch still reports a newly added device.
325 // This handles values that are not enumerators at all, which
326 // aieGetTargetModel admits by casting an unchecked uint32_t.
327 llvm::report_fatal_error("getTargetModel: unknown AIEDevice value " +
328 llvm::Twine(static_cast<uint32_t>(device)));
329}
330
331// Walk the operation hierarchy until we find a containing TileElement.
332// If no parent is a TileElement, then return null.
333static TileElement getParentTileElement(Operation *op) {
334 auto *parent = op->getParentOp();
335 while (!llvm::isa_and_nonnull<DeviceOp, ModuleOp>(parent)) {
336 if (auto element = llvm::dyn_cast<TileElement>(parent))
337 return element;
338 parent = parent->getParentOp();
339 }
340 return llvm::dyn_cast<TileElement>(parent);
341}
342
343// Returns the maximum index described by the input dimensions.
344static int64_t getDimsMaxIdx(ArrayRef<BDDimLayoutAttr> dims) {
345 int64_t maxIdx = 0;
346 for (BDDimLayoutAttr dim : dims) {
347 maxIdx += dim.getStride() * (dim.getSize() - 1);
348 }
349 return maxIdx;
350}
351
353 int64_t elements = 1;
354 for (BDDimLayoutAttr dim : inner)
355 elements *= dim.getSize();
356 return elements;
357}
358
360 ArrayRef<BDDimLayoutAttr> dims, ArrayRef<BDPadLayoutAttr> pads,
361 int64_t objectSize, function_ref<InFlightDiagnostic()> emitError,
362 StreamWindow &window) {
363 if (dims.size() < 2)
364 return emitError() << "a walk over a stream needs an outer dimension of "
365 "outputs and at least one inner dimension";
366 StreamWindow w;
367 w.objectSize = objectSize;
368 w.outputs = dims.front().getSize();
369 int64_t outerStride = dims.front().getStride();
370 if (outerStride % objectSize)
371 return emitError() << "a walk over a stream steps whole objects between "
372 "outputs, but its outer stride "
373 << outerStride << " is not a multiple of the "
374 << objectSize << "-element object";
375 w.advance = outerStride / objectSize;
376 w.inner.assign(dims.begin() + 1, dims.end());
377 w.rowDim = -1;
378 int64_t reach = 0;
379 for (auto [index, dim] : llvm::enumerate(w.inner)) {
380 if (dim.getSize() > 1 && dim.getStride() >= objectSize) {
381 if (w.rowDim >= 0 || dim.getStride() != objectSize)
382 return emitError() << "a walk over a stream may step one inner "
383 "dimension by exactly one "
384 << objectSize << "-element object";
385 w.rowDim = index;
386 continue;
387 }
388 reach += dim.getStride() * (dim.getSize() - 1);
389 }
390 if (reach >= objectSize)
391 return emitError() << "a walk over a stream reads " << reach + 1
392 << " elements of each object, past the " << objectSize
393 << "-element object";
394 w.span = w.rowDim >= 0 ? w.inner[w.rowDim].getSize() : 1;
395 w.top = w.bottom = 0;
396 for (auto [index, pad] : llvm::enumerate(pads)) {
397 if (index == 0) {
398 w.top = pad.getConstPadBefore();
399 w.bottom = pad.getConstPadAfter();
400 } else if (pad.getConstPadBefore() || pad.getConstPadAfter()) {
401 return emitError() << "a walk over a stream pads only its outer "
402 "dimension, with the objects before and after "
403 "the stream";
404 }
405 }
406 w.objects = (w.outputs - 1) * w.advance + w.span - w.top - w.bottom;
407 if (w.objects < w.span || w.top >= w.span || w.bottom >= w.span)
408 return emitError() << "a walk over a stream of " << w.objects
409 << " objects with " << w.top << " and " << w.bottom
410 << " padding objects leaves an output without data";
411 window = w;
412 return success();
413}
414
415SmallVector<StreamWindowStep>
417 SmallVector<StreamWindowStep> steps;
418 int64_t acquired = 0, released = 0;
419 for (int64_t j = 0; j < w.outputs; j++) {
420 int64_t start = j * w.advance - w.top;
421 int64_t newest = std::max(
422 acquired, start + std::clamp<int64_t>(w.objects - start, 0, w.span));
423 int64_t next =
424 j + 1 < w.outputs
425 ? std::clamp<int64_t>((j + 1) * w.advance - w.top, 0, newest)
426 : w.objects;
427 next = std::max(released, next);
428 steps.push_back({j * w.advance, newest - acquired, next - released});
429 acquired = newest;
430 released = next;
431 }
432 return steps;
433}
434
435namespace {
436
437struct UsesAreAccessible {
438 static LogicalResult verifyTrait(Operation *op) {
439 auto thisElement = cast<TileElement>(op);
440
441 // Skip accessibility checks for logical tiles as we cannot tell until tile
442 // is placed
443 if (!isa<TileOp>(thisElement.getTile().getDefiningOp()))
444 return success();
445
446 auto thisID = thisElement.getTileID();
447 auto users = op->getResult(0).getUsers();
448 const auto &targetModel = getTargetModel(op);
449 for (auto *user : users) {
450 // AIE.useLock may be used in a device to set the lock's default value
451 // Allow in a toplevel module for backward compatibility
452 if (llvm::isa_and_nonnull<DeviceOp, ModuleOp>(user->getParentOp())) {
453 continue;
454 }
455 // If any parent or the user itself prescribe that accessibility checks be
456 // skipped, skip the check for that user.
457 if (user->getParentWithTrait<SkipAccessibilityCheckTrait>() ||
458 user->hasTrait<SkipAccessibilityCheckTrait>()) {
459 continue;
460 }
461 TileElement element = llvm::dyn_cast<TileElement>(user);
462 if (!element) {
463 element = getParentTileElement(user);
464 }
465 if (!element) {
466 // This should probably be caught elsewhere as well.
467 return op->emitOpError("is accessed outside of a tile")
468 .attachNote(user->getLoc())
469 << "user";
470 }
471 auto tileID = element.getTileID();
472 if (!targetModel.isLegalMemAffinity(tileID.col, tileID.row, thisID.col,
473 thisID.row)) {
474 return (op->emitOpError("in Column ")
475 << thisID.col << " and Row " << thisID.row
476 << " is accessed from an unreachable tile in Column "
477 << tileID.col << " and Row " << tileID.row)
478 .attachNote(user->getLoc())
479 << "user";
480 }
481 }
482 return success();
483 }
484};
485
486} // namespace
487
488// Check that the operation only contains terminators in
489// TerminatorOpTypes.
490template <typename... TerminatorOpTypes>
492 static LogicalResult verifyTrait(Operation *op) {
493 for (auto &region : op->getRegions()) {
494 for (auto &block : region) {
495 if (!block.empty()) {
496 if (Operation *operation = &block.back();
497 !llvm::isa_and_nonnull<TerminatorOpTypes...>(operation))
498 return operation->emitOpError("is not an allowed terminator")
499 .attachNote(op->getLoc())
500 .append("in this context: ");
501 }
502 }
503 }
504 return success();
505 }
506};
507
508// AIE4 channels draw from small BD pools that may reuse ids. Check each pool's
509// BDs fit, pinned ids lie in the chain's pool, and no BD is reached from two
510// pools.
511static LogicalResult verifyBdPools(Operation *op, Region &body, TileLike tile,
512 const AIETargetModel &targetModel) {
513 std::optional<int> col = tile.tryGetCol();
514 std::optional<int> row = tile.tryGetRow();
515 if (!col || !row)
516 return success();
517
518 DenseMap<Block *, SmallVector<DMAChannel, 1>> blockChannels;
519 for (Block &block : body) {
520 for (auto dmaStart : block.getOps<DMAStartOp>()) {
521 // No channel index until --aie-objectfifo-allocate.
522 if (dmaStart.getEndpoint())
523 continue;
524 DMAChannel chan = {dmaStart.getChannelDir(), dmaStart.getChannelIndex()};
525 if (chan.channel < 0 || !targetModel.isDmaChannelSupported(
526 {*col, *row}, chan.direction, chan.channel))
527 continue;
528 SmallPtrSet<Block *, 16> visited;
529 SmallVector<Block *> worklist = {dmaStart.getDest()};
530 while (!worklist.empty()) {
531 Block *bdBlock = worklist.pop_back_val();
532 if (!visited.insert(bdBlock).second)
533 continue;
534 blockChannels[bdBlock].push_back(chan);
535 if (bdBlock->mightHaveTerminator())
536 llvm::append_range(worklist,
537 bdBlock->getTerminator()->getSuccessors());
538 }
539 }
540 }
541
542 // Channels sharing a pool compete for it, so both forms share the counters.
543 DenseMap<uint32_t, uint32_t> poolBdCount;
544 auto checkBds = [&](DMAChannel chan, uint32_t pool,
545 MutableArrayRef<DMABDOp> bdOps) -> LogicalResult {
546 uint32_t poolSize = targetModel.getNumBDsInPool(*col, *row, pool);
547 if (++poolBdCount[pool] > poolSize)
548 return (op->emitOpError("BD pool for channel (")
549 << stringifyDMAChannelDir(chan.direction) << ", " << chan.channel
550 << ") exceeds limit of " << poolSize << " BDs")
551 .attachNote(bdOps.front().getLoc())
552 .append("no space for this BD");
553
554 uint32_t poolStart = targetModel.getBdPoolStartId(*col, *row, pool);
555 auto checkBdId = [&](DMABDOp bdOp, std::optional<int32_t> id,
556 StringRef what) -> LogicalResult {
557 if (!id || *id < 0 ||
558 targetModel.isBdChannelAccessible(*col, *row,
559 static_cast<uint32_t>(*id),
560 chan.channel, chan.direction))
561 return success();
562 return (op->emitOpError(what)
563 << " " << *id << " is not accessible from channel ("
564 << stringifyDMAChannelDir(chan.direction) << ", " << chan.channel
565 << "), whose BD pool spans ids " << poolStart << " to "
566 << (poolStart + poolSize - 1))
567 .attachNote(bdOp.getLoc())
568 .append("this BD");
569 };
570 for (DMABDOp bdOp : bdOps) {
571 if (failed(checkBdId(bdOp, bdOp.getBdId(), "bd_id")) ||
572 failed(checkBdId(bdOp, bdOp.getNextBdId(), "next_bd_id")))
573 return failure();
574 }
575 return success();
576 };
577
578 for (Block &block : body) {
579 auto it = blockChannels.find(&block);
580 if (it == blockChannels.end())
581 continue;
582 auto bdOps = llvm::to_vector_of<DMABDOp>(block.getOps<DMABDOp>());
583 if (bdOps.empty())
584 continue;
585 DMAChannel chan = it->second.front();
586 uint32_t pool =
587 targetModel.getBdPoolId(*col, *row, chan.channel, chan.direction);
588 for (DMAChannel other : llvm::drop_begin(it->second))
589 if (targetModel.getBdPoolId(*col, *row, other.channel, other.direction) !=
590 pool)
591 return (op->emitOpError("BD is reached from channels (")
592 << stringifyDMAChannelDir(chan.direction) << ", "
593 << chan.channel << ") and ("
594 << stringifyDMAChannelDir(other.direction) << ", "
595 << other.channel
596 << "), which draw from different BD pools; one BD cannot "
597 "serve both")
598 .attachNote(bdOps.front().getLoc())
599 .append("this BD");
600 if (failed(checkBds(chan, pool, bdOps)))
601 return failure();
602 }
603
604 // Region form: each aie.dma region is one BD of that op's channel.
605 for (auto dma : body.getOps<DMAOp>()) {
606 DMAChannel chan = {dma.getChannelDir(),
607 static_cast<int>(dma.getChannelIndex())};
608 if (chan.channel < 0 || !targetModel.isDmaChannelSupported(
609 {*col, *row}, chan.direction, chan.channel))
610 continue;
611 uint32_t pool =
612 targetModel.getBdPoolId(*col, *row, chan.channel, chan.direction);
613 for (Region &bdRegion : dma.getBds()) {
614 auto bdOps = llvm::to_vector_of<DMABDOp>(bdRegion.getOps<DMABDOp>());
615 if (!bdOps.empty() && failed(checkBds(chan, pool, bdOps)))
616 return failure();
617 }
618 }
619 return success();
620}
621
622// Check that the given DMA-like op (e.g. MemOp, ShimDMAOp)
623// has valid BDs.
624template <typename ConcreteType>
625LogicalResult HasValidBDs<ConcreteType>::verifyTrait(Operation *op) {
626 auto element = cast<ConcreteType>(op);
627 const auto &targetModel = getTargetModel(op);
628
629 TileLike tile = element.getTileLike();
630 if (!tile)
631 return op->emitOpError("tile must implement TileLike interface");
632
633 if (isa<AIE4TargetModel>(targetModel) &&
634 failed(verifyBdPools(op, element.getBody(), tile, targetModel)))
635 return failure();
636
637 int bdMax = targetModel.getTotalNumBDs(tile.getTileType());
638
639 int bdNum = 0;
640 for (auto &block : element.getBody()) {
641 auto bdOps = llvm::to_vector_of<DMABDOp>(block.template getOps<DMABDOp>());
642
643 // Skip entry/end block
644 if (bdOps.empty())
645 continue;
646
647 // Check BD count limit
648 if (bdNum >= bdMax) {
649 return (op->emitOpError("has more than ") << bdMax << " blocks")
650 .attachNote(bdOps.front().getLoc())
651 .append("no space for this BD");
652 }
653 bdNum++;
654
655 // Check exactly 1 DMABDOp per BD block
656 if (bdOps.size() != 1) {
657 return (op->emitOpError("BD block must have exactly one DMABDOp, found ")
658 << bdOps.size())
659 .attachNote(block.front().getLoc())
660 .append("in this BD block");
661 }
662
663 // Check at most 2 UseLockOps per BD block (1 acquire, 1 release)
664 auto useLockOps =
665 llvm::to_vector_of<UseLockOp>(block.template getOps<UseLockOp>());
666 int acquireCount = 0;
667 int releaseCount = 0;
668 for (auto useLock : useLockOps) {
669 if (useLock.acquire() || useLock.acquireGE())
670 acquireCount++;
671 else if (useLock.release())
672 releaseCount++;
673 }
674
675 if (acquireCount > 1) {
676 return (op->emitOpError(
677 "BD block must have at most one acquire UseLockOp, found ")
678 << acquireCount)
679 .attachNote(block.front().getLoc())
680 .append("in this BD block");
681 }
682 if (releaseCount > 1) {
683 return (op->emitOpError(
684 "BD block must have at most one release UseLockOp, found ")
685 << releaseCount)
686 .attachNote(block.front().getLoc())
687 .append("in this BD block");
688 }
689 }
690 return success();
691}
692
693// Check that the given DMA-like op (e.g. MemOp, ShimDMAOp)
694// has valid DMA channels.
695template <typename ConcreteType>
697 DenseSet<DMAChannel> inputChannels;
698 DenseSet<DMAChannel> outputChannels;
699 DenseSet<std::pair<DMAChannelDir, StringAttr>> namedChannels;
700 auto element = cast<ConcreteType>(op);
701 Region &body = element.getBody();
702 if (body.empty())
703 return op->emitOpError("should have non-empty body");
704 for (auto &bodyOp : body.getOps()) {
705 // check for duplicate DMA channels within the same ShimDMAOp
706 if (auto dmaStart = dyn_cast<DMAStartOp>(bodyOp)) {
707 if (FlatSymbolRefAttr endpoint = dmaStart.getEndpoint()) {
708 namedChannels.insert({dmaStart.getChannelDir(), endpoint.getAttr()});
709 continue;
710 }
711 DMAChannel dmaChan = {dmaStart.getChannelDir(),
712 dmaStart.getChannelIndex()};
713 // Control/trace channels are verified by aie.dma_start.
714 if (getDMAChannelBundle(dmaChan.direction) != WireBundle::DMA)
715 continue;
716 // check if number of input and output channels is more than available
717 // hardware
718 if (dmaChan.direction == DMAChannelDir::S2MM)
719 inputChannels.insert(dmaChan);
720 else
721 outputChannels.insert(dmaChan);
722 }
723 }
724
725 TileLike tile = element.getTileLike();
726 if (!tile)
727 return op->emitOpError("tile must implement TileLike interface");
728
729 auto named = [&](DMAChannelDir dir) -> size_t {
730 return llvm::count_if(namedChannels,
731 [&](auto channel) { return channel.first == dir; });
732 };
733 if (inputChannels.size() + named(DMAChannelDir::S2MM) >
734 tile.getNumSourceConnections(WireBundle::DMA))
735 return op->emitOpError(
736 "uses more input channels than available on this tile");
737
738 if (outputChannels.size() + named(DMAChannelDir::MM2S) >
739 tile.getNumDestConnections(WireBundle::DMA))
740 return op->emitOpError(
741 "uses more output channels than available on this tile");
742 return success();
743}
744
745LogicalResult
746LockAcquireAttr::verify(function_ref<InFlightDiagnostic()> emitError,
747 int32_t column, int32_t row, int32_t lock_id,
748 LockAction action, int32_t value) {
749 if (column < 0 || row < 0 || lock_id < 0)
750 return emitError() << "lock column, row, and ID must be non-negative";
751 if (action != LockAction::Acquire &&
752 action != LockAction::AcquireGreaterEqual)
753 return emitError() << "expected Acquire or AcquireGreaterEqual, got "
754 << stringifyLockAction(action);
755 return success();
756}
757
758//===----------------------------------------------------------------------===//
759// ObjectFifoTransportAttr
760//===----------------------------------------------------------------------===//
761
762LogicalResult
763ObjectFifoTransportAttr::verify(function_ref<InFlightDiagnostic()> emitError,
764 ObjectFifoTransportMode mode,
765 PacketInfoAttr packet, bool out_of_order) {
766 // A packet header rides a stream-switch connection the DMAs drive, so only
767 // the paths that may use the DMAs can honour one.
768 if (packet && mode == ObjectFifoTransportMode::SharedMem)
769 return emitError() << "`packet` belongs to a dma or auto transport, not "
770 << stringifyObjectFifoTransportMode(mode);
771 if (out_of_order && !packet)
772 return emitError() << "`out_of_order` requires a packet transport";
773 return success();
774}
775
776//===----------------------------------------------------------------------===//
777// ConsumedByAttr
778//===----------------------------------------------------------------------===//
779
780LogicalResult
781ConsumedByAttr::verify(function_ref<InFlightDiagnostic()> emitError,
782 FlatSymbolRefAttr output, int64_t input_bytes,
783 int64_t output_bytes, int64_t granule_bytes,
784 FlatSymbolRefAttr device) {
785 if (input_bytes <= 0 || output_bytes <= 0)
786 return emitError() << "consumed_by needs positive byte counts, got "
787 << input_bytes << " and " << output_bytes;
788 if (granule_bytes < 0)
789 return emitError() << "consumed_by needs a granule of 0 or more bytes, got "
790 << granule_bytes;
791 return success();
792}
793
794//===----------------------------------------------------------------------===//
795// ObjectFifoEndPortAttr
796//===----------------------------------------------------------------------===//
797
798LogicalResult
799ObjectFifoEndPortAttr::verify(function_ref<InFlightDiagnostic()> emitError,
800 WireBundle bundle,
801 std::optional<uint32_t> channel) {
802 if (bundle != WireBundle::DMA && bundle != WireBundle::Core)
803 return emitError() << "an objectFifo end is driven by a DMA channel or a "
804 "Core stream port, not "
805 << stringifyWireBundle(bundle);
806 if (bundle == WireBundle::Core) {
807 if (!channel)
808 return emitError() << "a Core end needs its stream port";
809 if (*channel > 1)
810 return emitError() << "a Core end's stream port is 0 or 1, not "
811 << *channel;
812 }
813 return success();
814}
815
816//===----------------------------------------------------------------------===//
817// ObjectFifoCreateOp
818//===----------------------------------------------------------------------===//
819
820// Each initial value is one object's dense contents, in the object's shape
821// and element type: that is all a buffer can be loaded with.
822static LogicalResult verifyInitValues(Operation *op, ArrayAttr initValues,
823 MemRefType object) {
824 for (Attribute value : initValues) {
825 auto dense = dyn_cast<DenseElementsAttr>(value);
826 if (!dense)
827 return op->emitOpError("initial value ")
828 << value << " is not a dense elements attribute";
829 if (dense.getType().getShape() != object.getShape() ||
830 dense.getElementType() != object.getElementType())
831 return op->emitOpError("initial value of type ")
832 << dense.getType() << " does not match the object type " << object;
833 }
834 return success();
835}
836
837LogicalResult ObjectFifoCreateOp::verify() {
838 for (Type fifoType : {Type(getElemType()), getConsumerElemTypeOrDefault()})
839 if (MemRefType memref = cast<AIEObjectFifoType>(fifoType).getElementType();
840 !memref.hasStaticShape())
841 return emitOpError("type should be static shaped memref, but got ")
842 << memref;
843
844 // MLIR carries an attribute it does not know about rather than rejecting it,
845 // so IR written against the switches these replaced would keep parsing and
846 // quietly take the default path instead. Name them to fail that loudly.
847 static constexpr std::pair<llvm::StringLiteral, llvm::StringLiteral>
848 replaced[] = {
849 {"out_of_order", "transport = #aie.transport<dma, packet = "
850 "#aie.packet_info<>, out_of_order = true>"},
851 {"via_DMA", "transport = #aie.transport<dma>"},
852 {"packet", "transport = #aie.transport<dma, packet = "
853 "#aie.packet_info<>>"},
854 {"packet_id", "transport = #aie.transport<dma, packet = "
855 "#aie.packet_info<pkt_id = 3>>"},
856 {"aie_stream", "prod_port = #aie.end_port<Core : 0> or cons_ports "
857 "= [#aie.end_port<Core : 0>]"},
858 {"aie_stream_port", "prod_port = #aie.end_port<Core : 0> or "
859 "cons_ports = [#aie.end_port<Core : 0>]"},
860 {"prod_dma_channel", "prod_port = #aie.end_port<DMA : 1>"},
861 {"cons_dma_channels", "cons_ports = [#aie.end_port<DMA : 1>]"}};
862 for (auto [gone, replacement] : replaced)
863 if ((*this)->hasAttr(gone))
864 return emitOpError("`")
865 << gone << "` has been replaced; write " << replacement;
866
867 if (isa<ArrayAttr>(getElemNumber())) {
868 if (size_t numDepths = dyn_cast<ArrayAttr>(getElemNumber()).size();
869 numDepths != getConsumerTiles().size() + 1) // +1 for producer depth
870 return emitOpError("does not have enough depths specified for producer "
871 "and for each consumer.");
872 }
873
874 if (ArrayAttr consPorts = getConsPortsAttr();
875 consPorts && consPorts.size() != getConsumerTiles().size())
876 return emitOpError("`cons_ports` has ")
877 << consPorts.size() << " entries for " << getConsumerTiles().size()
878 << " consumers";
879
880 // Helper to get tile interface from Value. A block argument has no defining
881 // op.
882 auto getTileLikeFromValue = [](Value v) -> TileLike {
883 return llvm::dyn_cast_or_null<TileLike>(v.getDefiningOp());
884 };
885
886 TileLike producerTile = getTileLikeFromValue(getProducerTile());
887 if (!producerTile)
888 return emitError("producer tile must implement TileLike interface");
889
890 // data layout transformations on shim tiles are handled by runtime operations
891 if (producerTile.isShimTile() && !getDimensionsToStream().empty()) {
892 return emitError(
893 "`dimensionsToStream` data layout transformations are not supported "
894 "on shim tile producers");
895 }
896 for (auto consTileVal : getConsumerTiles()) {
897 TileLike consTile = getTileLikeFromValue(consTileVal);
898 if (!consTile)
899 return emitError("consumer tile must implement TileLike interface");
900 if (consTile.isShimTile() &&
901 !getDimensionsFromStream(consTileVal).empty()) {
902 return emitError(
903 "`dimensionsFromStreamPerConsumer` data layout transformations are "
904 "not supported on shim tile consumers");
905 }
906 }
907
908 // A core takes its consumer accesses from the first of its tile's ends
909 // a link does not already claim; a link on the tile reads one end each
910 // (getConsumerLink), in the order its own aie.objectfifo.link ops appear.
911 for (auto [index, consumer] : llvm::enumerate(getConsumerTiles())) {
912 size_t first =
913 llvm::find(getConsumerTiles(), consumer) - getConsumerTiles().begin();
914 TileLike tile = getTileLikeFromValue(consumer);
915 if (first == index || tile.getTileType() != AIETileType::CoreTile ||
916 getConsumerLink(index))
917 continue;
918 InFlightDiagnostic diag = emitOpError("lists core tile ");
919 if (std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
920 col && row)
921 diag << "(" << *col << ", " << *row << ") ";
922 diag << "as consumers " << first << " and " << index
923 << "; its core reads only the first of those ends, so the other "
924 "would never be drained";
925 diag.attachNote(consumer.getLoc()) << "the tile";
926 return diag;
927 }
928
929 if (getRepeatCount().has_value()) {
930 if (producerTile.isShimTile())
931 return emitError("`repeat_count` unavailable for shim tiles");
932 }
933
934 if (getPadValue() != 0) {
935 if (!getPadDimensions().has_value())
936 return emitError("`padValue` requires `padDimensions`");
937 if (!getTargetModel(getOperation()).isMemTilePadValueSupported())
938 return emitError("`padValue` requires the CONSTANT_PAD_VALUE register, "
939 "unavailable on this target");
940 }
941
942 if (usesStream()) {
943 if (getConsumerTiles().size() > 1)
944 return emitError("a Core stream port end can only be used in 1-to-1 "
945 "object FIFOs");
946
947 if (forcesSharedMemory())
948 return emitError("a Core stream port end sends over the stream, not "
949 "through shared memory");
950
951 if (streamsFromProducer()) {
952 if (producerTile.isShimTile() || producerTile.isMemTile())
953 return emitError(
954 "a Core stream port end is not available for shim and mem tiles");
955
956 if (getRepeatCount().has_value())
957 return emitError("`repeat_count` unavailable on stream end");
958
959 if (getInitValues().has_value())
960 return emitError("`init_values` unavailable on stream end");
961
962 if (getIterCount().has_value())
963 return emitError("`iter_count` unavailable on stream end");
964
965 if (!getDimensionsToStream().empty())
966 return emitError("`dimensionsToStream` data layout transformations are "
967 "unavailable on stream end");
968 }
969
970 if (streamsToConsumer(0)) {
971 TileLike consTile = getTileLikeFromValue(getConsumerTiles()[0]);
972 if (consTile && (consTile.isShimTile() || consTile.isMemTile()))
973 return emitError(
974 "a Core stream port end is not available for shim and mem tiles");
975 }
976
977 if (!getDimensionsFromStreamPerConsumer()[0].empty())
978 return emitError("`dimensionsFromStreamPerConsumer` data layout "
979 "transformations are unavailable on stream end");
980 }
981
982 if (getInitValues().has_value()) {
983 if (producerTile.isShimTile())
984 return emitError("`init_values` unavailable for shim tiles");
985 }
986
987 if (auto initValues = getInitValues()) {
988 if ((int)initValues->size() != size())
989 return emitError("`init_values` does not initialize all objects");
990 if (failed(verifyInitValues(
991 *this, *initValues,
992 cast<AIEObjectFifoType>(getElemType()).getElementType())))
993 return failure();
994 }
995
996 if (auto iterCountAttr = getIterCount()) {
997 int iterCount = *iterCountAttr;
998 if (iterCount < 1 || iterCount > 256)
999 return emitError("`iter_count` must be between 1 and 256");
1000 }
1001
1002 if (auto consumerElemType = getConsumerElemType()) {
1003 auto consType = llvm::dyn_cast<AIEObjectFifoType>(*consumerElemType);
1004 if (!consType)
1005 return emitError("consumer element type must be an "
1006 "!aie.objectfifo<memref<...>> type");
1007 auto prodType = llvm::cast<AIEObjectFifoType>(getElemType());
1008 auto prodMemref = prodType.getElementType();
1009 auto consMemref = consType.getElementType();
1010 if (prodMemref.getElementType() != consMemref.getElementType())
1011 return emitError("producer and consumer must have the same scalar "
1012 "element type, but got ")
1013 << prodMemref.getElementType() << " vs "
1014 << consMemref.getElementType();
1015 int64_t prodSize = prodMemref.getNumElements();
1016 int64_t consSize = consMemref.getNumElements();
1017 if (consSize <= 0)
1018 return emitError("consumer element count must be positive");
1019 if (prodSize % consSize != 0)
1020 return emitError("producer element size (")
1021 << prodSize << ") must be an integer multiple of consumer "
1022 << "element size (" << consSize << ")";
1023 }
1024
1025 return success();
1026}
1027
1028TileOp ObjectFifoCreateOp::getProducerTileOp() {
1029 return cast<TileOp>(getProducerTile().getDefiningOp());
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// ObjectFifoPoolOp
1034//===----------------------------------------------------------------------===//
1035
1036namespace {
1037/// Resolve a list of symbol names to the ops they name, skipping any that are
1038/// not yet declared.
1039template <typename OpTy>
1040SmallVector<OpTy> lookupAll(Operation *from, std::optional<ArrayAttr> names) {
1041 SmallVector<OpTy> ops;
1042 if (names) {
1043 for (auto name : names->getAsRange<FlatSymbolRefAttr>()) {
1044 if (auto op =
1045 dyn_cast_or_null<OpTy>(lookupNamedOp(from, name.getAttr()))) {
1046 ops.push_back(op);
1047 }
1048 }
1049 }
1050 return ops;
1051}
1052
1053} // namespace
1054
1055TileLike ObjectFifoPoolOp::getTileLike() {
1056 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1057}
1058
1059int64_t ObjectFifoPoolOp::getObjectSize() {
1060 return llvm::cast<MemRefType>(getElemType()).getNumElements();
1061}
1062
1063int64_t ObjectFifoPoolOp::getObjectsPerBuffer() {
1064 if (!getContiguous())
1065 return 1;
1066 int64_t objects = getDepth();
1067 if (auto zeros = getZeroObjects())
1068 objects += (*zeros)[0] + (*zeros)[1];
1069 return objects;
1070}
1071
1072LogicalResult ObjectFifoPoolOp::verify() {
1073 if (!getTileLike())
1074 return emitOpError("tile operand is not an aie.tile or aie.logical_tile");
1075 auto &target = (*this)->getParentOfType<DeviceOp>().getTargetModel();
1076 bool semaphoreLocks = target.hasProperty(AIETargetModel::UsesSemaphoreLocks);
1077
1078 // A binary lock travels with the buffer it guards; a semaphore lock counts
1079 // objects for a whole segment.
1080 if (auto locks = getLocks()) {
1081 if (semaphoreLocks) {
1082 return emitOpError("'locks' names binary locks, which this device has "
1083 "no use for");
1084 }
1085 if (static_cast<int64_t>(locks->size()) != getDepth()) {
1086 return emitOpError("expects one lock per buffer");
1087 }
1088 }
1089
1090 if (auto zeros = getZeroObjects()) {
1091 if (!getContiguous() || zeros->size() != 2 ||
1092 llvm::any_of(*zeros, [](int32_t count) { return count < 0; }))
1093 return emitOpError("'zeroObjects' expects [before, after] counts on a "
1094 "contiguous pool");
1095 }
1096
1097 if (auto buffers = getBuffers()) {
1098 if (getContiguous() && buffers->size() != 1) {
1099 return emitOpError("expects one buffer holding its objects side by side");
1100 }
1101 if (!getContiguous() &&
1102 static_cast<int64_t>(buffers->size()) != getDepth()) {
1103 return emitOpError("expects 'depth' buffers");
1104 }
1105 }
1106
1107 if (auto initValues = getInitValues()) {
1108 if (static_cast<int64_t>(initValues->size()) > getDepth()) {
1109 return emitOpError("has more 'init_values' than 'depth' objects");
1110 }
1111 if (failed(verifyInitValues(*this, *initValues, getElemType())))
1112 return failure();
1113 }
1114
1115 std::vector<ObjectFifoSegmentOp> segments = getSegmentOps();
1116 if (segments.empty()) {
1117 return emitOpError("expects at least one segment");
1118 }
1119
1120 int64_t previous = -1;
1121 int64_t covered = 0;
1122 for (ObjectFifoSegmentOp segment : segments) {
1123 if (static_cast<int64_t>(segment.getOffset()) <= previous) {
1124 return emitOpError("segments must be ordered by increasing offset");
1125 }
1126 if (static_cast<int64_t>(segment.getOffset()) != covered) {
1127 return segment.emitOpError("leaves a gap or overlaps the segment before "
1128 "it; segments must tile the object");
1129 }
1130 previous = segment.getOffset();
1131 covered = segment.getOffset() + segment.getSize();
1132 if (!semaphoreLocks &&
1133 (segment.getProduceLock() || segment.getConsumeLock())) {
1134 return emitOpError("segment locks are counting locks, which this "
1135 "device has no use for");
1136 }
1137 }
1138
1139 if (covered != getObjectSize()) {
1140 return emitOpError("segments cover ")
1141 << covered << " of " << getObjectSize() << " elements";
1142 }
1143
1144 if (segments.size() > 1 && !semaphoreLocks) {
1145 return emitOpError(
1146 "multi-segment pools are unsupported on binary lock architectures");
1147 }
1148
1149 return success();
1150}
1151
1152int64_t xilinx::AIE::getMemRefSizeInBytes(MemRefType type,
1153 const DataLayout &layout) {
1154 return type.getNumElements() * layout.getTypeSize(type.getElementType());
1155}
1156
1157int64_t ObjectFifoPoolOp::getObjectSizeInBytes() {
1158 return getMemRefSizeInBytes(getElemType(), DataLayout::closest(*this));
1159}
1160
1161// Whether one iterating descriptor could walk a pool of `depth` objects on a
1162// tile: a mem tile's pool, deeper than one object and no deeper than a lock
1163// counts (ObjectFifoPoolOp::canWalkWhole, ObjectFifoCreateOp::plannedDmaEnd).
1164static bool walksWholeDepth(bool isMemTile, int64_t depth,
1165 int64_t maxLockValue) {
1166 return isMemTile && depth > 1 && depth <= maxLockValue;
1167}
1168
1169// Whether `fifo`'s producer DMA end pushes a task per object: it asks for
1170// `push_queue`, or sharesSendChannel().
1171static bool usesPushQueue(ObjectFifoCreateOp fifo) {
1172 return fifo.getReleaseStrategy() == ObjectFifoRelease::PushQueue ||
1173 fifo.sharesSendChannel();
1174}
1175
1176std::vector<ObjectFifoSegmentOp> ObjectFifoPoolOp::getSegmentOps() {
1177 auto ops = getSegments().getOps<ObjectFifoSegmentOp>();
1178 return {ops.begin(), ops.end()};
1179}
1180
1181Value BufferOp::getBufferTile() { return getTile(); }
1182
1183SmallVector<BufferLike> ObjectFifoPoolOp::getBufferOps() {
1184 // Buffers and locks live beside the pool, not in the symbol table it opens
1185 // for its segments.
1186 return lookupAll<BufferLike>((*this)->getParentOfType<DeviceOp>(),
1187 getBuffers());
1188}
1189
1190SmallVector<LockOp> ObjectFifoPoolOp::getLockOps() {
1191 auto device = (*this)->getParentOfType<DeviceOp>();
1192 SmallVector<LockOp> locks = lookupAll<LockOp>(device, getLocks());
1193 for (ObjectFifoSegmentOp segment : getSegmentOps()) {
1194 for (std::optional<FlatSymbolRefAttr> name :
1195 {segment.getProduceLockAttr(), segment.getConsumeLockAttr()}) {
1196 if (name && *name) {
1197 if (auto lock = lookupNamedOp<LockOp>(device, name->getAttr())) {
1198 locks.push_back(lock);
1199 }
1200 }
1201 }
1202 }
1203 return locks;
1204}
1205
1206StringRef ObjectFifoPoolOp::getBaseName() {
1207 StringRef name = getSymName();
1208 return name.consume_back("__pool") ? name : getSymName();
1209}
1210
1211bool ObjectFifoPoolOp::canWalkWhole() {
1212 auto device = (*this)->getParentOfType<DeviceOp>();
1213 return walksWholeDepth(
1214 getTileLike().isMemTile(), getDepth(),
1215 static_cast<int64_t>(device.getTargetModel().getMaxLockValue())) &&
1216 !getContiguous() && getSegmentOps().size() == 1 && !getRepeatCount() &&
1217 !getBuffers() &&
1218 llvm::all_of(device.getOps<ObjectFifoDmaEndpointOp>(),
1219 [&](ObjectFifoDmaEndpointOp end) {
1220 auto dims = end.getDimensions();
1221 return end.getPool() != getSymName() ||
1222 (!end.getDispatch() && !end.getOutOfOrder() &&
1223 end.getReleaseStrategy() !=
1224 ObjectFifoRelease::PushQueue &&
1225 (!end.drains() || !dims || dims->empty() ||
1226 (*dims)[0].getValue().empty()));
1227 });
1228}
1229
1230//===----------------------------------------------------------------------===//
1231// ObjectFifo endpoints
1232//===----------------------------------------------------------------------===//
1233
1234namespace {
1235
1236LogicalResult verifyEndpoint(Operation *op, ObjectFifoPoolOp pool,
1237 std::optional<ArrayAttr> segments) {
1238 std::vector<ObjectFifoSegmentOp> all = pool.getSegmentOps();
1239 if (!segments) {
1240 if (all.size() > 1) {
1241 return op->emitOpError(
1242 "must list segments explicitly for a multi-segment pool");
1243 }
1244 return success();
1245 }
1246 if (segments->empty()) {
1247 return op->emitOpError("expects at least one segment");
1248 }
1249
1250 int64_t previous = -1;
1251 for (auto name : segments->getAsRange<FlatSymbolRefAttr>()) {
1252 auto segment = SymbolTable::lookupNearestSymbolFrom<ObjectFifoSegmentOp>(
1253 pool, name.getAttr());
1254 if (!segment) {
1255 return op->emitOpError("references undefined segment '")
1256 << name.getValue() << "' in pool '" << pool.getSymName() << "'";
1257 }
1258 // The endpoint's memref is one run of the object, and `dimensions` pairs
1259 // with this list positionally.
1260 if (static_cast<int64_t>(segment.getOffset()) <= previous) {
1261 return op->emitOpError("segments must be named in increasing offset "
1262 "order");
1263 }
1264 previous = segment.getOffset();
1265 }
1266 return success();
1267}
1268
1269ObjectFifoPoolOp lookupPool(Operation *op, StringRef name) {
1270 auto device = op->getParentOfType<DeviceOp>();
1271 return SymbolTable::lookupNearestSymbolFrom<ObjectFifoPoolOp>(
1272 device, StringAttr::get(op->getContext(), name));
1273}
1274
1275} // namespace
1276
1277/// The subset of `pool`'s segments `selected` names. Omission selects the
1278/// pool's only segment.
1279static std::vector<ObjectFifoSegmentOp>
1280selectSegments(ObjectFifoPoolOp pool, std::optional<ArrayAttr> selected) {
1281 if (!pool) {
1282 return {};
1283 }
1284 std::vector<ObjectFifoSegmentOp> all = pool.getSegmentOps();
1285 if (!selected) {
1286 return all.empty() ? std::vector<ObjectFifoSegmentOp>{}
1287 : std::vector<ObjectFifoSegmentOp>{all.front()};
1288 }
1289 std::vector<ObjectFifoSegmentOp> chosen;
1290 for (auto name : selected->getAsRange<FlatSymbolRefAttr>()) {
1291 if (auto segment =
1292 SymbolTable::lookupNearestSymbolFrom<ObjectFifoSegmentOp>(
1293 pool, name.getAttr())) {
1294 chosen.push_back(segment);
1295 }
1296 }
1297 return chosen;
1298}
1299
1300TileLike ObjectFifoCoreEndpointOp::getTileLike() {
1301 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1302}
1303
1304ObjectFifoPoolOp ObjectFifoCoreEndpointOp::getPoolOp() {
1305 return lookupPool(*this, getPool());
1306}
1307
1308std::vector<ObjectFifoSegmentOp>
1309ObjectFifoCoreEndpointOp::getSelectedSegments() {
1310 return selectSegments(getPoolOp(), getSegments());
1311}
1312
1313LogicalResult ObjectFifoCoreEndpointOp::verify() {
1314 if (!getTileLike())
1315 return emitOpError("tile operand is not an aie.tile or aie.logical_tile");
1316 ObjectFifoPoolOp pool = getPoolOp();
1317 if (!pool) {
1318 return emitOpError("references undefined pool '") << getPool() << "'";
1319 }
1320 if (failed(verifyEndpoint(*this, pool, getSegments()))) {
1321 return failure();
1322 }
1323
1324 if (auto push = getCorePushAttr()) {
1325 if (drains())
1326 return emitOpError("core_push requires a filling core endpoint");
1327 if (auto values = pool.getInitValues(); values && !values->empty())
1328 return emitOpError("core_push does not support initialized objects");
1329 if (push.getBdTags().size() != static_cast<size_t>(pool.getDepth()))
1330 return emitOpError("core_push requires one BD tag per pool buffer");
1331 if (llvm::any_of(push.getBdTags(), [](int32_t tag) { return tag < 0; }))
1332 return emitOpError("core_push requires nonnegative BD tags");
1333 }
1334
1335 // The core sees one memref, so the segments it selects have to be a single
1336 // run of the object.
1337 int64_t next = -1;
1338 for (ObjectFifoSegmentOp segment : getSelectedSegments()) {
1339 if (next >= 0 && segment.getOffset() != next) {
1340 return emitOpError("a core endpoint's segments must be contiguous");
1341 }
1342 next = segment.getOffset() + segment.getSize();
1343 }
1344 return success();
1345}
1346
1347std::pair<int64_t, int64_t> ObjectFifoCoreEndpointOp::getExtent() {
1348 std::vector<ObjectFifoSegmentOp> selected = getSelectedSegments();
1349 if (selected.empty()) {
1350 return {0, 0};
1351 }
1352 int64_t offset = selected.front().getOffset();
1353 int64_t end = selected.back().getOffset() + selected.back().getSize();
1354 return {offset, end - offset};
1355}
1356
1357MemRefType ObjectFifoCoreEndpointOp::getAccessType() {
1358 MemRefType elemType = getPoolOp().getElemType();
1359 auto [offset, size] = getExtent();
1360 if (offset == 0 && size == elemType.getNumElements()) {
1361 return elemType;
1362 }
1363 return cast<MemRefType>(memref::SubViewOp::inferRankReducedResultType(
1364 {size}, elemType, {offset}, {size}, {1}));
1365}
1366
1367TileLike ObjectFifoDmaEndpointOp::getTileLike() {
1368 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1369}
1370
1371ObjectFifoPoolOp ObjectFifoDmaEndpointOp::getPoolOp() {
1372 return lookupPool(*this, getPool());
1373}
1374
1375std::vector<ObjectFifoSegmentOp>
1376ObjectFifoDmaEndpointOp::getSelectedSegments() {
1377 return selectSegments(getPoolOp(), getSegments());
1378}
1379
1380int64_t ObjectFifoDmaEndpointOp::getNumDescriptors() {
1381 ObjectFifoPoolOp pool = getPoolOp();
1382 if (!pool)
1383 return 0;
1384 if (pool.getContiguous()) {
1385 // Taking k turns a pass, k descriptors walk the objects, each k apart.
1386 if (!walksStream()) {
1387 SmallVector<ObjectFifoDmaEndpointOp> ends = turnEndpoints(*this);
1388 if (ends.empty())
1389 return 1;
1390 ArrayRef<Attribute> turns = getTurnsAttr().getValue();
1391 SmallVector<std::pair<int64_t, int64_t>> counts;
1392 for (ObjectFifoDmaEndpointOp end : ends)
1393 counts.push_back(
1394 {llvm::count(turns, FlatSymbolRefAttr::get(end.getSymNameAttr())),
1395 end.getPoolOp().getContiguous() ? 0 : end.getNumDescriptors()});
1396 return llvm::count(turns, FlatSymbolRefAttr::get(getSymNameAttr())) *
1397 turnPasses(counts);
1398 }
1399 StreamWindow window;
1400 return succeeded(getStreamWindow(window)) ? window.outputs : 0;
1401 }
1402 return pool.getDepth() * getSelectedSegments().size();
1403}
1404
1405bool ObjectFifoDmaEndpointOp::walksStream() {
1406 ObjectFifoPoolOp pool = getPoolOp();
1407 auto dims = getDimensions();
1408 return pool && pool.getContiguous() && drains() && dims && !dims->empty() &&
1409 !(*dims)[0].getValue().empty();
1410}
1411
1412LogicalResult ObjectFifoDmaEndpointOp::getStreamWindow(StreamWindow &window) {
1413 auto dims = getDimensions();
1414 if (!dims || dims->empty())
1415 return emitOpError("walks no stream: it has no dimensions");
1416 ArrayRef<BDPadLayoutAttr> pads;
1417 if (auto padding = getPadDimensions(); padding && !padding->empty())
1418 pads = (*padding)[0].getValue();
1419 return inferStreamWindow((*dims)[0].getValue(), pads,
1420 getPoolOp().getObjectSize(),
1421 [&] { return emitOpError(); }, window);
1422}
1423
1424int64_t ObjectFifoDmaEndpointOp::getRepeat() {
1425 ObjectFifoPoolOp pool = getPoolOp();
1426 // The filling end covers the batch in one acquire instead.
1427 return pool && drains() ? pool.getRepeatCount().value_or(1) : 1;
1428}
1429
1430bool ObjectFifoDmaEndpointOp::repeatsInHardware() {
1431 return getRepeat() > 1 &&
1432 (getReleaseStrategy() == ObjectFifoRelease::PushQueue ||
1433 (getNumDescriptors() == 1 && !getIterCount()));
1434}
1435
1436int64_t ObjectFifoDmaEndpointOp::getDispatchPasses() {
1437 ObjectFifoPoolOp pool = getPoolOp();
1438 std::optional<ArrayAttr> turns = getDispatch();
1439 if (!pool || !turns || turns->empty())
1440 return 1;
1441 int64_t depth = std::max<int64_t>(pool.getDepth(), 1);
1442 return std::lcm(depth, static_cast<int64_t>(turns->size())) / depth;
1443}
1444
1445SmallVector<ObjectFifoDmaEndpointOp>
1446xilinx::AIE::turnEndpoints(ObjectFifoDmaEndpointOp endpoint) {
1447 SmallVector<ObjectFifoDmaEndpointOp> ends;
1448 if (std::optional<ArrayAttr> turns = endpoint.getTurns())
1449 for (auto name : turns->getAsRange<FlatSymbolRefAttr>())
1450 if (auto end =
1451 SymbolTable::lookupNearestSymbolFrom<ObjectFifoDmaEndpointOp>(
1452 endpoint, name);
1453 end && !llvm::is_contained(ends, end))
1454 ends.push_back(end);
1455 return ends;
1456}
1457
1458int64_t xilinx::AIE::turnPasses(ArrayRef<std::pair<int64_t, int64_t>> ends) {
1459 int64_t passes = 1;
1460 for (auto [appearances, count] : ends)
1461 if (count > 0)
1462 passes = std::lcm(passes, count / std::gcd(count, appearances));
1463 return passes;
1464}
1465
1466int64_t ObjectFifoDmaEndpointOp::getNumBDs() {
1467 SmallVector<ObjectFifoDmaEndpointOp> ends = turnEndpoints(*this);
1468 if (ends.empty())
1469 return getNumDescriptors() * (repeatsInHardware() ? 1 : getRepeat()) *
1470 getDispatchPasses();
1471 if (ends.front() != *this)
1472 return 0;
1473 ArrayRef<Attribute> turns = getTurnsAttr().getValue();
1474 SmallVector<std::pair<int64_t, int64_t>> counts;
1475 for (ObjectFifoDmaEndpointOp end : ends)
1476 counts.push_back(
1477 {llvm::count(turns, FlatSymbolRefAttr::get(end.getSymNameAttr())),
1478 end.getPoolOp().getContiguous() ? 0 : end.getNumDescriptors()});
1479 return turnPasses(counts) * static_cast<int64_t>(turns.size());
1480}
1481
1482DMAChannelDir ObjectFifoDmaEndpointOp::getRouteDirection() {
1483 return drains() ? DMAChannelDir::MM2S : DMAChannelDir::S2MM;
1484}
1485
1486WireBundle ObjectFifoDmaEndpointOp::getRouteBundle() { return WireBundle::DMA; }
1487
1488std::optional<int> ObjectFifoDmaEndpointOp::getRouteChannel() {
1489 return getChannelIndex();
1490}
1491
1492void ObjectFifoDmaEndpointOp::setRouteChannel(int channel) {
1493 setChannelIndex(channel);
1494}
1495
1496LogicalResult ObjectFifoDmaEndpointOp::verify() {
1497 if (!getTileLike())
1498 return emitOpError("tile operand is not an aie.tile or aie.logical_tile");
1499 ObjectFifoPoolOp pool = getPoolOp();
1500 if (!pool) {
1501 return emitOpError("references undefined pool '") << getPool() << "'";
1502 }
1503
1504 if (failed(verifyEndpoint(*this, pool, getSegments()))) {
1505 return failure();
1506 }
1507 if (failed(verifyAssignedPacket(*this, getPacketAttr()))) {
1508 return failure();
1509 }
1510
1511 if (getReleaseStrategy() == ObjectFifoRelease::PushQueue) {
1512 if (!drains() || !getTileLike().isCoreTile() ||
1514 return emitOpError("push_queue requires a sending DMA on a core tile "
1515 "with core-issued task support");
1516 if (auto values = pool.getInitValues(); values && !values->empty())
1517 return emitOpError("push_queue does not support initialized objects");
1518 if (getRepeat() - 1 > getTargetModel(*this).getMaxRepeatCount())
1519 return emitOpError(
1520 "push_queue repeat_count exceeds the hardware task limit");
1521 if (getOutOfOrder() && getRepeat() > 1)
1522 return emitOpError(
1523 "push_queue cannot repeat out-of-order packets: "
1524 "each repetition may need a different destination BD ID");
1525 }
1526
1527 if (std::optional<ArrayAttr> turns = getDispatch()) {
1528 if (!drains())
1529 return emitOpError("only a draining endpoint can dispatch");
1530 if (turns->empty())
1531 return emitOpError("dispatch names no destination");
1532 if (getPacketAttr())
1533 return emitOpError("a dispatching endpoint carries a header per turn in "
1534 "`dispatchPackets`, not one `packet`");
1535 if (pool.getRepeatCount().value_or(1) > 1)
1536 return emitOpError("cannot dispatch a pool that repeats its objects");
1537 if (std::optional<int32_t> iterCount = getIterCount();
1538 iterCount && *iterCount % std::max<int64_t>(getDispatchPasses(), 1))
1539 return emitOpError("iterCount ")
1540 << *iterCount << " is not a whole number of dispatch rounds ("
1541 << getDispatchPasses() << " passes over the pool)";
1542 }
1543 if (std::optional<ArrayAttr> headers = getDispatchPackets()) {
1544 std::optional<ArrayAttr> turns = getDispatch();
1545 if (!turns || turns->size() != headers->size())
1546 return emitOpError("dispatchPackets needs one header per dispatch turn");
1547 for (auto header : headers->getAsRange<PacketInfoAttr>())
1548 if (failed(verifyAssignedPacket(*this, header, "dispatchPackets")))
1549 return failure();
1550 }
1551 if (std::optional<ArrayAttr> turns = getTurns()) {
1552 if (!llvm::is_contained(*turns, FlatSymbolRefAttr::get(getSymNameAttr())))
1553 return emitOpError("takes no turn of its own in `turns`");
1554 for (auto name : turns->getAsRange<FlatSymbolRefAttr>())
1555 if (!SymbolTable::lookupNearestSymbolFrom<ObjectFifoDmaEndpointOp>(*this,
1556 name))
1557 return emitOpError("turns names ")
1558 << name << ", which is no objectfifo.dma_endpoint";
1559 if (getDispatch() || getPacketAttr() || getIterCount() || getRepeat() > 1)
1560 return emitOpError("taking turns on a channel, it cannot also dispatch, "
1561 "carry a header, stop after iterCount or repeat");
1562 for (ObjectFifoDmaEndpointOp end : turnEndpoints(*this))
1563 if (end.getTile() != getTile() || end.getRole() != getRole() ||
1564 end.getTurnsAttr() != getTurnsAttr() ||
1565 end.getChannelIndexAttr() != getChannelIndexAttr())
1566 return emitOpError("takes turns with ")
1567 << end.getSymNameAttr()
1568 << ", which is not on this tile and channel with the same turns";
1569 if (pool.getContiguous() && !walksStream() &&
1570 pool.getDepth() % getNumDescriptors())
1571 return emitOpError("walks a contiguous pool of ")
1572 << pool.getDepth() << " objects in " << getNumDescriptors()
1573 << " turns a pass, which do not divide them";
1574 }
1575
1576 std::optional<ArrayAttr> segmentNames = getSegments();
1577 size_t selectedCount = segmentNames ? segmentNames->size() : 1;
1578 auto dimensions = getDimensions();
1579 if (dimensions && dimensions->size() != selectedCount) {
1580 return emitOpError("dimensions has ")
1581 << dimensions->size() << " entries for " << selectedCount
1582 << " selected segments";
1583 }
1584 auto padding = getPadDimensions();
1585 if (padding && padding->size() != selectedCount) {
1586 return emitOpError("padDimensions has ")
1587 << padding->size() << " entries for " << selectedCount
1588 << " selected segments";
1589 }
1590 if (padding && !drains()) {
1591 return emitOpError("padDimensions is only valid on a draining endpoint");
1592 }
1593 if (getPadValue() != 0 &&
1594 (!padding || llvm::none_of(*padding, [](BDPadLayoutArrayAttr entry) {
1595 return !entry.empty();
1596 }))) {
1597 return emitOpError("nonzero padValue requires a non-empty padDimensions "
1598 "entry");
1599 }
1600
1601 // A walk over the stream reads across the pool's objects, outputs apart.
1602 StreamWindow window;
1603 if (walksStream())
1604 return getStreamWindow(window);
1605
1606 std::vector<ObjectFifoSegmentOp> selected = getSelectedSegments();
1607 for (size_t position = 0; position < selectedCount; ++position) {
1608 BDDimLayoutArrayAttr dims =
1609 dimensions ? (*dimensions)[position] : BDDimLayoutArrayAttr();
1610 BDPadLayoutArrayAttr pads =
1611 padding ? (*padding)[position] : BDPadLayoutArrayAttr();
1612 if (pads && !pads.empty() && (!dims || dims.empty())) {
1613 return emitOpError("padDimensions entry ")
1614 << position << " requires dimensions for the same segment";
1615 }
1616 if (dims && pads && !pads.empty() && dims.size() != pads.size()) {
1617 return emitOpError("dimensions and padDimensions entry ")
1618 << position << " have different ranks";
1619 }
1620 if (dims && !dims.empty() &&
1621 getDimsMaxIdx(dims) >= selected[position].getSize()) {
1622 return emitOpError("dimensions entry ")
1623 << position << " exceeds selected segment '"
1624 << selected[position].getSymName() << "' of size "
1625 << selected[position].getSize();
1626 }
1627 }
1628 return success();
1629}
1630
1631TileLike RouteEndpointOp::getTileLike() {
1632 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1633}
1634
1635DMAChannelDir RouteEndpointOp::getRouteDirection() {
1636 // A flow runs from its source, so an end named there sends and every other
1637 // end receives.
1638 auto device = getOperation()->getParentOfType<DeviceOp>();
1639 StringRef name = getSymName();
1640 bool named = false;
1641 for (auto flow : device.getOps<RouteOp>()) {
1642 if (flow.namesAsSource(name)) {
1643 return DMAChannelDir::MM2S;
1644 }
1645 named |= flow.namesAsDestination(name);
1646 }
1647 assert(named && "endpoint is named by no flow, so it has no direction to "
1648 "read; --aie-objectfifo-verify rejects this");
1649 (void)named;
1650 return DMAChannelDir::S2MM;
1651}
1652
1653WireBundle RouteEndpointOp::getRouteBundle() { return getBundle(); }
1654
1655std::optional<int> RouteEndpointOp::getRouteChannel() {
1656 return getChannelIndex();
1657}
1658
1659void RouteEndpointOp::setRouteChannel(int channel) { setChannelIndex(channel); }
1660
1661// consumed_by sits on a shim input (MM2S) and each of its proofs names a shim
1662// output (S2MM), the `outputs` kind of op that `namesShimOutput` recognises. A
1663// route end's direction is its flows', which allocation removes, so there only
1664// the shim is checked.
1665static LogicalResult
1666verifyConsumedBy(Operation *op, ArrayAttr proofs, bool shimInput,
1667 StringRef outputs,
1668 function_ref<bool(FlatSymbolRefAttr)> namesShimOutput) {
1669 if (!shimInput)
1670 return op->emitOpError("consumed_by belongs on a shim input (MM2S)");
1671 for (auto proof : proofs.getAsRange<ConsumedByAttr>())
1672 if (!namesShimOutput(proof.getOutput()))
1673 return op->emitOpError("consumed_by output ")
1674 << proof.getOutput() << " names no shim output (S2MM " << outputs
1675 << ")";
1676 return success();
1677}
1678
1679LogicalResult RouteEndpointOp::verify() {
1680 TileLike tile = getTileLike();
1681 if (!tile) {
1682 return emitOpError("tile operand is not an aie.tile or aie.logical_tile");
1683 }
1684 if (failed(verifyAssignedPacket(*this, getPacketAttr()))) {
1685 return failure();
1686 }
1687 // getRouteDirection() reads this end's direction off the flows naming it, so
1688 // they must all name it on the same side. Packet flows can share the channel;
1689 // a circuit owns it.
1690 StringRef name = getSymName();
1691 SmallVector<RouteOp> sources, dests;
1692 for (auto flow : (*this)->getParentOfType<DeviceOp>().getOps<RouteOp>()) {
1693 if (flow.namesAsSource(name))
1694 sources.push_back(flow);
1695 if (flow.namesAsDestination(name))
1696 dests.push_back(flow);
1697 }
1698 if (!sources.empty() && !dests.empty()) {
1699 return emitOpError("is named as both a source and a destination, so its "
1700 "direction is ambiguous");
1701 }
1702 ArrayRef<RouteOp> sharers = sources.empty() ? dests : sources;
1703 if (sharers.size() > 1) {
1704 if (llvm::any_of(sharers, [](RouteOp flow) { return !flow.getPacket(); }))
1705 return emitOpError("drives one channel, which a circuit flow owns, but "
1706 "it is named ")
1707 << sharers.size() << " times";
1708 llvm::SmallDenseSet<int> ids;
1709 for (RouteOp flow : sources) {
1710 std::optional<uint16_t> id = flow.getPacketAttr().getPktId();
1711 if (!id)
1712 return emitOpError("sends several packet flows, so each must pin its "
1713 "pkt_id for the BDs to state it");
1714 if (!ids.insert(*id).second)
1715 return emitOpError("sends several packet flows, two of which pin the "
1716 "same pkt_id ")
1717 << static_cast<int>(*id) << "; each needs its own";
1718 }
1719 // The port keeps or drops every header it receives.
1720 if (llvm::any_of(dests, [&](RouteOp flow) {
1721 return flow.getKeepPktHeader() != dests[0].getKeepPktHeader();
1722 }))
1723 return emitOpError("receives several packet flows, so they must agree "
1724 "on keep_pkt_header");
1725 }
1726 if (ArrayAttr proofs = getConsumedByAttr()) {
1727 auto device = (*this)->getParentOfType<DeviceOp>();
1728 if (failed(verifyConsumedBy(
1729 *this, proofs, tile.isShimTile(),
1730 "aie.route_endpoint or aie.shim_dma_allocation",
1731 [&](FlatSymbolRefAttr symbol) {
1732 Operation *output = device.lookupSymbol(symbol.getAttr());
1733 if (auto alloc = dyn_cast_or_null<ShimDMAAllocationOp>(output))
1734 return alloc.getChannelDir() == DMAChannelDir::S2MM;
1735 auto end = dyn_cast_or_null<RouteEndpointOp>(output);
1736 return end && end.getTileLike().isShimTile();
1737 })))
1738 return failure();
1739 }
1740 switch (getBundle()) {
1741 case WireBundle::DMA:
1742 // The runtime drives a shim's DMA, and a DMA program or the runtime
1743 // sequence any other tile's; either names this op for the channel.
1744 return success();
1745 case WireBundle::PLIO:
1746 if (!tile.isShimTile()) {
1747 return emitOpError("a PLIO end is on a shim");
1748 }
1749 return success();
1750 case WireBundle::Core:
1751 return success();
1752 default:
1753 return emitOpError("bundle must be DMA, PLIO or Core");
1754 }
1755}
1756
1757//===----------------------------------------------------------------------===//
1758// RouteOp
1759//===----------------------------------------------------------------------===//
1760
1761// A route's sources print bare when there is one, bracketed when there are
1762// several; both forms parse.
1763static ParseResult parseRouteSources(OpAsmParser &parser, ArrayAttr &sources) {
1764 SmallVector<Attribute> names;
1765 auto parseOne = [&]() -> ParseResult {
1766 FlatSymbolRefAttr name;
1767 if (parser.parseAttribute(name))
1768 return failure();
1769 names.push_back(name);
1770 return success();
1771 };
1772 if (succeeded(parser.parseOptionalLSquare())) {
1773 if (failed(parser.parseOptionalRSquare()) &&
1774 (parser.parseCommaSeparatedList(parseOne) || parser.parseRSquare()))
1775 return failure();
1776 } else if (parseOne()) {
1777 return failure();
1778 }
1779 sources = parser.getBuilder().getArrayAttr(names);
1780 return success();
1781}
1782
1783static void printRouteSources(OpAsmPrinter &p, Operation *, ArrayAttr sources) {
1784 if (sources.size() == 1) {
1785 p.printAttribute(sources[0]);
1786 return;
1787 }
1788 p << '[';
1789 llvm::interleaveComma(sources, p,
1790 [&](Attribute name) { p.printAttribute(name); });
1791 p << ']';
1792}
1793
1794LogicalResult RouteOp::verify() {
1795 if (getSources().empty()) {
1796 return emitOpError("expects at least one source");
1797 }
1798 if (getDestinations().empty()) {
1799 return emitOpError("expects at least one destination");
1800 }
1801
1802 if (getKeepPktHeader() && !getPacket()) {
1803 return emitOpError("keep_pkt_header is only meaningful on a packet flow");
1804 }
1805
1806 auto device = (*this)->getParentOfType<DeviceOp>();
1807 auto lookup = [&](StringRef name) {
1808 return dyn_cast_or_null<RouteEndpoint>(SymbolTable::lookupNearestSymbolFrom(
1809 device, StringAttr::get(getContext(), name)));
1810 };
1811
1812 llvm::SmallDenseSet<StringRef> seen;
1813 for (StringRef source : getSourceNames()) {
1814 if (!lookup(source)) {
1815 return emitOpError("source '") << source << "' is not an endpoint";
1816 }
1817 if (!seen.insert(source).second) {
1818 return emitOpError("names '@") << source << "' as a source twice";
1819 }
1820 }
1821 for (StringRef destination : getDestinationNames()) {
1822 if (!lookup(destination)) {
1823 return emitOpError("destination '")
1824 << destination << "' is not an endpoint";
1825 }
1826 if (!seen.insert(destination).second) {
1827 return emitOpError("names '@")
1828 << destination
1829 << "' more than once; an end is a source or a "
1830 "destination, and only one of each";
1831 }
1832 }
1833
1834 // A circuit joins one slave port to its master ports, so only packets can
1835 // share a destination channel between sources.
1836 if (isFanIn() && !getPacket()) {
1837 return emitOpError("has several sources, so it needs a `packet` header; "
1838 "a circuit cannot merge streams");
1839 }
1840 return success();
1841}
1842
1843BDDimLayoutArrayAttr
1844ObjectFifoCreateOp::getDimensionsFromStream(Value consumerTile) {
1845 int dimsIndex = 0;
1846 for (auto cons : getConsumerTiles()) {
1847 if (cons == consumerTile)
1848 break;
1849 dimsIndex++;
1850 }
1851 return getDimensionsFromStreamPerConsumer()[dimsIndex];
1852}
1853
1855 OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
1856 BDDimLayoutArrayAttr &dimensions) {
1857 std::vector<BDDimLayoutAttr> emptyDims = {};
1858 if (parser.parseOperand(operand))
1859 return failure();
1860 if (succeeded(parser.parseOptionalKeyword("dimensionsToStream"))) {
1861 if (parser.parseCustomAttributeWithFallback<BDDimLayoutArrayAttr>(
1862 dimensions)) {
1863 return failure();
1864 }
1865 } else {
1866 dimensions =
1867 BDDimLayoutArrayAttr::get(parser.getContext(), ArrayRef(emptyDims));
1868 }
1869 return success();
1870}
1871
1872void xilinx::AIE::printObjectFifoProducerTile(OpAsmPrinter &printer,
1873 Operation *op, Value operand,
1874 BDDimLayoutArrayAttr dimensions) {
1875 printer << operand;
1876 if (!dimensions.empty()) {
1877 printer << " dimensionsToStream ";
1878 printer.printStrippedAttrOrType(dimensions);
1879 }
1880}
1881
1882ParseResult xilinx::AIE::parseDMAStartChannel(OpAsmParser &parser,
1883 Attribute &channel) {
1884 StringAttr name;
1885 if (succeeded(parser.parseOptionalSymbolName(name))) {
1886 channel = FlatSymbolRefAttr::get(name);
1887 return success();
1888 }
1889 int32_t index;
1890 if (parser.parseInteger(index))
1891 return failure();
1892 channel = parser.getBuilder().getI32IntegerAttr(index);
1893 return success();
1894}
1895
1896LogicalResult xilinx::AIE::verifyDMAChannelsResolved(DeviceOp device) {
1897 bool resolved = true;
1898 device.walkOutsideRuntimeSequences<DMAStartOp>([&](DMAStartOp start) {
1899 if (FlatSymbolRefAttr endpoint = start.getEndpoint()) {
1900 start.emitOpError() << "names route endpoint " << endpoint
1901 << " in place of a channel index; run "
1902 "--aie-objectfifo-allocate to assign one";
1903 resolved = false;
1904 }
1905 });
1906 return success(resolved);
1907}
1908
1909void xilinx::AIE::printDMAStartChannel(OpAsmPrinter &printer, Operation *op,
1910 Attribute channel) {
1911 if (auto index = dyn_cast<IntegerAttr>(channel))
1912 printer << index.getInt();
1913 else
1914 printer.printAttributeWithoutType(channel);
1915}
1916
1917ParseResult
1919 ObjectFifoPortAttr &port,
1920 SmallVectorImpl<Type> &objects) {
1921 if (parser.parseLParen())
1922 return failure();
1923
1924 StringRef portName;
1925 SMLoc portLoc = parser.getCurrentLocation();
1926 if (succeeded(parser.parseOptionalKeyword(&portName))) {
1927 std::optional<ObjectFifoPort> parsed = symbolizeObjectFifoPort(portName);
1928 if (!parsed)
1929 return parser.emitError(portLoc, "invalid objectFifo port: ") << portName;
1930 port = ObjectFifoPortAttr::get(parser.getContext(), *parsed);
1931 if (parser.parseComma())
1932 return failure();
1933 }
1934
1935 int64_t count;
1936 SMLoc countLoc = parser.getCurrentLocation();
1937 if (parser.parseInteger(count) || parser.parseRParen() ||
1938 parser.parseColon() || parser.parseTypeList(objects))
1939 return failure();
1940
1941 if (count != static_cast<int64_t>(objects.size()))
1942 return parser.emitError(countLoc, "acquires ")
1943 << count << " objects but names " << objects.size() << " of them";
1944 return success();
1945}
1946
1947void xilinx::AIE::printObjectFifoAcquireObjects(OpAsmPrinter &printer,
1948 Operation *op,
1949 ObjectFifoPortAttr port,
1950 TypeRange objects) {
1951 printer << "(";
1952 if (port)
1953 printer << stringifyObjectFifoPort(port.getValue()) << ", ";
1954 printer << objects.size() << ") : ";
1955 llvm::interleaveComma(objects, printer);
1956}
1957
1958ParseResult xilinx::AIE::parseObjectFifoReleaseCount(OpAsmParser &parser,
1959 ObjectFifoPortAttr &port,
1960 IntegerAttr &size) {
1961 if (parser.parseLParen())
1962 return failure();
1963
1964 StringRef portName;
1965 SMLoc portLoc = parser.getCurrentLocation();
1966 if (succeeded(parser.parseOptionalKeyword(&portName))) {
1967 std::optional<ObjectFifoPort> parsed = symbolizeObjectFifoPort(portName);
1968 if (!parsed)
1969 return parser.emitError(portLoc, "invalid objectFifo port: ") << portName;
1970 port = ObjectFifoPortAttr::get(parser.getContext(), *parsed);
1971 if (parser.parseComma())
1972 return failure();
1973 }
1974
1975 int64_t count;
1976 if (parser.parseInteger(count) || parser.parseRParen())
1977 return failure();
1978 size = parser.getBuilder().getI32IntegerAttr(count);
1979 return success();
1980}
1981
1982void xilinx::AIE::printObjectFifoReleaseCount(OpAsmPrinter &printer,
1983 Operation *op,
1984 ObjectFifoPortAttr port,
1985 IntegerAttr size) {
1986 printer << "(";
1987 if (port)
1988 printer << stringifyObjectFifoPort(port.getValue()) << ", ";
1989 printer << size.getInt() << ")";
1990}
1991
1993 OpAsmParser &parser, SmallVectorImpl<OpAsmParser::UnresolvedOperand> &tiles,
1994 BDDimLayoutArrayArrayAttr &dimensions) {
1995 // parseCommaSeparatedList doesn't handle the missing case for "none",
1996 // so we handle it custom here.
1997 std::vector<BDDimLayoutArrayAttr> tileDims = {};
1998
1999 auto parseOneOperand = [&]() -> ParseResult {
2000 if (parser.parseOperand(tiles.emplace_back(), true)) {
2001 return failure();
2002 }
2003 // By default, create empty dimensions array for each consumer; this way,
2004 // we can be certain to have as many entries in the dimensions array as
2005 // there are customer
2006 BDDimLayoutArrayAttr dimAttr =
2007 BDDimLayoutArrayAttr::get(parser.getContext(), {});
2008
2009 if (succeeded(parser.parseOptionalKeyword("dimensionsFromStream"))) {
2010 // If specified, parse actual data layout transform dimensions
2011 if (parser.parseCustomAttributeWithFallback<BDDimLayoutArrayAttr>(
2012 dimAttr)) {
2013 return failure();
2014 }
2015 }
2016 tileDims.emplace_back(dimAttr);
2017 return success();
2018 };
2019
2020 if (parser.parseCommaSeparatedList(AsmParser::Delimiter::None,
2021 parseOneOperand, " in operand list"))
2022 return failure();
2023
2024 dimensions = BDDimLayoutArrayArrayAttr::get(parser.getContext(), tileDims);
2025 return success();
2026}
2027
2029 OpAsmPrinter &printer, Operation *op, OperandRange tiles,
2030 BDDimLayoutArrayArrayAttr dimsPerTileAttr) {
2031 size_t tileIdx = 0;
2032 for (auto tile : tiles) {
2033 printer << tile;
2034 if (dimsPerTileAttr && tileIdx < dimsPerTileAttr.size() &&
2035 dimsPerTileAttr[tileIdx] && !dimsPerTileAttr[tileIdx].empty()) {
2036 printer << " dimensionsFromStream ";
2037 printer.printStrippedAttrOrType(dimsPerTileAttr[tileIdx]);
2038 }
2039 if (tileIdx < tiles.size() - 1) {
2040 printer << ", ";
2041 }
2042 tileIdx++;
2043 }
2044}
2045
2046static void printObjectFifoConsumerElemType(OpAsmPrinter &p,
2047 ObjectFifoCreateOp op,
2048 TypeAttr consumerElemType) {
2049 if (consumerElemType)
2050 p << " -> " << consumerElemType;
2051}
2052
2053ParseResult xilinx::AIE::parseFlowVias(
2054 OpAsmParser &parser, SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vias,
2055 DenseI32ArrayAttr &ingressBundles, DenseI32ArrayAttr &ingressChannels,
2056 DenseI32ArrayAttr &egressBundles, DenseI32ArrayAttr &egressChannels) {
2057 SmallVector<int32_t> inBundles, inChannels, egBundles, egChannels;
2058 auto parseBundle = [&](SmallVectorImpl<int32_t> &out) -> ParseResult {
2059 StringRef kw;
2060 if (parser.parseKeyword(&kw)) {
2061 return failure();
2062 }
2063 auto bundle = symbolizeWireBundle(kw);
2064 if (!bundle) {
2065 return parser.emitError(parser.getCurrentLocation(),
2066 "invalid wire bundle '" + kw + "'");
2067 }
2068 out.push_back(static_cast<int32_t>(*bundle));
2069 return success();
2070 };
2071 // via ( %tile : <ingress bundle> : <ch> -> <egress bundle> : <ch>, ... )
2072 if (succeeded(parser.parseOptionalKeyword("via"))) {
2073 auto parseOne = [&]() -> ParseResult {
2074 int32_t inChan, egChan;
2075 if (parser.parseOperand(vias.emplace_back()) || parser.parseColon() ||
2076 parseBundle(inBundles) || parser.parseColon() ||
2077 parser.parseInteger(inChan) || parser.parseArrow() ||
2078 parseBundle(egBundles) || parser.parseColon() ||
2079 parser.parseInteger(egChan)) {
2080 return failure();
2081 }
2082 inChannels.push_back(inChan);
2083 egChannels.push_back(egChan);
2084 return success();
2085 };
2086 if (parser.parseCommaSeparatedList(AsmParser::Delimiter::Paren, parseOne)) {
2087 return failure();
2088 }
2089 }
2090 if (!vias.empty()) {
2091 MLIRContext *ctx = parser.getContext();
2092 ingressBundles = DenseI32ArrayAttr::get(ctx, inBundles);
2093 ingressChannels = DenseI32ArrayAttr::get(ctx, inChannels);
2094 egressBundles = DenseI32ArrayAttr::get(ctx, egBundles);
2095 egressChannels = DenseI32ArrayAttr::get(ctx, egChannels);
2096 }
2097 return success();
2098}
2099
2100void xilinx::AIE::printFlowVias(OpAsmPrinter &printer, Operation *op,
2101 OperandRange vias,
2102 DenseI32ArrayAttr ingressBundles,
2103 DenseI32ArrayAttr ingressChannels,
2104 DenseI32ArrayAttr egressBundles,
2105 DenseI32ArrayAttr egressChannels) {
2106 if (vias.empty()) {
2107 return;
2108 }
2109 printer << "via (";
2110 for (size_t i = 0; i < vias.size(); i++) {
2111 if (i) {
2112 printer << ", ";
2113 }
2114 printer << vias[i] << " : "
2115 << stringifyWireBundle(static_cast<WireBundle>(ingressBundles[i]))
2116 << " : " << ingressChannels[i] << " -> "
2117 << stringifyWireBundle(static_cast<WireBundle>(egressBundles[i]))
2118 << " : " << egressChannels[i];
2119 }
2120 printer << ")";
2121}
2122
2123static ParseResult parseObjectFifoConsumerElemType(OpAsmParser &parser,
2124 TypeAttr &consumerElemType) {
2125 if (failed(parser.parseOptionalArrow()))
2126 return success(); // no consumer type
2127 Type type;
2128 if (parser.parseType(type))
2129 return failure();
2130 consumerElemType = TypeAttr::get(type);
2131 return success();
2132}
2133
2134static void printObjectFifoInitValues(OpAsmPrinter &p, ObjectFifoCreateOp op,
2135 Attribute numElem, TypeAttr type,
2136 Attribute initValues) {
2137 if (op.getInitValues()) {
2138 p << "= [";
2139 // `numElem` may be an IntegerAttr (scalar depth) or an ArrayAttr of
2140 // per-endpoint depths; initValues populates the producer side, which
2141 // is the first entry of the ArrayAttr.
2142 int depth;
2143 if (isa<ArrayAttr>(numElem)) {
2144 depth =
2145 llvm::cast<mlir::IntegerAttr>(llvm::cast<mlir::ArrayAttr>(numElem)[0])
2146 .getInt();
2147 } else {
2148 depth = llvm::cast<mlir::IntegerAttr>(numElem).getInt();
2149 }
2150 for (int i = 0; i < depth; i++) {
2151 p.printStrippedAttrOrType(llvm::cast<mlir::ArrayAttr>(initValues)[i]);
2152 if (i < depth - 1) {
2153 p << ", ";
2154 }
2155 }
2156 p << "]";
2157 }
2158}
2159
2160static ParseResult parseObjectFifoInitValues(OpAsmParser &parser,
2161 Attribute numElem, TypeAttr type,
2162 Attribute &initValues) {
2163 int depth;
2164 if (isa<ArrayAttr>(numElem)) {
2165 depth =
2166 llvm::cast<mlir::IntegerAttr>(llvm::cast<mlir::ArrayAttr>(numElem)[0])
2167 .getInt();
2168 } else {
2169 depth = llvm::cast<mlir::IntegerAttr>(numElem).getInt();
2170 }
2171 auto objfifoType = llvm::cast<AIEObjectFifoType>(type.getValue());
2172 auto memrefType = llvm::cast<MemRefType>(objfifoType.getElementType());
2173
2174 if (!memrefType.hasStaticShape())
2175 return parser.emitError(parser.getNameLoc())
2176 << "type should be static shaped memref, but got " << memrefType;
2177
2178 if (parser.parseOptionalEqual())
2179 return success();
2180
2181 Type tensorType = mlir::memref::getTensorTypeFromMemRefType(memrefType);
2182 if (parser.parseAttribute(initValues, tensorType))
2183 return failure();
2184 for (int i = 0; i < depth; i++) {
2185 auto initialValues = llvm::dyn_cast<mlir::ArrayAttr>(initValues);
2186 if ((int)initialValues.size() != depth)
2187 return parser.emitError(parser.getNameLoc())
2188 << "initial values should initialize all objects";
2189 if (!llvm::isa<ElementsAttr>(initialValues[i]))
2190 return parser.emitError(parser.getNameLoc())
2191 << "initial value should be an elements attribute";
2192 }
2193
2194 return success();
2195}
2196
2197//===----------------------------------------------------------------------===//
2198// ObjectFifoCreateOp DMA decision
2199//===----------------------------------------------------------------------===//
2200
2201std::optional<ObjectFifoLinkOp> ObjectFifoCreateOp::getLink() {
2202 auto self = FlatSymbolRefAttr::get(getSymNameAttr());
2203 for (ObjectFifoLinkOp link :
2204 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>())
2205 if (llvm::is_contained(link.getFifoIns(), self) ||
2206 llvm::is_contained(link.getFifoOuts(), self))
2207 return link;
2208 return std::nullopt;
2209}
2210
2211std::optional<ObjectFifoAllocateOp> ObjectFifoCreateOp::getAllocate() {
2212 for (ObjectFifoAllocateOp alloc :
2213 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoAllocateOp>())
2214 if (alloc.getObjFifoName() == name().getValue())
2215 return alloc;
2216 return std::nullopt;
2217}
2218
2219bool ObjectFifoCreateOp::delegateReaches(const AIETargetModel &target,
2220 TileID delegate, TileID producer,
2221 TileID consumer) {
2222 using SharedMemory = AIETargetModel::SharedMemory;
2223 return llvm::all_of(std::array{producer, consumer}, [&](TileID end) {
2224 SharedMemory s = target.getSharedMemory(delegate, end);
2225 return s == SharedMemory::First || s == SharedMemory::Either;
2226 });
2227}
2228
2229bool ObjectFifoCreateOp::allocatedHome(const AIETargetModel &target,
2230 TileID producer, TileID consumer,
2231 TileID delegate,
2232 std::optional<TileID> linkTile) {
2233 TileID home = linkTile.value_or(delegate);
2234 return delegateReaches(target, delegate, producer, consumer) &&
2235 delegateReaches(target, home, producer, consumer);
2236}
2237
2238bool ObjectFifoCreateOp::allocateFallsBackToDMA() {
2239 auto self = FlatSymbolRefAttr::get(getSymNameAttr());
2240 bool linked = false;
2241 for (ObjectFifoLinkOp link :
2242 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>()) {
2243 if (!llvm::is_contained(link.getFifoIns(), self) &&
2244 !llvm::is_contained(link.getFifoOuts(), self))
2245 continue;
2246 if (link.getOptionalSharedTile() && link.getPoolOwner() == *this)
2247 return false;
2248 linked = true;
2249 }
2250 return linked;
2251}
2252
2253LinkPoolMisfit ObjectFifoCreateOp::linkPoolMisfit() {
2254 ObjectFifoLinkOp producerLink = getProducerLink();
2255 ObjectFifoLinkOp consumerLink =
2256 getConsumerTiles().empty() ? ObjectFifoLinkOp() : getConsumerLink(0);
2257 if (producerLink && consumerLink)
2259 if (consumerLink && consumerLink.isMerge())
2261 if (producerLink && producerLink.isDispatch())
2263 ObjectFifoLinkOp link = producerLink ? producerLink : consumerLink;
2264 if (!link)
2265 return LinkPoolMisfit::None;
2266 ObjectFifoCreateOp owner = link.getPoolOwner();
2267 if (owner == *this)
2268 return LinkPoolMisfit::None;
2269 if (owner.getElemType() != getElemType())
2271 return getInitValues() ? LinkPoolMisfit::InitialValues : LinkPoolMisfit::None;
2272}
2273
2274std::optional<StringRef> ObjectFifoCreateOp::dmaReason() {
2275 if (forcesDMA())
2276 return "it asks for a dma transport";
2277 if (getRepeatCount())
2278 return "it repeats objects (`repeat_count`)";
2279 if (usesStream())
2280 return "an end is a Core stream port";
2281 if (getConsumerElemType())
2282 return "its consumer takes a different element type";
2283 if (getConsumerTiles().size() > 1)
2284 return "it has more than one consumer";
2285 if (!getDimensionsToStream().empty())
2286 return "its producer reshapes the data (`dimensionsToStream`)";
2287 for (BDDimLayoutArrayAttr dims : getDimensionsFromStreamPerConsumer())
2288 if (!dims.empty())
2289 return "a consumer reshapes the data (`dimensionsFromStream`)";
2290 // A link passes objects between two fifos through a tile's DMAs, unless an
2291 // aie.objectfifo.allocate names a delegate whose memory both ends reach.
2292 if (getLink() && !getAllocate())
2293 return "it is linked through a tile's DMAs";
2294 return std::nullopt;
2295}
2296
2297AIETargetModel::SharedMemory ObjectFifoCreateOp::sharedMemoryOf(
2298 const AIETargetModel &target, TileID producer, TileID consumer,
2299 std::optional<TileID> delegate, std::optional<TileID> linkTile) {
2300 using SharedMemory = AIETargetModel::SharedMemory;
2301 // A delegate both ends reach holds the objects even where the ends share no
2302 // memory of their own; a link's objects need one.
2303 if (delegate &&
2304 allocatedHome(target, producer, consumer, *delegate, linkTile)) {
2305 SharedMemory own = target.getSharedMemory(producer, consumer);
2306 return own == SharedMemory::None ? SharedMemory::Either : own;
2307 }
2308 if (linkTile)
2309 return SharedMemory::None;
2310 return target.getSharedMemory(producer, consumer);
2311}
2312
2313static std::optional<TileID> placedAt(Value tile) {
2314 auto tileLike = dyn_cast_or_null<TileLike>(tile.getDefiningOp());
2315 if (!tileLike)
2316 return std::nullopt;
2317 std::optional<int> col = tileLike.tryGetCol(), row = tileLike.tryGetRow();
2318 if (!col || !row)
2319 return std::nullopt;
2320 return TileID{*col, *row};
2321}
2322
2323std::optional<StringRef>
2324ObjectFifoCreateOp::placedDmaReason(AIETargetModel::SharedMemory &shared) {
2325 if (std::optional<StringRef> reason = dmaReason())
2326 return reason;
2327 std::optional<ObjectFifoAllocateOp> alloc = getAllocate();
2328 std::optional<TileID> producer = placedAt(getProducerTile());
2329 std::optional<TileID> consumer = placedAt(getConsumerTiles()[0]);
2330 std::optional<TileID> delegate =
2331 alloc ? placedAt(alloc->getDelegateTile()) : std::nullopt;
2332 std::optional<ObjectFifoLinkOp> link = getLink();
2333 std::optional<Value> linkPoint =
2334 link ? link->getOptionalSharedTile() : std::nullopt;
2335 std::optional<TileID> linkTile =
2336 linkPoint ? placedAt(*linkPoint) : std::nullopt;
2337 if (!producer || !consumer || (alloc && !delegate) || (link && !linkTile))
2338 return std::nullopt;
2339 shared = sharedMemoryOf(getTargetModel(*this), *producer, *consumer, delegate,
2340 linkTile);
2342 return link ? "it is linked through a tile's DMAs"
2343 : "its ends share no memory module";
2344 return std::nullopt;
2345}
2346
2347std::optional<StringRef> ObjectFifoCreateOp::pushQueueRefusal() {
2348 if (auto values = getInitValues(); values && !values->empty())
2349 return StringRef("push_queue does not support initialized objects");
2350 auto tile = cast<TileLike>(getProducerTile().getDefiningOp());
2351 auto device = (*this)->getParentOfType<DeviceOp>();
2352 if (!tile.isCoreTile() || streamsFromProducer() ||
2353 device.getTargetModel().getDmaTaskQueueDepth() == 0)
2354 return StringRef("push_queue requires a sending DMA on a core tile with "
2355 "core-issued task support");
2356 bool hasRelease = false;
2357 for (Operation *user : getProducerTile().getUsers())
2358 if (auto core = dyn_cast<CoreOp>(user))
2359 core.walk([&](ObjectFifoReleaseOp release) {
2360 hasRelease |= release.getObjectFifo() == *this &&
2361 release.getPort() == ObjectFifoPort::Produce;
2362 });
2363 if (!hasRelease)
2364 return StringRef("push_queue requires producer releases in a local core "
2365 "to submit send tasks");
2366 return std::nullopt;
2367}
2368
2369std::optional<StringRef>
2370ObjectFifoCreateOp::sharedReceiveRefusal(bool shim, bool outOfOrder) {
2371 if (shim)
2372 return StringRef("a shim's receiving channel writes into the runtime's "
2373 "tasks, which no object header picks");
2374 if (!outOfOrder)
2375 return StringRef("a channel its fifos receive in turn holds their order; "
2376 "out_of_order puts that order in each object's header");
2377 return std::nullopt;
2378}
2379
2380bool ObjectFifoCreateOp::sharesSendChannel() {
2381 auto pinned = [](ObjectFifoCreateOp fifo) -> std::optional<int> {
2382 ObjectFifoEndPortAttr port = fifo.getProdPortAttr();
2383 return port && !port.isCore() ? port.channelIndex() : std::nullopt;
2384 };
2385 auto byDMA = [](ObjectFifoCreateOp fifo) {
2387 return fifo.placedDmaReason(shared).has_value();
2388 };
2389 std::optional<int> channel = pinned(*this);
2390 Value tile = getProducerTile();
2391 if (!channel || cast<TileLike>(tile.getDefiningOp()).isShimTile() ||
2392 !byDMA(*this))
2393 return false;
2394 std::optional<TileID> at = placedAt(tile);
2395 for (ObjectFifoCreateOp other :
2396 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoCreateOp>()) {
2397 Value otherTile = other.getProducerTile();
2398 if (other != *this && pinned(other) == channel &&
2399 (otherTile == tile || (at && placedAt(otherTile) == at)) &&
2400 byDMA(other))
2401 return true;
2402 }
2403 return false;
2404}
2405
2406int ObjectFifoCreateOp::dmaDepth(std::optional<unsigned> consumer) {
2407 if (consumer ? streamsToConsumer(*consumer) : streamsFromProducer())
2408 return 0;
2409 if (!consumer && getInitValues())
2410 return size();
2411 if (consumer && isa<ArrayAttr>(getElemNumber()))
2412 return size(*consumer + 1);
2413 if (size() == 0)
2414 return 0;
2415 // Enough objects for the largest acquire the end's core makes, plus one so
2416 // it can hold an object while the next arrives. A core on the producer's
2417 // tile may also consume, through another end.
2418 Value tile = consumer ? getConsumerTiles()[*consumer] : getProducerTile();
2419 ObjectFifoPort port =
2420 consumer ? ObjectFifoPort::Consume : ObjectFifoPort::Produce;
2421 int maxAcquire = 0;
2422 for (Operation *user : tile.getUsers())
2423 if (auto core = dyn_cast<CoreOp>(user))
2424 core.walk([&](ObjectFifoAcquireOp acquire) {
2425 if (acquire.getObjectFifo() == *this && acquire.getPort() == port)
2426 maxAcquire = std::max(maxAcquire, acquire.acqNumber());
2427 });
2428 if (maxAcquire == 0)
2429 return size();
2430 if (maxAcquire == 1 && size() == 1)
2431 return 1;
2432 return maxAcquire + 1;
2433}
2434
2435ObjectFifoLinkOp ObjectFifoCreateOp::getProducerLink() {
2436 auto self = FlatSymbolRefAttr::get(getSymNameAttr());
2437 for (ObjectFifoLinkOp link :
2438 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>())
2439 if (llvm::is_contained(link.getFifoOuts(), self) &&
2440 link.getOptionalSharedTile() == getProducerTile())
2441 return link;
2442 return {};
2443}
2444
2445ObjectFifoLinkOp ObjectFifoCreateOp::getConsumerLink(unsigned consumer) {
2446 auto consumers = getConsumerTiles();
2447 Value tile = consumers[consumer];
2448 size_t earlier = llvm::count(consumers.take_front(consumer), tile);
2449 auto self = FlatSymbolRefAttr::get(getSymNameAttr());
2450 for (ObjectFifoLinkOp link :
2451 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>())
2452 if (llvm::is_contained(link.getFifoIns(), self) &&
2453 link.getOptionalSharedTile() == tile && earlier-- == 0)
2454 return link;
2455 return {};
2456}
2457
2458std::optional<PlannedDmaEnd>
2459ObjectFifoCreateOp::plannedDmaEnd(std::optional<unsigned> consumer) {
2460 return plannedDmaEnd(consumer, placedAt);
2461}
2462
2463std::optional<PlannedDmaEnd>
2464ObjectFifoCreateOp::plannedDmaEnd(std::optional<unsigned> consumer,
2465 TilePositions positions) {
2466 bool drains = !consumer;
2467 Value tile = drains ? getProducerTile() : getConsumerTiles()[*consumer];
2468 auto tileLike = cast<TileLike>(tile.getDefiningOp());
2469 if (tileLike.isShimTile() ||
2470 (drains ? streamsFromProducer() : streamsToConsumer(*consumer)))
2471 return std::nullopt;
2472 auto device = (*this)->getParentOfType<DeviceOp>();
2473 int64_t maxLock = device.getTargetModel().getMaxLockValue();
2474 ObjectFifoEndPortAttr port =
2475 drains ? getProdPortAttr() : getConsumerPort(*consumer);
2476 std::optional<int> channel = port ? port.channelIndex() : std::nullopt;
2477 auto walkable = [&](int64_t depth) {
2478 return walksWholeDepth(tileLike.isMemTile(), depth, maxLock);
2479 };
2480
2481 ObjectFifoLinkOp link =
2482 drains ? getProducerLink() : getConsumerLink(*consumer);
2483 DataLayout layout = DataLayout::closest(*this);
2484 auto objectBytes = [&](Type fifoType) -> int64_t {
2485 MemRefType type = cast<AIEObjectFifoType>(fifoType).getElementType();
2486 return getMemRefSizeInBytes(type, layout);
2487 };
2488 auto ordered = [](ObjectFifoCreateOp fifo, bool drains) {
2489 return !fifo.getOutOfOrder() && (!drains || !usesPushQueue(fifo));
2490 };
2491 if (!link) {
2492 int depth = dmaDepth(consumer);
2493 if (!drains)
2494 return PlannedDmaEnd{depth,
2495 *this,
2496 static_cast<int>(*consumer),
2497 depth,
2498 walkable(depth) && ordered(*this, false),
2499 objectBytes(getConsumerElemTypeOrDefault()),
2500 0,
2501 channel};
2502 int64_t repeat = getRepeatCount().value_or(1);
2503 bool inHardware =
2504 repeat > 1 && (usesPushQueue(*this) || (depth == 1 && !getIterCount()));
2505 return PlannedDmaEnd{depth * (inHardware ? 1 : repeat),
2506 *this,
2507 -1,
2508 depth,
2509 walkable(depth) && ordered(*this, true) &&
2510 !getRepeatCount() &&
2511 getDimensionsToStream().empty(),
2512 objectBytes(getElemType()),
2513 0,
2514 channel};
2515 }
2516
2517 // A merge's participants fill one end, a dispatch's drain one, made by the
2518 // first of them the split reaches.
2519 if (drains ? link.isDispatch() : link.isMerge()) {
2520 std::vector<ObjectFifoCreateOp> sharing =
2521 drains ? link.getOutputObjectFifos() : link.getInputObjectFifos();
2522 for (ObjectFifoCreateOp fifo : device.getOps<ObjectFifoCreateOp>())
2523 if (llvm::is_contained(sharing, fifo)) {
2524 if (fifo != *this)
2525 return std::nullopt;
2526 break;
2527 }
2528 }
2529 int64_t depth = link.getPoolDepth(positions);
2530 int64_t segments = link.getPoolSegments().size();
2531 int64_t selected =
2532 (drains ? link.isDistribute() : link.isJoin()) ? 1 : segments;
2533 int64_t descriptors = depth * selected;
2534 int64_t contiguousObjects = 0;
2535 if (link.walksStream()) {
2536 StreamWindow window;
2537 bool inferred = succeeded(link.getStreamWindow(window));
2538 descriptors = !drains ? 1 : inferred ? window.outputs : 0;
2539 if (inferred)
2540 contiguousObjects = depth + window.top + window.bottom;
2541 }
2542 int64_t repeat = drains ? link.getRepeatCount().value_or(1) : 1;
2543 bool inHardware = repeat > 1 && ((drains && usesPushQueue(*this)) ||
2544 (descriptors == 1 && !getIterCount()));
2545 int64_t passes = 1;
2546 if (drains && link.isDispatch()) {
2547 int64_t objects = std::max<int64_t>(depth, 1);
2548 passes =
2549 std::lcm(objects, static_cast<int64_t>(link.getFifoOuts().size())) /
2550 objects;
2551 }
2552 bool drainLaysOut =
2553 llvm::any_of(link.getOutputObjectFifos(), [](ObjectFifoCreateOp out) {
2554 return !out.getDimensionsToStream().empty();
2555 });
2556 // A merge's one fill end is made for its first output.
2557 bool linkOrdered =
2558 llvm::all_of(
2559 link.getOutputObjectFifos(),
2560 [&](ObjectFifoCreateOp out) { return ordered(out, true); }) &&
2561 (link.isMerge() ||
2562 llvm::all_of(link.getInputObjectFifos(),
2563 [&](ObjectFifoCreateOp in) { return ordered(in, false); }));
2564 return PlannedDmaEnd{descriptors * (inHardware ? 1 : repeat) * passes,
2565 link,
2566 -1,
2567 depth,
2568 walkable(depth) && segments == 1 &&
2569 !link.getRepeatCount() && !link.walksStream() &&
2570 !link.isDispatch() && !drainLaysOut && linkOrdered,
2571 objectBytes(link.getPoolOwner().getElemType()),
2572 contiguousObjects,
2573 channel};
2574}
2575
2576bool ObjectFifoCreateOp::canTakeTurns() {
2577 if (getConsumerTiles().size() != 1)
2578 return false;
2579 auto pinned = [](ObjectFifoEndPortAttr port) {
2580 return port && (port.isCore() || port.channelIndex());
2581 };
2582 bool dispatch = false, walksStream = false;
2583 int64_t repeat = getRepeatCount().value_or(1);
2584 for (ObjectFifoLinkOp link :
2585 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>()) {
2586 if (llvm::is_contained(link.getOutputObjectFifos(), *this)) {
2587 dispatch |= link.isDispatch();
2588 walksStream |= link.walksStream();
2589 repeat = std::max<int64_t>(repeat, link.getRepeatCount().value_or(1));
2590 }
2591 if (link.isMerge() && llvm::is_contained(link.getInputObjectFifos(), *this))
2592 return false;
2593 }
2594 return ObjectFifoDmaEndpointOp::canTakeTurns(
2595 usesPushQueue(*this),
2596 pinned(getProdPortAttr()) || pinned(getConsumerPort(0)), dispatch,
2597 packetHeader() != nullptr, getIterCount().has_value(), repeat,
2598 walksStream);
2599}
2600
2601bool ObjectFifoDmaEndpointOp::canTakeTurns(bool pushQueue, bool pinned,
2602 bool dispatch, bool packet,
2603 bool iterates, int64_t repeat,
2604 bool walksStream) {
2605 return !pushQueue && !pinned && !dispatch && !packet && !iterates &&
2606 repeat == 1 && !walksStream;
2607}
2608
2609int ObjectFifoCreateOp::sharedDepth() {
2610 int depth = size();
2611 if (auto depths = dyn_cast<ArrayAttr>(getElemNumber()))
2612 for (int index = 1, e = depths.size(); index < e; ++index)
2613 depth = std::max(depth, size(index));
2614 return depth;
2615}
2616
2617//===----------------------------------------------------------------------===//
2618// ObjectFifoAllocateOp
2619//===----------------------------------------------------------------------===//
2620
2621LogicalResult ObjectFifoAllocateOp::verify() {
2622 ObjectFifoCreateOp objFifo = getObjectFifo();
2623 if (!objFifo)
2624 return emitError("cannot retrieve associated object FIFO");
2625 if (!isa_and_nonnull<TileLike>(getDelegateTile().getDefiningOp()))
2626 return emitOpError("delegate must be a tile");
2627 if (objFifo.getConsumerTiles().size() != 1)
2628 return emitError("can only be used in 1-to-1 object FIFOs");
2629 // A linked fifo that shares memory keeps its objects in the link's one
2630 // pool, which a core fills or drains one pool object per acquire. Whether
2631 // it shares depends on where its tiles are placed.
2632 std::optional<ObjectFifoLinkOp> linked = objFifo.getLink();
2633 if (std::optional<StringRef> reason = objFifo.dmaReason())
2634 return emitError("cannot allocate a shared memory module to an objectfifo "
2635 "that moves by DMA: ")
2636 << *reason;
2637 if (LinkPoolMisfit misfit =
2638 linked ? objFifo.linkPoolMisfit() : LinkPoolMisfit::None;
2639 linked && misfit != LinkPoolMisfit::None) {
2640 ObjectFifoLinkOp link = *linked;
2641 auto producer = dyn_cast<TileOp>(objFifo.getProducerTile().getDefiningOp());
2642 auto consumer =
2643 dyn_cast<TileOp>(objFifo.getConsumerTiles()[0].getDefiningOp());
2644 auto delegate = dyn_cast<TileOp>(getDelegateTile().getDefiningOp());
2645 // A link without a link point is the link verifier's to report.
2646 std::optional<Value> linkPoint = link.getOptionalSharedTile();
2647 auto linkTile =
2648 linkPoint ? dyn_cast<TileOp>(linkPoint->getDefiningOp()) : TileOp();
2649 bool shared = producer && consumer && delegate && linkTile &&
2650 ObjectFifoCreateOp::allocatedHome(
2651 (*this)->getParentOfType<DeviceOp>().getTargetModel(),
2652 producer.getTileID(), consumer.getTileID(),
2653 delegate.getTileID(), linkTile.getTileID());
2654 StringRef name = objFifo.name().getValue();
2655 if (shared) {
2656 InFlightDiagnostic diag = emitOpError("places @")
2657 << name << "'s objects in the link's pool";
2658 switch (misfit) {
2660 ObjectFifoCreateOp owner = link.getPoolOwner();
2661 diag << ", whose objects are @" << owner.name().getValue() << "'s "
2662 << owner.getElemType().getElementType()
2663 << "; a fifo that shares memory with a link must have the pool's "
2664 "object type (@"
2665 << name << "'s is " << objFifo.getElemType().getElementType()
2666 << ")";
2667 break;
2668 }
2670 diag << ", which starts with @" << link.getPoolOwner().name().getValue()
2671 << "'s initial objects, "
2672 << "but @" << name << " has initial objects of its own";
2673 break;
2675 diag << ", but @" << name
2676 << " is a merge's input, and a merge's inputs take turns filling "
2677 "the pool through one DMA end";
2678 break;
2680 diag << ", but @" << name
2681 << " is a dispatch's output, and a dispatch's outputs take turns "
2682 "draining the pool through one DMA end";
2683 break;
2685 diag << ", but @" << name
2686 << " is one link's output and another link's input, so its "
2687 "objects would be both links' pools";
2688 break;
2690 break;
2691 }
2692 return diag;
2693 }
2694 }
2695 for (Operation *op = (*this)->getPrevNode(); op; op = op->getPrevNode())
2696 if (auto other = dyn_cast<ObjectFifoAllocateOp>(op);
2697 other && other.getObjFifoName() == getObjFifoName())
2698 return emitOpError("objectfifo ")
2699 << getObjFifoNameAttr() << " already has an allocate operation";
2700 return success();
2701}
2702
2703TileOp ObjectFifoAllocateOp::getDelegateTileOp() {
2704 return cast<TileOp>(getDelegateTile().getDefiningOp());
2705}
2706
2707ObjectFifoCreateOp ObjectFifoAllocateOp::getObjectFifo() {
2708 Operation *parent = getOperation();
2709 while ((parent = parent->getParentOp())) {
2710 if (parent->hasTrait<OpTrait::SymbolTable>()) {
2711 if (auto *st = SymbolTable::lookupSymbolIn(parent, getObjFifoName());
2712 isa_and_nonnull<ObjectFifoCreateOp>(st))
2713 return cast<ObjectFifoCreateOp>(st);
2714 }
2715 }
2716 return {};
2717}
2718
2719//===----------------------------------------------------------------------===//
2720// ObjectFifoLinkOp
2721//===----------------------------------------------------------------------===//
2722
2723LogicalResult ObjectFifoLinkOp::verify() {
2724 for (Attribute name : llvm::concat<const Attribute>(
2725 getFifoIns().getValue(), getFifoOuts().getValue())) {
2726 auto flat = dyn_cast<FlatSymbolRefAttr>(name);
2727 if (!flat || !isa_and_nonnull<ObjectFifoCreateOp>(
2728 SymbolTable::lookupNearestSymbolFrom(*this, flat)))
2729 return emitOpError("names no objectfifo ") << name;
2730 }
2731
2732 if (isJoin() && isDistribute())
2733 return emitError("ObjectFifoLinkOp does not support 'join' and "
2734 "'distribute' at the same time");
2735
2736 if (isTime()) {
2737 if (isMerge() && isDispatch())
2738 return emitOpError("a time link merges or dispatches, not both");
2739 if (!isMerge() && !isDispatch())
2740 return emitOpError("a time link takes turns, so it needs several inputs "
2741 "or several outputs");
2742 if (!getSrcOffsets().empty() || !getDstOffsets().empty())
2743 return emitOpError("a time link moves whole objects and takes no "
2744 "offsets");
2745 std::vector<ObjectFifoCreateOp> fifos = getInputObjectFifos();
2746 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
2747 fifos.insert(fifos.end(), outs.begin(), outs.end());
2748 for (ObjectFifoCreateOp fifo : fifos) {
2749 if (fifo.getElemType() != fifos.front().getElemType())
2750 return emitOpError("a time link's participants carry one object "
2751 "type, but '")
2752 << fifo.name().getValue() << "' carries " << fifo.getElemType()
2753 << " and '" << fifos.front().name().getValue() << "' carries "
2754 << fifos.front().getElemType();
2755 }
2756 if (isDispatch()) {
2757 for (ObjectFifoCreateOp out : outs)
2758 if (out.getConsumerTiles().size() != 1)
2759 return emitOpError("each turn of a dispatch reaches one consumer, "
2760 "but '")
2761 << out.name().getValue() << "' has "
2762 << out.getConsumerTiles().size();
2763 }
2764 if (isMerge()) {
2765 PacketInfoAttr pinned;
2766 for (ObjectFifoCreateOp in : getInputObjectFifos()) {
2767 PacketInfoAttr header = in.packetHeader();
2768 if (!header || !header.isAssigned())
2769 continue;
2770 if (pinned && pinned != header)
2771 return emitOpError("a merge is one route with one header, but its "
2772 "inputs pin different ones");
2773 pinned = header;
2774 }
2775 }
2776 }
2777
2778 auto sharedTile = getOptionalSharedTile();
2779 if (!sharedTile)
2780 return emitError("ObjectFifoLinkOp must have a link point, i.e., a "
2781 "shared tile between objectFifos");
2782 // getOptionalSharedTile reads only the first of a time link's inputs and
2783 // outputs.
2784 if (isTime()) {
2785 for (ObjectFifoCreateOp out : getOutputObjectFifos())
2786 if (out.getProducerTile() != *sharedTile)
2787 return emitOpError("a time link's participants meet on its tile, but '")
2788 << out.name().getValue() << "' is produced on another";
2789 for (ObjectFifoCreateOp in : getInputObjectFifos())
2790 if (!llvm::is_contained(in.getConsumerTiles(), *sharedTile))
2791 return emitOpError("a time link's participants meet on its tile, but '")
2792 << in.name().getValue() << "' is consumed on others";
2793 }
2794
2795 // A fifo has one producer, so one link at most fills it; each link reading
2796 // it takes one of its consumer ends on the link's tile. A fifo out of one
2797 // link may go into the next, as a chain of mem tile holds does.
2798 DenseMap<Operation *, size_t> reads;
2799 for (auto other :
2800 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>()) {
2801 if (other == *this) {
2802 break;
2803 }
2804 for (ObjectFifoCreateOp fifo : getOutputObjectFifos())
2805 if (llvm::is_contained(other.getOutputObjectFifos(), fifo))
2806 return fifo.emitOpError(
2807 "objectfifo cannot be filled by more than one ObjectFifoLinkOp");
2808 for (ObjectFifoCreateOp fifo : getInputObjectFifos())
2809 if (llvm::is_contained(other.getInputObjectFifos(), fifo) &&
2810 other.getOptionalSharedTile() == sharedTile)
2811 reads[fifo]++;
2812 }
2813 for (ObjectFifoCreateOp fifo : getInputObjectFifos())
2814 if (reads.lookup(fifo) >=
2815 static_cast<size_t>(llvm::count(fifo.getConsumerTiles(), *sharedTile)))
2816 return fifo.emitOpError("objectfifo is read by more ObjectFifoLinkOps "
2817 "on a tile than it has consumer ends there");
2818
2819 TileLike tile =
2820 llvm::dyn_cast_or_null<TileLike>(sharedTile.value().getDefiningOp());
2821 if (!tile)
2822 return emitError("shared tile must implement TileLike interface");
2823 // Each participant occupies its own slice of the shared object, so the link
2824 // point needs a memory module to hold that object and one counting lock pair
2825 // per slice.
2826 if (isJoin() || isDistribute()) {
2827 if (tile.isShimTile())
2828 return emitError("ObjectFifoLinkOp join and distribute are "
2829 "unavailable on shim tiles");
2830 if (!getTargetModel(getOperation())
2832 return emitError("ObjectFifoLinkOp join and distribute require "
2833 "semaphore locks, which this device lacks");
2834 }
2835 if (isTime() && tile.isShimTile())
2836 return emitOpError("a time link holds its objects on the link point, which "
2837 "a shim tile has no memory for");
2838
2839 // A join or distribute slot must hold a whole number of its participant's
2840 // objects, or one straddles two shared objects and the DMA stalls.
2841 auto elementsOf = [](Type objectFifoType) {
2842 return cast<MemRefType>(
2843 cast<AIEObjectFifoType>(objectFifoType).getElementType())
2844 .getNumElements();
2845 };
2846 // The data layout sizes block-float elements too, which have no bit width.
2847 DataLayout dataLayout = DataLayout::closest(getOperation());
2848 auto bytesOf = [&](Type objectFifoType, int64_t elements) {
2849 return elements *
2850 static_cast<int64_t>(dataLayout.getTypeSize(
2851 cast<MemRefType>(
2852 cast<AIEObjectFifoType>(objectFifoType).getElementType())
2853 .getElementType()));
2854 };
2855 auto checkSlot = [&](StringRef role, ObjectFifoCreateOp participant,
2856 int64_t object, ObjectFifoCreateOp shared,
2857 int64_t slotBytes, ArrayAttr offsets) -> LogicalResult {
2858 if (object <= 0)
2859 return emitOpError() << role << " @" << participant.name().getValue()
2860 << " has empty objects";
2861 if (slotBytes % object == 0)
2862 return success();
2863 std::string offsetText;
2864 llvm::raw_string_ostream os(offsetText);
2865 llvm::interleaveComma(offsets, os, [&](Attribute offset) {
2866 os << *getConstantIntValue(offset);
2867 });
2868 return emitOpError() << role << " @" << participant.name().getValue()
2869 << " has " << object << " B objects, but its "
2870 << slotBytes << " B slot in @"
2871 << shared.name().getValue() << " from offsets ["
2872 << offsetText << "] is not a whole number of them";
2873 };
2874
2875 if (isJoin()) {
2876 if (getFifoIns().size() != getSrcOffsets().size())
2877 return emitOpError("number of provided src offsets must be equal "
2878 "to the number of input objectFifos");
2879
2880 if (!getDstOffsets().empty())
2881 return emitOpError("dst offsets should be empty for join");
2882
2883 // Each input's transfer runs to the next input's offset, so the offsets
2884 // must increase; otherwise the lengths come out wrong and the link hangs.
2885 for (auto [idx, len] : llvm::enumerate(getJoinTransferLengths()))
2886 if (len <= 0)
2887 return emitOpError("src offsets must increase: input objectFifo ")
2888 << idx << " would transfer " << len << " elements";
2889
2890 ObjectFifoCreateOp fifoOut = getOutputObjectFifos()[0];
2891 for (auto [fifoIn, slot] :
2892 llvm::zip(getInputObjectFifos(), getJoinTransferLengths())) {
2893 int64_t object =
2894 fifoIn.getConsumerElemType()
2895 ? bytesOf(fifoIn.getConsumerElemTypeOrDefault(),
2896 elementsOf(fifoIn.getConsumerElemTypeOrDefault()))
2897 : bytesOf(fifoIn.getElemType(),
2898 paddedSize(fifoIn.getDimensionsToStream(),
2899 fifoIn.getPadDimensions().value_or(
2900 ArrayRef<BDPadLayoutAttr>{}),
2901 elementsOf(fifoIn.getElemType())));
2902 if (failed(checkSlot("input", fifoIn, object, fifoOut,
2903 bytesOf(fifoOut.getElemType(), slot),
2904 getSrcOffsets())))
2905 return failure();
2906 }
2907 if (!fifoOut.getDimensionsToStream().empty()) {
2908 int64_t maxIdx = getDimsMaxIdx(fifoOut.getDimensionsToStream());
2909 int64_t minInputBufferSize = -1;
2910 for (auto lenIn : getJoinTransferLengths()) {
2911 if (lenIn <= minInputBufferSize || minInputBufferSize < 0)
2912 minInputBufferSize = lenIn;
2913 }
2914 if (minInputBufferSize <= maxIdx) {
2915 return emitOpError()
2916 << "specified output stride(s) and size(s) result in out "
2917 "of bounds access in join input, for index "
2918 << std::to_string(maxIdx) << " in transfer of length "
2919 << std::to_string(minInputBufferSize) << ".";
2920 }
2921 }
2922
2923 } else if (isDistribute()) {
2924 if (getFifoOuts().size() != getDstOffsets().size())
2925 return emitOpError("number of provided dst offsets must be equal "
2926 "to the number of output objectFifos");
2927
2928 if (!getSrcOffsets().empty())
2929 return emitOpError("src offsets should be empty for distribute");
2930
2931 for (auto [idx, len] : llvm::enumerate(getDistributeTransferLengths()))
2932 if (len <= 0)
2933 return emitOpError("dst offsets must increase: output objectFifo ")
2934 << idx << " would transfer " << len << " elements";
2935
2936 ObjectFifoCreateOp fifoIn = getInputObjectFifos()[0];
2937 for (auto [fifoOut, slot] :
2938 llvm::zip(getOutputObjectFifos(), getDistributeTransferLengths())) {
2939 // The memtile sends the slot, padded if the output pads.
2940 if (failed(checkSlot(
2941 "output", fifoOut,
2942 bytesOf(fifoOut.getElemType(), elementsOf(fifoOut.getElemType())),
2943 fifoIn,
2944 bytesOf(fifoIn.getElemType(),
2945 paddedSize(fifoOut.getDimensionsToStream(),
2946 fifoOut.getPadDimensions().value_or(
2947 ArrayRef<BDPadLayoutAttr>{}),
2948 slot)),
2949 getDstOffsets())))
2950 return failure();
2951 }
2952 // The end this link reads: the next on its tile after earlier links'.
2953 size_t end = 0;
2954 for (size_t seen = 0; end < fifoIn.getConsumerTiles().size(); end++)
2955 if (fifoIn.getConsumerTiles()[end] == *sharedTile &&
2956 seen++ == reads.lookup(fifoIn))
2957 break;
2958 BDDimLayoutArrayAttr dims =
2959 fifoIn.getDimensionsFromStreamPerConsumer()[end];
2960 if (!dims.empty()) {
2961 int64_t maxIdx = getDimsMaxIdx(dims);
2962 int64_t minOutputBufferSize = -1;
2963 for (auto lenOut : getDistributeTransferLengths()) {
2964 if (lenOut <= minOutputBufferSize || minOutputBufferSize < 0)
2965 minOutputBufferSize = lenOut;
2966 }
2967 if (minOutputBufferSize <= maxIdx) {
2968 return emitOpError()
2969 << "specified input stride(s) and size(s) result in out "
2970 "of bounds access in distribute output, for index "
2971 << std::to_string(maxIdx) << " in transfer of length "
2972 << std::to_string(minOutputBufferSize) << ".";
2973 }
2974 }
2975 } else {
2976 if (!getSrcOffsets().empty() && !getDstOffsets().empty())
2977 return emitOpError("all offsets should be empty if there is no "
2978 "join or distribute");
2979 // Each pool object leaves whole in one descriptor, so a walk that covers
2980 // less would run its outer dimension on past the walk.
2981 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
2982 if (!isTime() && !walksStream() && !outs.empty()) {
2983 ArrayRef<BDDimLayoutAttr> dims = outs[0].getDimensionsToStream();
2984 std::optional<ArrayRef<BDPadLayoutAttr>> pads =
2985 outs[0].getPadDimensions();
2986 int64_t walked = 1;
2987 for (BDDimLayoutAttr dim : dims)
2988 walked *= dim.getSize();
2989 int64_t object = elementsOf(getPoolOwner().getElemType());
2990 if (!dims.empty() && (!pads || pads->empty()) && walked != object)
2991 return emitOpError()
2992 << "@" << outs[0].name().getValue() << "'s walk covers "
2993 << walked << " elements, but each transfer sends a whole "
2994 << object
2995 << "-element object; to send part of each input object, walk "
2996 "the stream (an outer dimension stepping whole input "
2997 "objects)";
2998 }
2999 }
3000
3001 if (walksStream()) {
3002 StreamWindow window;
3003 if (failed(getStreamWindow(window)))
3004 return failure();
3005 if (!tile.isMemTile())
3006 return emitOpError("a walk over a stream needs a MemTile link point");
3007 ObjectFifoCreateOp in = getInputObjectFifos()[0];
3008 ObjectFifoCreateOp out = getOutputObjectFifos()[0];
3009 if (in.getRepeatCount() || out.getRepeatCount())
3010 return emitOpError("a walk over a stream does not repeat objects");
3011 if (in.getIterCount() || out.getIterCount())
3012 return emitOpError("a walk over a stream runs without an iter_count");
3013 const AIETargetModel &target = getTargetModel(getOperation());
3014 // Its pool counts the stream's objects on one lock pair, and each output
3015 // is a descriptor of its own on a MemTile channel.
3016 if (window.objects > static_cast<int64_t>(target.getMaxLockValue()))
3017 return emitOpError() << "a walk over a stream of " << window.objects
3018 << " objects needs a lock counting that many, "
3019 "but locks count to "
3020 << target.getMaxLockValue();
3021 // The output channel is unallocated: use the smallest MemTile MM2S pool
3022 // (all memtiles alike, so an unplaced tile uses column 0's).
3023 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
3024 for (int r = 0; (!col || !row) && r < target.rows(); ++r) {
3025 if (target.isMemTile(0, r)) {
3026 col = 0;
3027 row = r;
3028 }
3029 }
3030 std::optional<int64_t> poolBds;
3031 if (col && row)
3032 for (uint32_t channel = 0, channels = target.getNumDMAChannels(
3033 *col, *row, DMAChannelDir::MM2S);
3034 channel < channels; ++channel)
3035 poolBds =
3036 std::min<int64_t>(poolBds.value_or(INT64_MAX),
3037 target.getNumBDsForChannel(*col, *row, channel,
3038 DMAChannelDir::MM2S));
3039 int64_t bds = poolBds.value_or(target.getNumBDs(AIETileType::MemTile) / 2);
3040 if (window.outputs > bds)
3041 return emitOpError() << "a walk over a stream lowers to one descriptor "
3042 "per output, "
3043 << window.outputs << ", but a MemTile channel has "
3044 << bds;
3045 }
3046
3047 // Distribute outputs drain one shared pool with a single repeat count.
3048 // Join inputs repeat at independent producer pools.
3049 if (isDistribute()) {
3050 auto fifos = getOutputObjectFifos();
3051 for (size_t i = 1; i < fifos.size(); ++i) {
3052 ObjectFifoCreateOp first = fifos[0], fifo = fifos[i];
3053 int repeat = first.getRepeatCount().value_or(1);
3054 int otherRepeat = fifo.getRepeatCount().value_or(1);
3055 if (repeat != otherRepeat)
3056 return emitOpError()
3057 << "distribute outputs must have equal effective repeat counts: "
3058 "@"
3059 << first.name().getValue() << " has " << repeat
3060 << (first.getRepeatCount() ? "" : " (default)") << ", @"
3061 << fifo.name().getValue() << " has " << otherRepeat
3062 << (fifo.getRepeatCount() ? "" : " (default)");
3063 }
3064 }
3065
3066 return success();
3067}
3068
3069std::optional<Value> ObjectFifoLinkOp::getOptionalSharedTile() {
3070 std::vector<ObjectFifoCreateOp> fifoIn = getInputObjectFifos();
3071 std::vector<ObjectFifoCreateOp> fifoOut = getOutputObjectFifos();
3072 // A name that resolves to no fifo is the link verifier's to report.
3073 if (fifoIn.size() < getFifoIns().size() ||
3074 fifoOut.size() < getFifoOuts().size() || fifoIn.empty() ||
3075 fifoOut.empty())
3076 return {};
3077
3078 // An input read by several links meets each at its consumer end on that
3079 // link's tile, whichever of its ends that is.
3080 if (isJoin()) {
3081 Value tile = fifoOut[0].getProducerTile();
3082 for (auto in : fifoIn)
3083 if (!llvm::is_contained(in.getConsumerTiles(), tile))
3084 return {};
3085 return {tile};
3086 }
3087
3088 if (isDistribute()) {
3089 Value tile = fifoOut[0].getProducerTile();
3090 for (auto out : fifoOut)
3091 if (out.getProducerTile() != tile)
3092 return {};
3093 if (!llvm::is_contained(fifoIn[0].getConsumerTiles(), tile))
3094 return {};
3095 return {tile};
3096 }
3097
3098 for (auto consumerIn : fifoIn[0].getConsumerTiles())
3099 if (consumerIn == fifoOut[0].getProducerTile())
3100 return {fifoOut[0].getProducerTile()};
3101 return {};
3102}
3103
3104bool ObjectFifoLinkOp::walksStream() {
3105 if (isJoin() || isDistribute())
3106 return false;
3107 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
3108 if (outs.empty())
3109 return false;
3110 ArrayRef<BDDimLayoutAttr> dims = outs[0].getDimensionsToStream();
3111 if (dims.size() < 2 || dims.front().getSize() < 2)
3112 return false;
3113 int64_t inner = 1;
3114 for (BDDimLayoutAttr dim : dims.drop_front())
3115 inner *= dim.getSize();
3116 int64_t objectSize =
3117 cast<AIEObjectFifoType>(getInputObjectFifos()[0].getElemType())
3118 .getElementType()
3119 .getNumElements();
3120 // A walk within one input object (rate conversion) is no window.
3121 return getDimsMaxIdx(dims) >= objectSize &&
3122 inner == cast<AIEObjectFifoType>(outs[0].getElemType())
3123 .getElementType()
3124 .getNumElements();
3125}
3126
3127LogicalResult ObjectFifoLinkOp::getStreamWindow(StreamWindow &window) {
3128 ObjectFifoCreateOp in = getInputObjectFifos()[0];
3129 ObjectFifoCreateOp out = getOutputObjectFifos()[0];
3130 ArrayRef<BDPadLayoutAttr> pads;
3131 if (auto padding = out.getPadDimensions())
3132 pads = *padding;
3133 return inferStreamWindow(
3134 out.getDimensionsToStream(), pads,
3135 cast<AIEObjectFifoType>(in.getElemType())
3136 .getElementType()
3137 .getNumElements(),
3138 [&] { return emitOpError(); }, window);
3139}
3140
3141std::optional<unsigned> ObjectFifoLinkOp::getOwnerConsumerIndex() {
3142 ObjectFifoCreateOp owner = getPoolOwner();
3143 if (!getOptionalSharedTile() ||
3144 llvm::is_contained(getOutputObjectFifos(), owner))
3145 return std::nullopt;
3146 for (unsigned index = 0, e = owner.getConsumerTiles().size(); index < e;
3147 ++index)
3148 if (owner.getConsumerLink(index) == *this)
3149 return index;
3150 return std::nullopt;
3151}
3152
3153int64_t ObjectFifoLinkOp::getPoolDepth() { return getPoolDepth(placedAt); }
3154
3155int64_t ObjectFifoLinkOp::getPoolDepth(TilePositions positions) {
3156 return getPoolPlan().depthAt(getTargetModel(*this), positions);
3157}
3158
3159LinkPoolPlan ObjectFifoLinkOp::getPoolPlan() {
3160 LinkPoolPlan plan{getOptionalSharedTile().value_or(Value()), 0, {}};
3161 StreamWindow window;
3162 if (walksStream()) {
3163 plan.depth = succeeded(getStreamWindow(window)) ? window.objects : 0;
3164 return plan;
3165 }
3166 ObjectFifoCreateOp owner = getPoolOwner();
3167 if (!owner.getAllocate()) {
3168 std::optional<unsigned> index = getOwnerConsumerIndex();
3169 plan.depth = index ? owner.dmaDepth(index) : owner.size();
3170 }
3171 // The owner's allocate puts both its ends in the pool; another
3172 // participant's puts there only its end off the link's tile, the one its
3173 // no-allocate twin keeps in a pool of its own (no core acquires on the
3174 // link's tile).
3175 std::vector<ObjectFifoCreateOp> ins = getInputObjectFifos();
3176 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
3177 for (ObjectFifoCreateOp fifo : llvm::concat<ObjectFifoCreateOp>(ins, outs)) {
3178 std::optional<ObjectFifoAllocateOp> alloc = fifo.getAllocate();
3179 if (!alloc)
3180 continue;
3181 if (fifo == owner)
3182 plan.depth = std::max<int64_t>(
3183 {plan.depth, fifo.dmaDepth(std::nullopt), fifo.dmaDepth(0)});
3184 else if (plan.linkTile && fifo.getConsumerTiles().size() == 1 &&
3185 fifo.linkPoolMisfit() == LinkPoolMisfit::None)
3186 plan.sharers.push_back(
3187 {fifo.getProducerTile(), fifo.getConsumerTiles()[0],
3188 alloc->getDelegateTile(),
3189 llvm::is_contained(outs, fifo) ? fifo.dmaDepth(0)
3190 : fifo.dmaDepth(std::nullopt)});
3191 }
3192 return plan;
3193}
3194
3196 TilePositions positions) const {
3197 int64_t result = depth;
3198 std::optional<TileID> link =
3199 sharers.empty() ? std::nullopt : positions(linkTile);
3200 for (const LinkPoolSharer &sharer : sharers) {
3201 std::optional<TileID> producer = positions(sharer.producer);
3202 std::optional<TileID> consumer = positions(sharer.consumer);
3203 std::optional<TileID> delegate = positions(sharer.delegate);
3204 if (link && producer && consumer && delegate &&
3205 ObjectFifoCreateOp::allocatedHome(target, *producer, *consumer,
3206 *delegate, link))
3207 result = std::max(result, sharer.depth);
3208 }
3209 return result;
3210}
3211
3212ObjectFifoCreateOp ObjectFifoLinkOp::getPoolOwner() {
3213 std::vector<ObjectFifoCreateOp> ins = getInputObjectFifos();
3214 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
3215 if (isJoin() || isMerge())
3216 return outs[0];
3217 if (isDistribute() || isDispatch())
3218 return ins[0];
3219 // A window's pool holds the stream it walks, object by object.
3220 if (walksStream())
3221 return ins[0];
3222 auto count = [](ObjectFifoCreateOp fifo) {
3223 return cast<AIEObjectFifoType>(fifo.getElemType())
3224 .getElementType()
3225 .getNumElements();
3226 };
3227 // Padding is applied as the objects leave, so the pool holds what arrives.
3228 if (outs[0].getInitValues() ||
3229 (count(outs[0]) > count(ins[0]) && !outs[0].getPadDimensions()))
3230 return outs[0];
3231 return ins[0];
3232}
3233
3234SmallVector<std::pair<int64_t, int64_t>> ObjectFifoLinkOp::getPoolSegments() {
3235 auto count = [](ObjectFifoCreateOp fifo) {
3236 return cast<AIEObjectFifoType>(fifo.getElemType())
3237 .getElementType()
3238 .getNumElements();
3239 };
3240 int64_t whole = count(getPoolOwner());
3241 if (!isJoin() && !isDistribute())
3242 return {{0, whole}};
3243 ArrayAttr offsets = isJoin() ? getSrcOffsets() : getDstOffsets();
3244 std::vector<ObjectFifoCreateOp> side =
3245 isJoin() ? getInputObjectFifos() : getOutputObjectFifos();
3246 SmallVector<std::pair<int64_t, int64_t>> segments;
3247 for (auto [index, participant] : llvm::enumerate(side)) {
3248 int64_t offset = cast<IntegerAttr>(offsets[index]).getInt();
3249 int64_t next = index + 1 < side.size()
3250 ? cast<IntegerAttr>(offsets[index + 1]).getInt()
3251 : whole;
3252 int64_t size = next - offset;
3253 if (size <= 0)
3254 size = count(participant);
3255 segments.emplace_back(offset, size);
3256 }
3257 return segments;
3258}
3259
3260std::vector<ObjectFifoCreateOp> ObjectFifoLinkOp::getInputObjectFifos() {
3261 std::vector<ObjectFifoCreateOp> inputObjFifos;
3262 Operation *parent = getOperation();
3263 while ((parent = parent->getParentOp())) {
3264 if (parent->hasTrait<OpTrait::SymbolTable>()) {
3265 for (auto sym : getFifoIns()) {
3266 auto name = dyn_cast<FlatSymbolRefAttr>(sym);
3267 if (!name)
3268 continue;
3269 if (auto *st = SymbolTable::lookupSymbolIn(parent, name);
3270 isa_and_nonnull<ObjectFifoCreateOp>(st))
3271 inputObjFifos.push_back(cast<ObjectFifoCreateOp>(st));
3272 }
3273 }
3274 }
3275 return inputObjFifos;
3276}
3277
3278std::vector<ObjectFifoCreateOp> ObjectFifoLinkOp::getOutputObjectFifos() {
3279 std::vector<ObjectFifoCreateOp> outputObjFifos;
3280 Operation *parent = getOperation();
3281 while ((parent = parent->getParentOp())) {
3282 if (parent->hasTrait<OpTrait::SymbolTable>()) {
3283 for (auto sym : getFifoOuts()) {
3284 auto name = dyn_cast<FlatSymbolRefAttr>(sym);
3285 if (!name)
3286 continue;
3287 if (auto *st = mlir::SymbolTable::lookupSymbolIn(parent, name);
3288 isa_and_nonnull<ObjectFifoCreateOp>(st))
3289 outputObjFifos.push_back(cast<ObjectFifoCreateOp>(st));
3290 }
3291 }
3292 }
3293 return outputObjFifos;
3294}
3295
3296std::vector<int> ObjectFifoLinkOp::getJoinTransferLengths() {
3297 std::vector<int> lengths;
3298 if (isJoin()) {
3299 auto fifoOut =
3300 llvm::cast<AIEObjectFifoType>(getOutputObjectFifos()[0].getElemType());
3301 auto elemTypeOut = llvm::cast<MemRefType>(fifoOut.getElementType());
3302 int lenOut = elemTypeOut.getNumElements();
3303 // src_offsets is an I64ArrayAttr, so every element is an IntegerAttr and
3304 // getConstantIntValue always yields a value; assert to keep this fail-fast.
3305 auto srcOffset = [&](size_t idx) -> int {
3306 std::optional<int64_t> v = getConstantIntValue(getSrcOffsets()[idx]);
3307 assert(v && "src_offsets element must be a constant integer");
3308 return static_cast<int>(*v);
3309 };
3310 for (size_t i = 0; i < getFifoIns().size(); i++) {
3311 int len = 0;
3312 int offset = srcOffset(i);
3313 if (i == getFifoIns().size() - 1)
3314 len = lenOut - offset;
3315 else
3316 len = srcOffset(i + 1) - offset;
3317 lengths.push_back(len);
3318 }
3319 }
3320 return lengths;
3321}
3322
3323std::vector<int> ObjectFifoLinkOp::getDistributeTransferLengths() {
3324 std::vector<int> lengths;
3325 if (isDistribute()) {
3326 auto fifoIn =
3327 llvm::cast<AIEObjectFifoType>(getInputObjectFifos()[0].getElemType());
3328 auto elemTypeIn = llvm::cast<MemRefType>(fifoIn.getElementType());
3329 int lenIn = elemTypeIn.getNumElements();
3330 // dst_offsets is an I64ArrayAttr, so every element is an IntegerAttr and
3331 // getConstantIntValue always yields a value; assert to keep this fail-fast.
3332 auto dstOffset = [&](size_t idx) -> int {
3333 std::optional<int64_t> v = getConstantIntValue(getDstOffsets()[idx]);
3334 assert(v && "dst_offsets element must be a constant integer");
3335 return static_cast<int>(*v);
3336 };
3337 for (size_t i = 0; i < getFifoOuts().size(); i++) {
3338 int offset = dstOffset(i);
3339 int len = 0;
3340 if (i == getFifoOuts().size() - 1)
3341 len = lenIn - offset;
3342 else
3343 len = dstOffset(i + 1) - offset;
3344 lengths.push_back(len);
3345 }
3346 }
3347 return lengths;
3348}
3349
3350std::optional<int> ObjectFifoLinkOp::getRepeatCount() {
3351 for (auto fifoOut : getOutputObjectFifos())
3352 if (fifoOut.getRepeatCount().has_value())
3353 return {fifoOut.getRepeatCount()};
3354 return {};
3355}
3356
3357//===----------------------------------------------------------------------===//
3358// ObjectFifoRegisterExternalBuffersOp
3359//===----------------------------------------------------------------------===//
3360
3361TileOp ObjectFifoRegisterExternalBuffersOp::getTileOp() {
3362 return cast<TileOp>(getTile().getDefiningOp());
3363}
3364
3365ObjectFifoCreateOp ObjectFifoRegisterExternalBuffersOp::getObjectFifo() {
3366 Operation *parent = getOperation();
3367 while ((parent = parent->getParentOp())) {
3368 if (parent->hasTrait<OpTrait::SymbolTable>()) {
3369 if (auto *st = SymbolTable::lookupSymbolIn(parent, getObjFifoName());
3370 isa_and_nonnull<ObjectFifoCreateOp>(st))
3371 return cast<ObjectFifoCreateOp>(st);
3372 }
3373 }
3374 return {};
3375}
3376
3377//===----------------------------------------------------------------------===//
3378// ObjectFifoAcquireOp
3379//===----------------------------------------------------------------------===//
3380
3381namespace {
3382
3383/// Symbol an objectFifo access names: the fifo it belongs to, or the core
3384/// endpoint it works through.
3385Operation *lookupAccessTarget(Operation *op, StringRef name) {
3386 for (Operation *parent = op->getParentOp(); parent;
3387 parent = parent->getParentOp()) {
3388 if (parent->hasTrait<OpTrait::SymbolTable>()) {
3389 if (Operation *target = SymbolTable::lookupSymbolIn(parent, name)) {
3390 return target;
3391 }
3392 }
3393 }
3394 return nullptr;
3395}
3396
3397/// Element type an access sees, or a null type if the symbol names neither a
3398/// fifo nor an endpoint.
3399Type accessElementType(Operation *target) {
3400 if (auto fifo = dyn_cast_or_null<ObjectFifoCreateOp>(target)) {
3401 return llvm::cast<AIEObjectFifoType>(fifo.getElemType()).getElementType();
3402 }
3403 if (auto endpoint = dyn_cast_or_null<ObjectFifoCoreEndpointOp>(target)) {
3404 if (endpoint.getPoolOp()) {
3405 return endpoint.getAccessType();
3406 }
3407 }
3408 return {};
3409}
3410
3411/// A core may only reach a fifo end that is placed on its own tile.
3412LogicalResult verifyAccessPlacement(Operation *op, Operation *target,
3413 std::optional<ObjectFifoPort> port) {
3414 auto core = op->getParentOfType<CoreOp>();
3415 Value coreTile = core.getTile();
3416
3417 if (auto endpoint = dyn_cast_or_null<ObjectFifoCoreEndpointOp>(target)) {
3418 if (port) {
3419 return op->emitOpError("port is implied by the endpoint's role");
3420 }
3421 if (endpoint.getTile() != coreTile) {
3422 return core.emitOpError(
3423 "objectFifo endpoint accessed by core running on another tile");
3424 }
3425 return success();
3426 }
3427
3428 auto fifo = dyn_cast_or_null<ObjectFifoCreateOp>(target);
3429 if (!fifo) {
3430 return op->emitError("cannot retrieve associated object FIFO");
3431 }
3432 if (!port) {
3433 return op->emitOpError("port is required when accessing an objectFifo");
3434 }
3435
3436 if (*port == ObjectFifoPort::Produce) {
3437 if (coreTile != fifo.getProducerTile()) {
3438 return core.emitOpError(
3439 "producer port of objectFifo accessed by core running "
3440 "on non-producer tile");
3441 }
3442 } else {
3443 if (!llvm::is_contained(fifo.getConsumerTiles(), coreTile)) {
3444 return core.emitOpError(
3445 "consumer port of objectFifo accessed by core running "
3446 "on non-consumer tile");
3447 }
3448 }
3449 return success();
3450}
3451
3452} // namespace
3453
3454LogicalResult ObjectFifoAcquireOp::verify() {
3455 auto parent = getOperation()->getParentOfType<CoreOp>();
3456 if (parent == nullptr) {
3457 return emitOpError("must be called from inside a CoreOp");
3458 }
3459
3460 Operation *target = lookupAccessTarget(*this, getObjFifoName());
3461 if (failed(verifyAccessPlacement(*this, target, getPort()))) {
3462 return failure();
3463 }
3464
3465 if (getObjects().empty()) {
3466 return emitOpError("must acquire at least one object");
3467 }
3468
3469 Type elem = accessElementType(target);
3470 if (!elem) {
3471 return success();
3472 }
3473 auto fifo = dyn_cast<ObjectFifoCreateOp>(target);
3474 if (fifo) {
3475 // A fifo may state a depth per endpoint, the producer first.
3476 int index = 0;
3477 if (getPort() == ObjectFifoPort::Consume) {
3478 for (auto [position, consumer] :
3479 llvm::enumerate(fifo.getConsumerTiles())) {
3480 if (consumer == parent.getTile()) {
3481 index = position + 1;
3482 break;
3483 }
3484 }
3485 }
3486 if (static_cast<int>(getObjects().size()) > fifo.size(index)) {
3487 return emitOpError("acquires ")
3488 << getObjects().size() << " objects from an objectFifo that holds "
3489 << fifo.size(index);
3490 }
3491 }
3492 // An asymmetric fifo hands the consumer a different element type.
3493 auto consType = fifo ? llvm::dyn_cast<AIEObjectFifoType>(
3494 fifo.getConsumerElemTypeOrDefault())
3495 : nullptr;
3496 if (fifo && !consType) {
3497 return emitOpError("ObjectFifo consumer element type must be an "
3498 "!aie.objectfifo<memref<...>> type");
3499 }
3500
3501 for (Type object : getObjects().getTypes()) {
3502 if (object != elem && (!consType || consType.getElementType() != object)) {
3503 return emitOpError("acquired object type ")
3504 << object << " does not match the objectFifo's " << elem;
3505 }
3506 }
3507
3508 return success();
3509}
3510
3511ObjectFifoCreateOp ObjectFifoAcquireOp::getObjectFifo() {
3512 Operation *parent = getOperation();
3513 while ((parent = parent->getParentOp())) {
3514 if (parent->hasTrait<OpTrait::SymbolTable>()) {
3515 if (auto *st = SymbolTable::lookupSymbolIn(parent, getObjFifoName());
3516 isa_and_nonnull<ObjectFifoCreateOp>(st))
3517 return cast<ObjectFifoCreateOp>(st);
3518 }
3519 }
3520 return {};
3521}
3522
3523//===----------------------------------------------------------------------===//
3524// ObjectFifoReleaseOp
3525//===----------------------------------------------------------------------===//
3526
3527LogicalResult ObjectFifoReleaseOp::verify() {
3528 auto parent = getOperation()->getParentOfType<CoreOp>();
3529 if (parent == nullptr)
3530 return emitOpError("must be called from inside a CoreOp");
3531
3532 Operation *target = lookupAccessTarget(*this, getObjFifoName());
3533 return verifyAccessPlacement(*this, target, getPort());
3534}
3535
3536ObjectFifoCreateOp ObjectFifoReleaseOp::getObjectFifo() {
3537 Operation *parent = getOperation();
3538 while ((parent = parent->getParentOp())) {
3539 if (parent->hasTrait<OpTrait::SymbolTable>()) {
3540 if (auto *st = SymbolTable::lookupSymbolIn(parent, getObjFifoName());
3541 isa_and_nonnull<ObjectFifoCreateOp>(st))
3542 return cast<ObjectFifoCreateOp>(st);
3543 }
3544 }
3545 return {};
3546}
3547
3548//===----------------------------------------------------------------------===//
3549// CascadeFlowOp
3550//===----------------------------------------------------------------------===//
3551
3552LogicalResult CascadeFlowOp::verify() {
3553 TileLike src = getSourceTileLike();
3554 TileLike dst = getDestTileLike();
3555
3556 if (!src || !dst)
3557 return emitOpError("source and dest must be tile-like operations");
3558
3559 if (src.isShimTile() || dst.isShimTile())
3560 return emitOpError("shimTile row has no cascade stream interface");
3561 if (src.isMemTile() || dst.isMemTile())
3562 return emitOpError("memTile row has no cascade stream interface");
3563
3564 const auto &t = getTargetModel(*this);
3565 // Which ways a cascade may run is the target's; an op built outside any
3566 // device is checked for adjacency alone.
3567 bool onTarget = (*this)->getParentOfType<AIETarget>() != nullptr;
3568 if (onTarget && t.getCascadeSteps().empty())
3569 return emitOpError("cascade not supported in ")
3570 << stringifyAIEArch(t.getTargetArch());
3571
3572 std::optional<int> srcCol = src.tryGetCol();
3573 std::optional<int> srcRow = src.tryGetRow();
3574 std::optional<int> dstCol = dst.tryGetCol();
3575 std::optional<int> dstRow = dst.tryGetRow();
3576
3577 if (srcCol && srcRow && dstCol && dstRow) {
3578 if (!t.isSouth(*srcCol, *srcRow, *dstCol, *dstRow) &&
3579 !t.isWest(*srcCol, *srcRow, *dstCol, *dstRow) &&
3580 !t.isNorth(*srcCol, *srcRow, *dstCol, *dstRow) &&
3581 !t.isEast(*srcCol, *srcRow, *dstCol, *dstRow)) {
3582 return emitOpError("tiles must be adjacent");
3583 }
3584 if (onTarget && !t.isLegalCascade(*srcCol, *srcRow, *dstCol, *dstRow))
3585 return emitOpError("source tile must be to the North or West of the "
3586 "destination tile");
3587 }
3588
3589 return success();
3590}
3591
3592TileLike CascadeFlowOp::getSourceTileLike() {
3593 return dyn_cast_or_null<TileLike>(getSourceTile().getDefiningOp());
3594}
3595
3596TileLike CascadeFlowOp::getDestTileLike() {
3597 return dyn_cast_or_null<TileLike>(getDestTile().getDefiningOp());
3598}
3599
3600TileOp CascadeFlowOp::getSourceTileOp() {
3601 if (auto tileOp = dyn_cast_or_null<TileOp>(getSourceTile().getDefiningOp()))
3602 return tileOp;
3603 llvm::report_fatal_error("Calling getSourceTileOp requires TileOp.");
3604}
3605
3606TileOp CascadeFlowOp::getDestTileOp() {
3607 if (auto tileOp = dyn_cast_or_null<TileOp>(getDestTile().getDefiningOp()))
3608 return tileOp;
3609 llvm::report_fatal_error("Calling getDestTileOp requires TileOp.");
3610}
3611
3612//===----------------------------------------------------------------------===//
3613// ConfigureCascadeOp
3614//===----------------------------------------------------------------------===//
3615
3616// The direction a cascade step (dstCol - srcCol, dstRow - srcRow) leaves the
3617// source tile on; getCascadeSteps() only ever returns axis-aligned unit steps.
3618static CascadeDir cascadeStepOutputDir(std::pair<int, int> step) {
3619 if (step.first == 1)
3620 return CascadeDir::East;
3621 if (step.first == -1)
3622 return CascadeDir::West;
3623 return step.second == 1 ? CascadeDir::North : CascadeDir::South;
3624}
3625
3626static CascadeDir oppositeCascadeDir(CascadeDir dir) {
3627 switch (dir) {
3628 case CascadeDir::North:
3629 return CascadeDir::South;
3630 case CascadeDir::South:
3631 return CascadeDir::North;
3632 case CascadeDir::East:
3633 return CascadeDir::West;
3634 case CascadeDir::West:
3635 return CascadeDir::East;
3636 }
3637 llvm_unreachable("unhandled CascadeDir");
3638}
3639
3640static std::string describeCascadeDirs(ArrayRef<CascadeDir> dirs) {
3641 std::string s;
3642 llvm::raw_string_ostream os(s);
3643 llvm::interleave(
3644 dirs, os, [&](CascadeDir d) { os << stringifyCascadeDir(d); }, " or ");
3645 return s;
3646}
3647
3648LogicalResult ConfigureCascadeOp::verify() {
3649 Operation *tileDef = getTile().getDefiningOp();
3650 if (!isa_and_nonnull<TileLike>(tileDef))
3651 return emitOpError("tile operand is not an aie.tile or aie.logical_tile");
3652 auto tile = dyn_cast<TileOp>(tileDef);
3653 if (!tile)
3654 return emitOpError("requires a placed tile (aie.tile), not a logical tile");
3655
3656 const auto &t = getTargetModel(*this);
3657 CascadeDir inputDir = getInputDir();
3658 CascadeDir outputDir = getOutputDir();
3659
3660 if (tile.isShimTile())
3661 return emitOpError("shimTile row has no cascade stream interface");
3662 if (tile.isMemTile())
3663 return emitOpError("memTile row has no cascade stream interface");
3664
3665 llvm::ArrayRef<std::pair<int, int>> steps = t.getCascadeSteps();
3666 if (!steps.empty()) {
3667 SmallVector<CascadeDir> legalOutputs, legalInputs;
3668 for (std::pair<int, int> step : steps) {
3669 legalOutputs.push_back(cascadeStepOutputDir(step));
3670 legalInputs.push_back(oppositeCascadeDir(legalOutputs.back()));
3671 }
3672 if (!llvm::is_contained(legalInputs, inputDir))
3673 return emitOpError("input direction of cascade must be ")
3674 << describeCascadeDirs(legalInputs) << " on "
3675 << stringifyAIEArch(t.getTargetArch());
3676 if (!llvm::is_contained(legalOutputs, outputDir))
3677 return emitOpError("output direction of cascade must be ")
3678 << describeCascadeDirs(legalOutputs) << " on "
3679 << stringifyAIEArch(t.getTargetArch());
3680 } else {
3681 return emitOpError("cascade not supported in ")
3682 << stringifyAIEArch(t.getTargetArch());
3683 }
3684 return success();
3685}
3686
3687//===----------------------------------------------------------------------===//
3688// PutCascadeOp
3689//===----------------------------------------------------------------------===//
3690
3691LogicalResult PutCascadeOp::verify() {
3692 const auto &targetModel = getTargetModel(*this);
3693 Type type = getCascadeValue().getType();
3694 DataLayout dataLayout = DataLayout::closest(*this);
3695 auto bits = dataLayout.getTypeSizeInBits(type);
3696 auto archbits = targetModel.getAccumulatorCascadeSize();
3697 if (bits != archbits)
3698 return emitOpError("type must match architecture cascade width (")
3699 << archbits << " bits in "
3700 << stringifyAIEArch(targetModel.getTargetArch()) << ")";
3701 return success();
3702}
3703
3704//===----------------------------------------------------------------------===//
3705// GetCascadeOp
3706//===----------------------------------------------------------------------===//
3707
3708LogicalResult GetCascadeOp::verify() {
3709 const auto &targetModel = getTargetModel(*this);
3710 Type type = getCascadeValue().getType();
3711 DataLayout dataLayout = DataLayout::closest(*this);
3712 auto bits = dataLayout.getTypeSizeInBits(type);
3713 auto archbits = targetModel.getAccumulatorCascadeSize();
3714 if (bits != archbits)
3715 return emitOpError("must be a ") << archbits << "-bit type";
3716 return success();
3717}
3718
3719//===----------------------------------------------------------------------===//
3720// GetStreamOp, PutStreamOp
3721//===----------------------------------------------------------------------===//
3722
3723// AIE4 cores read two input streams in 512/1024-bit units and write one output
3724// in 32/256/512-bit units; earlier cores have no vector stream access.
3725
3726LogicalResult GetStreamOp::verify() {
3727 Type type = getStreamValue().getType();
3728 auto vectorType = dyn_cast<VectorType>(type);
3729 if (!isa<AIE4TargetModel>(getTargetModel(*this))) {
3730 if (vectorType)
3731 return emitOpError("vector stream reads are only supported on AIE4");
3732 return success();
3733 }
3734 if (!vectorType)
3735 return emitOpError("AIE4 cores read streams in 512-bit or 1024-bit units; "
3736 "use a vector<16xi32> or vector<32xi32> result instead "
3737 "of ")
3738 << type
3739 << " (a 32-bit read has no AIE4 equivalent outside the load-FIFO "
3740 "mode)";
3741 if (vectorType.getRank() != 1 || vectorType.isScalable())
3742 return emitOpError("AIE4 stream reads require a fixed rank-1 "
3743 "vector<16xi32> or vector<32xi32> result; got ")
3744 << type;
3745 APInt channel;
3746 if (matchPattern(getChannel(), m_ConstantInt(&channel)) && channel.ugt(1))
3747 return emitOpError("AIE4 cores have input streams 0 and 1 only; got ")
3748 << llvm::toString(channel, /*Radix=*/10, /*Signed=*/false);
3749 return success();
3750}
3751
3752LogicalResult PutStreamOp::verify() {
3753 Type type = getStreamValue().getType();
3754 auto vectorType = dyn_cast<VectorType>(type);
3755 if (!isa<AIE4TargetModel>(getTargetModel(*this))) {
3756 if (vectorType)
3757 return emitOpError("vector stream writes are only supported on AIE4");
3758 return success();
3759 }
3760 if (!type.isSignlessInteger(32) &&
3761 (!vectorType || vectorType.getRank() != 1 || vectorType.isScalable()))
3762 return emitOpError("AIE4 stream writes require i32 or a fixed rank-1 "
3763 "vector<8xi32> or vector<16xi32> value; got ")
3764 << type;
3765 APInt channel;
3766 if (matchPattern(getChannel(), m_ConstantInt(&channel)) && !channel.isZero())
3767 return emitOpError("AIE4 cores have output stream 0 only");
3768 return success();
3769}
3770
3771//===----------------------------------------------------------------------===//
3772// DeviceOp
3773//===----------------------------------------------------------------------===//
3774
3775namespace {
3776
3777// A flow endpoint reduced to a comparable key: resolved tile coordinates plus
3778// the stream-switch port, as (col, row, bundle, channel). Only used for
3779// equality and ordering, so the raw WireBundle enum value is a fine component.
3780using PortKey = std::tuple<int, int, int, int>;
3781
3782// Returns the key for the port (`tileValue`, `bundle`, `channel`), or nullopt
3783// when the tile's coordinates are not known yet -- an aie.logical_tile that
3784// --aie-place-tiles has not placed. Two such endpoints cannot be compared
3785// until placement runs, at which point the caller's check runs again on the
3786// resulting aie.tile coordinates.
3787std::optional<PortKey> tryGetPortKey(Value tileValue, WireBundle bundle,
3788 int channel) {
3789 auto tile = llvm::dyn_cast_or_null<TileLike>(tileValue.getDefiningOp());
3790 if (!tile)
3791 return std::nullopt;
3792 std::optional<int> col = tile.tryGetCol();
3793 std::optional<int> row = tile.tryGetRow();
3794 if (!col || !row)
3795 return std::nullopt;
3796 return PortKey{*col, *row, static_cast<int>(bundle), channel};
3797}
3798
3799std::string to_string(const PortKey &key) {
3800 auto [col, row, bundle, channel] = key;
3801 return "(" + std::to_string(col) + ", " + std::to_string(row) + ") " +
3802 stringifyWireBundle(static_cast<WireBundle>(bundle)).str() + " : " +
3803 std::to_string(channel);
3804}
3805
3806// Rejects two aie.flow ops that declare the same source and destination port.
3807// A repeated flow is not a harmless redundancy: Pathfinder::addFlow folds a
3808// flow into any existing flow with the same source, so the duplicate lands in
3809// that flow's destination list a second time and the router is asked to
3810// broadcast to the same endpoint twice.
3811LogicalResult verifyNoDuplicateFlows(DeviceOp device) {
3812 std::map<std::pair<PortKey, PortKey>, FlowOp> flowSeen;
3813 for (FlowOp flow : device.getOps<FlowOp>()) {
3814 std::optional<PortKey> src = tryGetPortKey(
3815 flow.getSource(), flow.getSourceBundle(), flow.getSourceChannel());
3816 std::optional<PortKey> dst = tryGetPortKey(
3817 flow.getDest(), flow.getDestBundle(), flow.getDestChannel());
3818 if (!src || !dst)
3819 continue;
3820 auto [it, inserted] = flowSeen.try_emplace({*src, *dst}, flow);
3821 if (!inserted) {
3822 InFlightDiagnostic diag = flow.emitOpError()
3823 << "duplicates an earlier flow; "
3824 << to_string(*src) << " -> " << to_string(*dst)
3825 << " is already declared";
3826 diag.attachNote(it->second.getLoc()) << "the other flow is here";
3827 return failure();
3828 }
3829 }
3830 return success();
3831}
3832
3833// Rejects two aie.packet_flow ops that carry the same ID between the same set
3834// of sources and destinations under the same mask. Declaring the flow twice
3835// makes the routing problem look more congested than it is and gives the two
3836// copies conflicting keep_pkt_header/priority_route settings when their
3837// attributes disagree.
3838LogicalResult verifyNoDuplicatePacketFlows(DeviceOp device) {
3839 using PacketFlowKey =
3840 std::tuple<int, int, std::vector<PortKey>, std::vector<PortKey>>;
3841 std::map<PacketFlowKey, PacketFlowOp> packetFlowSeen;
3842 for (PacketFlowOp packetFlow : device.getOps<PacketFlowOp>()) {
3843 Region &body = packetFlow.getPorts();
3844 if (body.empty())
3845 continue;
3846 // Sources and destinations are unordered within a packet flow, so sort
3847 // both to give permutations of the same flow the same key.
3848 std::vector<PortKey> sources, dests;
3849 bool comparable = true;
3850 for (Operation &op : body.front()) {
3851 std::vector<PortKey> *endpoints = nullptr;
3852 std::optional<PortKey> port;
3853 if (auto source = dyn_cast<PacketSourceOp>(op)) {
3854 endpoints = &sources;
3855 port = tryGetPortKey(source.getTile(), source.getBundle(),
3856 source.getChannel());
3857 } else if (auto dest = dyn_cast<PacketDestOp>(op)) {
3858 endpoints = &dests;
3859 port =
3860 tryGetPortKey(dest.getTile(), dest.getBundle(), dest.getChannel());
3861 } else {
3862 continue;
3863 }
3864 // One unplaced endpoint makes the whole flow incomparable.
3865 if (!port) {
3866 comparable = false;
3867 break;
3868 }
3869 endpoints->push_back(*port);
3870 }
3871 if (!comparable || sources.empty() || dests.empty())
3872 continue;
3873 llvm::sort(sources);
3874 llvm::sort(dests);
3875 int mask = packetFlow.getMask().value_or(
3876 device.getTargetModel().getPacketIdMask());
3877 auto [it, inserted] = packetFlowSeen.try_emplace(
3878 {packetFlow.IDInt(), mask, std::move(sources), std::move(dests)},
3879 packetFlow);
3880 if (!inserted) {
3881 InFlightDiagnostic diag =
3882 packetFlow.emitOpError()
3883 << "duplicates an earlier packet flow; ID " << packetFlow.IDInt()
3884 << " under mask 0x" << llvm::utohexstr(mask)
3885 << " is already declared between the same sources and destinations";
3886 diag.attachNote(it->second.getLoc()) << "the other packet flow is here";
3887 return failure();
3888 }
3889 }
3890 return success();
3891}
3892
3893// Rejects two DMA programs on one tile starting the same channel: each would
3894// queue its own chain on it, and the later never runs behind an endless one.
3895static LogicalResult verifyNoSharedProgramChannels(DeviceOp device) {
3896 std::map<std::tuple<Operation *, int, int, DMAChannelDir, int>,
3897 std::pair<DMAStartOp, Operation *>>
3898 starts;
3899 for (DmaBody program : device.getOps<DmaBody>()) {
3900 Operation *tile = cast<TileElement>(*program).getTile().getDefiningOp();
3901 auto like = dyn_cast_or_null<TileLike>(tile);
3902 std::optional<int> col = like ? like.tryGetCol() : std::nullopt;
3903 std::optional<int> row = like ? like.tryGetRow() : std::nullopt;
3904 Operation *key = col && row ? nullptr : tile;
3905 for (DMAStartOp start : program.getDmaBody().getOps<DMAStartOp>()) {
3906 if (start.getEndpoint())
3907 continue;
3908 auto [it, added] =
3909 starts.try_emplace({key, col.value_or(-1), row.value_or(-1),
3910 start.getChannelDir(), start.getChannelIndex()},
3911 start, program);
3912 if (added || it->second.second == program)
3913 continue;
3914 InFlightDiagnostic diag =
3915 start.emitOpError()
3916 << stringifyDMAChannelDir(start.getChannelDir()) << " channel "
3917 << start.getChannelIndex()
3918 << " is started by another DMA program on this tile too";
3919 diag.attachNote(it->second.first.getLoc()) << "the other start is here";
3920 return failure();
3921 }
3922 }
3923 return success();
3924}
3925
3926// Rejects two aie.flows into one port and a packet flow sharing an endpoint
3927// with an aie.flow: a circuit sends every word from its source, packets
3928// included, and its destination takes words from nothing else.
3929LogicalResult verifyNoSharedCircuitPorts(DeviceOp device) {
3930 std::map<PortKey, FlowOp> circuitSources, circuitDests;
3931 for (FlowOp flow : device.getOps<FlowOp>()) {
3932 std::optional<PortKey> src = tryGetPortKey(
3933 flow.getSource(), flow.getSourceBundle(), flow.getSourceChannel());
3934 std::optional<PortKey> dst = tryGetPortKey(
3935 flow.getDest(), flow.getDestBundle(), flow.getDestChannel());
3936 if (src)
3937 circuitSources.try_emplace(*src, flow);
3938 if (!dst)
3939 continue;
3940 auto [it, inserted] = circuitDests.try_emplace(*dst, flow);
3941 if (inserted)
3942 continue;
3943 InFlightDiagnostic diag =
3944 flow.emitOpError()
3945 << "ends at " << to_string(*dst)
3946 << ", where another circuit flow ends; a port takes one circuit";
3947 diag.attachNote(it->second.getLoc()) << "the other circuit flow is here";
3948 return failure();
3949 }
3950 for (PacketFlowOp packetFlow : device.getOps<PacketFlowOp>()) {
3951 Region &body = packetFlow.getPorts();
3952 if (body.empty())
3953 continue;
3954 for (Operation &op : body.front()) {
3955 std::optional<PortKey> port;
3956 std::map<PortKey, FlowOp> *circuits = nullptr;
3957 StringRef role;
3958 if (auto source = dyn_cast<PacketSourceOp>(op)) {
3959 port = tryGetPortKey(source.getTile(), source.getBundle(),
3960 source.getChannel());
3961 circuits = &circuitSources;
3962 role = "starts";
3963 } else if (auto dest = dyn_cast<PacketDestOp>(op)) {
3964 port =
3965 tryGetPortKey(dest.getTile(), dest.getBundle(), dest.getChannel());
3966 circuits = &circuitDests;
3967 role = "ends";
3968 }
3969 if (!port)
3970 continue;
3971 auto it = circuits->find(*port);
3972 if (it == circuits->end())
3973 continue;
3974 InFlightDiagnostic diag =
3975 packetFlow.emitOpError()
3976 << role << " at " << to_string(*port) << ", where a circuit flow "
3977 << role << "; a port carries either one circuit or packets";
3978 diag.attachNote(it->second.getLoc()) << "the circuit flow is here";
3979 return failure();
3980 }
3981 }
3982 return success();
3983}
3984
3985LogicalResult verifyNoSharedCircuitViaEgresses(DeviceOp device) {
3986 enum class ClaimKind { FlowDest, PacketDest, Connect, MasterSet, Via };
3987 struct Claim {
3988 Operation *op;
3989 ClaimKind kind;
3990 size_t viaIndex = 0;
3991 };
3992 std::map<PortKey, Claim> claimedEgresses;
3993
3994 auto addInterconnectClaims = [&](auto interconnect) {
3995 Value tile = interconnect.getTile();
3996 for (ConnectOp connect :
3997 interconnect.getConnections().template getOps<ConnectOp>()) {
3998 Port dest = connect.destPort();
3999 if (std::optional<PortKey> port =
4000 tryGetPortKey(tile, dest.bundle, dest.channel))
4001 claimedEgresses.try_emplace(*port, Claim{connect, ClaimKind::Connect});
4002 }
4003 for (MasterSetOp masterSet :
4004 interconnect.getConnections().template getOps<MasterSetOp>()) {
4005 Port dest = masterSet.destPort();
4006 if (std::optional<PortKey> port =
4007 tryGetPortKey(tile, dest.bundle, dest.channel))
4008 claimedEgresses.try_emplace(*port,
4009 Claim{masterSet, ClaimKind::MasterSet});
4010 }
4011 };
4012 for (SwitchboxOp switchbox : device.getOps<SwitchboxOp>())
4013 addInterconnectClaims(switchbox);
4014 for (ShimMuxOp shimMux : device.getOps<ShimMuxOp>())
4015 addInterconnectClaims(shimMux);
4016 for (FlowOp flow : device.getOps<FlowOp>()) {
4017 if (std::optional<PortKey> dest = tryGetPortKey(
4018 flow.getDest(), flow.getDestBundle(), flow.getDestChannel()))
4019 claimedEgresses.try_emplace(*dest, Claim{flow, ClaimKind::FlowDest});
4020 }
4021 for (PacketFlowOp packetFlow : device.getOps<PacketFlowOp>()) {
4022 for (PacketDestOp dest : packetFlow.getPorts().getOps<PacketDestOp>()) {
4023 if (std::optional<PortKey> port = tryGetPortKey(
4024 dest.getTile(), dest.getBundle(), dest.getChannel()))
4025 claimedEgresses.try_emplace(*port, Claim{dest, ClaimKind::PacketDest});
4026 }
4027 }
4028
4029 WalkResult result = device.walk([&](FlowOp flow) {
4030 ArrayRef<int32_t> bundles =
4031 flow.getViaEgressBundlesAttr()
4032 ? flow.getViaEgressBundlesAttr().asArrayRef()
4033 : ArrayRef<int32_t>();
4034 ArrayRef<int32_t> channels =
4035 flow.getViaEgressChannelsAttr()
4036 ? flow.getViaEgressChannelsAttr().asArrayRef()
4037 : ArrayRef<int32_t>();
4038 if (bundles.size() != flow.getVias().size() ||
4039 channels.size() != flow.getVias().size()) {
4040 return WalkResult::advance();
4041 }
4042 for (auto [index, via] : llvm::enumerate(flow.getVias())) {
4043 std::optional<PortKey> egress = tryGetPortKey(
4044 via, static_cast<WireBundle>(bundles[index]), channels[index]);
4045 if (!egress) {
4046 continue;
4047 }
4048 Claim viaClaim{flow, ClaimKind::Via, index};
4049 auto [it, inserted] = claimedEgresses.try_emplace(*egress, viaClaim);
4050 if (inserted)
4051 continue;
4052 if (index + 1 == flow.getVias().size() && it->second.op == flow &&
4053 it->second.kind == ClaimKind::FlowDest) {
4054 it->second = viaClaim;
4055 continue;
4056 }
4057 InFlightDiagnostic diag = flow.emitOpError()
4058 << "via " << index << " claims circuit egress "
4059 << to_string(*egress)
4060 << ", which another operation already claims";
4061 Diagnostic &note = diag.attachNote(it->second.op->getLoc());
4062 switch (it->second.kind) {
4063 case ClaimKind::FlowDest:
4064 note << "a circuit flow ends at the same port";
4065 break;
4066 case ClaimKind::PacketDest:
4067 note << "a packet flow ends at the same port";
4068 break;
4069 case ClaimKind::Connect:
4070 note << "a fixed connect drives the same port";
4071 break;
4072 case ClaimKind::MasterSet:
4073 note << "a fixed master set drives the same port";
4074 break;
4075 case ClaimKind::Via:
4076 note << "via " << it->second.viaIndex
4077 << " claims the same circuit egress";
4078 break;
4079 }
4080 return WalkResult::interrupt();
4081 }
4082 return WalkResult::advance();
4083 });
4084 return failure(result.wasInterrupted());
4085}
4086
4087// `mlir::detail::verifySymbolTable` compares names carried by `Symbol` ops.
4088// `aie.buffer`, `aie.external_buffer`, `aie.lock` and `aie.dma` name themselves
4089// with `sym_name` but define an SSA value, so they are not `Symbol` ops and
4090// their names escape that check. `lookupNamedOpIn` resolves them by name, so a
4091// repeated name would bind every reference to whichever op comes first.
4092LogicalResult verifyNoDuplicateNames(Operation *symbolTableOp) {
4093 if (symbolTableOp->getNumRegions() == 0 ||
4094 symbolTableOp->getRegion(0).empty()) {
4095 return success();
4096 }
4097 DenseMap<StringAttr, Operation *> nameSeen;
4098 for (Operation &op : symbolTableOp->getRegion(0).front()) {
4099 auto name = op.getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
4100 if (!name) {
4101 continue;
4102 }
4103 auto [it, inserted] = nameSeen.try_emplace(name, &op);
4104 if (inserted) {
4105 continue;
4106 }
4107 // Leave a pair of `Symbol` ops to `verifySymbolTable`, which runs after the
4108 // body and so lets the body ops report about themselves first.
4109 if (isa<SymbolOpInterface>(op) && isa<SymbolOpInterface>(it->second)) {
4110 continue;
4111 }
4112 InFlightDiagnostic diag = op.emitError() << "redefinition of symbol named '"
4113 << name.getValue() << "'";
4114 diag.attachNote(it->second->getLoc())
4115 << "see existing symbol definition here";
4116 return failure();
4117 }
4118 return success();
4119}
4120
4121} // namespace
4122
4123LogicalResult DeviceOp::verify() {
4124 // Cores and flows are the device's own ops, as the router and the CDO read
4125 // them; a walk would also visit every op of the runtime sequences.
4126 //
4127 // A compute tile has exactly one core in hardware, so at most one aie.core
4128 // may resolve to any given (col, row). Cores whose tile is a logical_tile
4129 // with unspecified coordinates are skipped here — they cannot collide until
4130 // --aie-place-tiles assigns them a position, at which point this same check
4131 // runs again on the resulting aie.tile coordinates.
4132 DenseMap<TileID, CoreOp> coreAtTile;
4133 for (CoreOp core : getOps<CoreOp>()) {
4134 auto tile =
4135 llvm::dyn_cast_or_null<TileLike>(core.getTile().getDefiningOp());
4136 if (!tile)
4137 continue;
4138 std::optional<int> col = tile.tryGetCol();
4139 std::optional<int> row = tile.tryGetRow();
4140 if (!col || !row)
4141 continue;
4142 TileID id{*col, *row};
4143 auto [it, inserted] = coreAtTile.try_emplace(id, core);
4144 if (!inserted) {
4145 InFlightDiagnostic diag =
4146 core.emitOpError()
4147 << "tile (" << *col << ", " << *row
4148 << ") already has a core; each compute tile can host only one core";
4149 diag.attachNote(it->second.getLoc()) << "the other core is here";
4150 return failure();
4151 }
4152 }
4153
4154 // A flow declared twice is always a mistake, and one that is otherwise only
4155 // noticed (if at all) as unexplained routing pressure much later on.
4156 if (failed(verifyNoDuplicateFlows(*this)))
4157 return failure();
4158 if (failed(verifyNoDuplicatePacketFlows(*this)))
4159 return failure();
4160 if (failed(verifyNoSharedCircuitPorts(*this)))
4161 return failure();
4162 if (failed(verifyNoSharedProgramChannels(*this)))
4163 return failure();
4164 if (failed(verifyNoSharedCircuitViaEgresses(*this))) {
4165 return failure();
4166 }
4167
4168 if (failed(verifyNoDuplicateNames(*this))) {
4169 return failure();
4170 }
4171
4172 return success();
4173}
4174
4175LogicalResult DeviceOp::verifyRegions() {
4176 // Region verification follows all child invariants, including the joined
4177 // verification of isolated children. Named uses may safely inspect forward
4178 // definitions here. The collection belongs only to this verification sweep.
4180 WalkResult result = getOperation()->walk<WalkOrder::PreOrder>(
4181 [&](Operation *op) -> WalkResult {
4182 if (op != getOperation() && isa<DeviceOp>(op))
4183 return WalkResult::skip();
4184 if (auto user = dyn_cast<NamedOpUserOpInterface>(op))
4185 if (failed(user.verifyNamedOpUses(names)))
4186 return WalkResult::interrupt();
4187 return WalkResult::advance();
4188 });
4189 return failure(result.wasInterrupted());
4190}
4191
4192const AIETargetModel &DeviceOp::getTargetModel() {
4193 return xilinx::AIE::getTargetModel(getDevice());
4194}
4195
4196xilinx::AIE::DeviceOp DeviceOp::getForSymbolInModule(mlir::ModuleOp module,
4197 llvm::StringRef symbol) {
4198 DeviceOp deviceOp;
4199 if (symbol.empty()) {
4200 // If no device name is given, assume 'main'
4201 symbol = "main";
4202 }
4203 Operation *maybeDeviceOp = mlir::SymbolTable::lookupSymbolIn(module, symbol);
4204 if (!maybeDeviceOp) {
4205 return nullptr;
4206 }
4207 deviceOp = llvm::dyn_cast<DeviceOp>(maybeDeviceOp);
4208 return deviceOp;
4209}
4210
4211xilinx::AIE::DeviceOp
4212DeviceOp::getForSymbolInModuleOrError(mlir::ModuleOp module,
4213 llvm::StringRef symbol) {
4214 DeviceOp deviceOp = getForSymbolInModule(module, symbol);
4215 if (!deviceOp) {
4216 if (!symbol.empty()) {
4217 module.emitError("No such device: ") << symbol;
4218 } else {
4219 module.emitError("No 'main' device in module");
4220 }
4221 }
4222 return deviceOp;
4223}
4224
4225//===----------------------------------------------------------------------===//
4226// TileElement
4227//===----------------------------------------------------------------------===//
4228
4229TileOp TileElement::tryGetTileOp() {
4230 auto element = cast<TileElement>(this->getOperation());
4231 return dyn_cast_or_null<TileOp>(element.getTile().getDefiningOp());
4232}
4233
4234TileOp TileElement::getTileOp() {
4235 if (auto tileOp = tryGetTileOp())
4236 return tileOp;
4237 llvm::report_fatal_error("Calling getTileOp requires TileOp.");
4238}
4239
4240//===----------------------------------------------------------------------===//
4241// LogicalTileOp
4242//===----------------------------------------------------------------------===//
4243
4244LogicalResult LogicalTileOp::verify() {
4245 if (failed(verifyAssignedPacket(
4246 *this, (*this)->getAttrOfType<PacketInfoAttr>("controller_id"),
4247 "controller_id")))
4248 return failure();
4249 const auto &targetModel = getTargetModel(*this);
4250 int columns = targetModel.columns();
4251 int rows = targetModel.rows();
4252
4253 // Only verify col/row bounds if they are specified
4254 if (auto col = getCol()) {
4255 if (*col >= columns)
4256 return emitOpError("column index (")
4257 << *col
4258 << ") must be less than the number of columns in the device ("
4259 << columns << ")";
4260 }
4261 if (auto row = getRow()) {
4262 if (*row >= rows)
4263 return emitOpError("row index (")
4264 << *row << ") must be less than the number of rows in the device ("
4265 << rows << ")";
4266 }
4267
4268 // Check that the specified tile type exists on the target device
4269 AIETileType tileType = getTileType();
4270 bool tileTypeExists = false;
4271 for (int col = 0; col < columns && !tileTypeExists; col++) {
4272 for (int row = 0; row < rows && !tileTypeExists; row++) {
4273 if (targetModel.getTileType(col, row) == tileType)
4274 tileTypeExists = true;
4275 }
4276 }
4277 if (!tileTypeExists) {
4278 return emitOpError("tile type '")
4279 << stringifyAIETileType(tileType)
4280 << "' does not exist on the target device";
4281 }
4282
4283 // Check logical tile type matches coordinates on device
4284 // Only validate when both col and row are specified
4285 if (auto col = tryGetCol()) {
4286 if (auto row = tryGetRow()) {
4287 if (targetModel.getTileType(*col, *row) != tileType) {
4288 return emitOpError("declared logical tile type does not match "
4289 "the tile type at coordinates (")
4290 << *col << ", " << *row << ")";
4291 }
4292 }
4293 }
4294
4295 return success();
4296}
4297
4298TileID LogicalTileOp::getCanonicalTileID() {
4299 const auto &targetModel = getTargetModel(*this);
4300
4301 // If col and row are both specified, use them directly
4302 std::optional<int32_t> col = getCol();
4303 std::optional<int32_t> row = getRow();
4304 if (col.has_value() && row.has_value())
4305 return {*col, *row};
4306
4307 // Otherwise, find a representative tile of the given type
4308 AIETileType tileType = getTileType();
4309 for (int col = 0; col < targetModel.columns(); col++) {
4310 for (int row = 0; row < targetModel.rows(); row++) {
4311 if (targetModel.getTileType(col, row) == tileType) {
4312 return {col, row};
4313 }
4314 }
4315 }
4316 llvm_unreachable("No tile of matching tile type found in AIE device");
4317}
4318
4319size_t LogicalTileOp::getNumSourceConnections(WireBundle bundle) {
4320 const auto &targetModel = getTargetModel(*this);
4321 TileID tile = getCanonicalTileID();
4322
4323 if (bundle == WireBundle::Core || bundle == WireBundle::DMA) {
4324 // Note dest is correct here, since direction is reversed.
4325 if (targetModel.hasShimMux(tile.col, tile.row))
4326 return targetModel.getNumDestShimMuxConnections(tile.col, tile.row,
4327 bundle);
4328 return targetModel.getNumDestSwitchboxConnections(tile.col, tile.row,
4329 bundle);
4330 }
4331 return 0;
4332}
4333
4334size_t LogicalTileOp::getNumDestConnections(WireBundle bundle) {
4335 const auto &targetModel = getTargetModel(*this);
4336 TileID tile = getCanonicalTileID();
4337
4338 if (bundle == WireBundle::Core || bundle == WireBundle::DMA) {
4339 // Note source is correct here, since direction is reversed.
4340 if (targetModel.hasShimMux(tile.col, tile.row))
4341 return targetModel.getNumSourceShimMuxConnections(tile.col, tile.row,
4342 bundle);
4343 return targetModel.getNumSourceSwitchboxConnections(tile.col, tile.row,
4344 bundle);
4345 }
4346 return 0;
4347}
4348
4349std::optional<int> LogicalTileOp::tryGetCol() {
4350 if (auto col = getCol())
4351 return col;
4352 return std::nullopt;
4353}
4354
4355std::optional<int> LogicalTileOp::tryGetRow() {
4356 if (auto row = getRow())
4357 return row;
4358 return std::nullopt;
4359}
4360
4361//===----------------------------------------------------------------------===//
4362// Custom Printer and Parser for LogicalTileOp
4363//===----------------------------------------------------------------------===//
4364
4365ParseResult LogicalTileOp::parse(OpAsmParser &parser, OperationState &result) {
4366 AIETileType tileType;
4367 if (parser.parseLess())
4368 return failure();
4369
4370 StringRef tileTypeStr;
4371 if (parser.parseKeyword(&tileTypeStr))
4372 return failure();
4373
4374 auto tileTypeOpt = symbolizeAIETileType(tileTypeStr);
4375 if (!tileTypeOpt)
4376 return parser.emitError(parser.getCurrentLocation(),
4377 "unknown logical tile type: ")
4378 << tileTypeStr;
4379 tileType = *tileTypeOpt;
4380
4381 if (parser.parseGreater())
4382 return failure();
4383
4384 if (parser.parseLParen())
4385 return failure();
4386
4387 std::optional<int32_t> col;
4388 if (succeeded(parser.parseOptionalQuestion())) {
4389 // col is unspecified
4390 } else {
4391 int32_t colVal;
4392 if (parser.parseInteger(colVal))
4393 return failure();
4394 col = colVal;
4395 }
4396
4397 if (parser.parseComma())
4398 return failure();
4399
4400 std::optional<int32_t> row;
4401 if (succeeded(parser.parseOptionalQuestion())) {
4402 // row is unspecified
4403 } else {
4404 int32_t rowVal;
4405 if (parser.parseInteger(rowVal))
4406 return failure();
4407 row = rowVal;
4408 }
4409
4410 if (parser.parseRParen())
4411 return failure();
4412
4413 // Parse optional attributes
4414 if (parser.parseOptionalAttrDict(result.attributes))
4415 return failure();
4416
4417 // Add the parsed attributes to the result
4418 result.getOrAddProperties<LogicalTileOp::Properties>().tile_type =
4419 AIETileTypeAttr::get(parser.getContext(), tileType);
4420 if (col)
4421 result.getOrAddProperties<LogicalTileOp::Properties>().col =
4422 parser.getBuilder().getI32IntegerAttr(*col);
4423 if (row)
4424 result.getOrAddProperties<LogicalTileOp::Properties>().row =
4425 parser.getBuilder().getI32IntegerAttr(*row);
4426
4427 // Add result type (index)
4428 result.addTypes(parser.getBuilder().getIndexType());
4429
4430 return success();
4431}
4432
4433void LogicalTileOp::print(OpAsmPrinter &printer) {
4434 printer << "<" << stringifyAIETileType(getTileType()) << ">";
4435
4436 printer << "(";
4437 if (auto col = getCol())
4438 printer << *col;
4439 else
4440 printer << "?";
4441 printer << ", ";
4442 if (auto row = getRow())
4443 printer << *row;
4444 else
4445 printer << "?";
4446 printer << ")";
4447
4448 SmallVector<StringRef, 3> elidedAttrs = {"tile_type", "col", "row"};
4449 printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
4450}
4451
4452//===----------------------------------------------------------------------===//
4453// TileOp
4454//===----------------------------------------------------------------------===//
4455
4456LogicalResult TileOp::verify() {
4457 if (failed(verifyAssignedPacket(
4458 *this, (*this)->getAttrOfType<PacketInfoAttr>("controller_id"),
4459 "controller_id")))
4460 return failure();
4461 const auto &targetModel = getTargetModel(*this);
4462 int columns = targetModel.columns();
4463 int rows = targetModel.rows();
4464 if (colIndex() >= columns)
4465 return emitOpError("column index (")
4466 << colIndex()
4467 << ") must be less than the number of columns in the device ("
4468 << columns << ")";
4469 if (rowIndex() >= rows)
4470 return emitOpError("row index (")
4471 << rowIndex()
4472 << ") must be less than the number of rows in the device (" << rows
4473 << ")";
4474
4475 auto users = getResult().getUsers();
4476 bool found = false;
4477 for (auto *user : users) {
4478 if (llvm::isa<SwitchboxOp>(*user)) {
4479 if (found)
4480 return emitOpError("can only have one switchbox");
4481 found = true;
4482 }
4483 }
4484
4485 return success();
4486}
4487
4488size_t TileOp::getNumSourceConnections(WireBundle bundle) {
4489 const auto &targetModel = getTargetModel(*this);
4490 if (bundle == WireBundle::Core || bundle == WireBundle::DMA)
4491 // Note dest is correct here, since direction is reversed.
4492 {
4493 // Note dest is correct here, since direction is reversed.
4494 if (targetModel.hasShimMux(getCol(), getRow()))
4495 return targetModel.getNumDestShimMuxConnections(getCol(), getRow(),
4496 bundle);
4497 return targetModel.getNumDestSwitchboxConnections(getCol(), getRow(),
4498 bundle);
4499 }
4500 return 0;
4501}
4502
4503size_t TileOp::getNumDestConnections(WireBundle bundle) {
4504 const auto &targetModel = getTargetModel(*this);
4505 if (bundle == WireBundle::Core || bundle == WireBundle::DMA)
4506 // Note source is correct here, since direction is reversed.
4507 {
4508 // Note source is correct here, since direction is reversed.
4509 if (targetModel.hasShimMux(getCol(), getRow()))
4510 return targetModel.getNumSourceShimMuxConnections(getCol(), getRow(),
4511 bundle);
4512 return targetModel.getNumSourceSwitchboxConnections(getCol(), getRow(),
4513 bundle);
4514 }
4515 return 0;
4516}
4517
4518std::optional<int> TileOp::tryGetCol() { return getCol(); }
4519std::optional<int> TileOp::tryGetRow() { return getRow(); }
4520
4521AIETileType TileOp::getTileType() {
4522 const auto &targetModel = getTargetModel(*this);
4523 return targetModel.getTileType(getCol(), getRow());
4524}
4525
4526static bool isLegalTileConnection(TileOp tile,
4527 const AIETargetModel &targetModel,
4528 MasterSetOp masterOp, PacketRulesOp slaveOp) {
4529 auto srcBundle = slaveOp.sourcePort().bundle;
4530 auto srcChan = slaveOp.sourcePort().channel;
4531 auto dstBundle = masterOp.destPort().bundle;
4532 auto dstChan = masterOp.destPort().channel;
4533 return targetModel.isLegalTileConnection(
4534 tile.colIndex(), tile.rowIndex(), srcBundle, srcChan, dstBundle, dstChan);
4535}
4536
4537static bool isLegalTileConnection(TileOp tile,
4538 const AIETargetModel &targetModel,
4539 ConnectOp connectOp) {
4540 auto srcBundle = connectOp.getSourceBundle();
4541 auto srcChan = connectOp.getSourceChannel();
4542 auto dstBundle = connectOp.getDestBundle();
4543 auto dstChan = connectOp.getDestChannel();
4544 return targetModel.isLegalTileConnection(
4545 tile.colIndex(), tile.rowIndex(), srcBundle, srcChan, dstBundle, dstChan);
4546}
4547
4548TileOp TileOp::getOrCreate(mlir::OpBuilder builder, DeviceOp device, int col,
4549 int row, std::optional<mlir::Location> loc) {
4550 TileOp tile = nullptr;
4551 // Find matching predefined tile at device top level, ...
4552 for (auto t : device.getOps<AIE::TileOp>()) {
4553 if (t.getRow() == row && t.getCol() == col) {
4554 tile = t;
4555 break;
4556 }
4557 }
4558 // ... or if undefined, create a new tile op
4559 if (!tile) {
4560 OpBuilder::InsertionGuard guard(builder);
4561 mlir::Block &device_start_block = *device.getBodyRegion().begin();
4562 builder.setInsertionPointToStart(&device_start_block);
4563 tile = TileOp::create(builder, loc.value_or(device.getLoc()),
4564 builder.getIndexType(), col, row);
4565 }
4566 return tile;
4567}
4568
4569//===----------------------------------------------------------------------===//
4570// ShimMuxOp
4571//===----------------------------------------------------------------------===//
4572
4573LogicalResult ShimMuxOp::verify() {
4574 // The port/connection checks below are keyed off the target model for a
4575 // placed tile. Before --aie-place-tiles the tile is still an
4576 // aie.logical_tile, so defer those checks to the post-placement re-verify --
4577 // mirroring SwitchboxOp::verify and the UsesAreAccessible trait.
4578 if (!isa<TileOp>(getTile().getDefiningOp()))
4579 return success();
4580
4581 TileOp tile = getTileOp();
4582 if (!getTargetModel(*this).hasShimMux(tile.getCol(), tile.getRow()))
4583 return emitOpError("tile (")
4584 << tile.getCol() << ", " << tile.getRow()
4585 << ") has no shim mux: its DMA connects to the switchbox "
4586 "directly";
4587
4588 Region &body = getConnections();
4589 DenseSet<Port> destset;
4590 if (body.empty())
4591 return emitOpError("should have non-empty body");
4592
4593 for (auto &ops : body.front()) {
4594 if (auto connectOp = dyn_cast<ConnectOp>(ops)) {
4595 Port dest = {connectOp.getDestBundle(), connectOp.destIndex()};
4596 if (destset.count(dest))
4597 return connectOp.emitOpError("targets same destination ")
4598 << stringifyWireBundle(dest.bundle) << ": " << dest.channel
4599 << " as another connect operation";
4600 destset.insert(dest);
4601 } else if (isa<EndOp>(ops)) {
4602 // continue;
4603 } else {
4604 return ops.emitOpError("cannot be contained in a Switchbox op");
4605 }
4606 }
4607 return success();
4608}
4609
4610size_t ShimMuxOp::getNumSourceConnections(WireBundle bundle) {
4611 auto tile = getTileOp();
4612 const auto &targetModel = getTargetModel(*this);
4613 return targetModel.getNumSourceShimMuxConnections(tile.getCol(),
4614 tile.getRow(), bundle);
4615}
4616
4617size_t ShimMuxOp::getNumDestConnections(WireBundle bundle) {
4618 auto tile = getTileOp();
4619 const auto &targetModel = getTargetModel(*this);
4620 return targetModel.getNumDestShimMuxConnections(tile.getCol(), tile.getRow(),
4621 bundle);
4622}
4623
4624//===----------------------------------------------------------------------===//
4625// ShimDMAOp
4626//===----------------------------------------------------------------------===//
4627
4628LogicalResult ShimDMAOp::verify() {
4630 .failed())
4631 return failure();
4632 return success();
4633}
4634
4635TileOp ShimDMAOp::getTileOp() {
4636 return cast<TileElement>(this->getOperation()).getTileOp();
4637}
4638
4639LogicalResult PacketRulesOp::verify() {
4640 if (Region &body = getRules(); body.empty())
4641 return emitOpError("should have non-empty body");
4642 return success();
4643}
4644
4645LogicalResult MasterSetOp::verify() {
4646 int arbiter = -1;
4647 for (auto val : getAmsels()) {
4648 auto amsel = dyn_cast_if_present<AMSelOp>(val.getDefiningOp());
4649 if (!amsel)
4650 return emitOpError("amsel operand must be produced by an 'aie.amsel' op");
4651 if (arbiter != -1 && arbiter != amsel.arbiterIndex())
4652 return emitOpError("a master port can only be tied to one arbiter");
4653 arbiter = amsel.arbiterIndex();
4654 }
4655 return success();
4656}
4657
4658bool MasterSetOp::keepsPktHeader() {
4659 return AIE::keepsPktHeader(
4660 (*this)->getParentOfType<SwitchboxOp>().getTileOp().getTileID(),
4661 destPort(), getKeepPktHeader());
4662}
4663
4665 std::optional<bool> keep) {
4666 if (keep)
4667 return *keep;
4668 return master.bundle != WireBundle::DMA &&
4669 (tile.row != 0 || master.bundle != WireBundle::South);
4670}
4671
4672// A Core or DMA port a flow starts or ends at on a placed tile must exist
4673// there, as must a NOC or PLIO port on a shim without a shim mux. The placer
4674// checks logical tiles' channel budgets.
4675static LogicalResult verifyFlowEndpoint(Operation *op, Value tile, Port port,
4676 bool isSource) {
4677 if (!isa_and_nonnull<TileLike>(tile.getDefiningOp()))
4678 return op->emitOpError(
4679 "tile operand is not an aie.tile or aie.logical_tile");
4680 bool shimPort =
4681 port.bundle == WireBundle::NOC || port.bundle == WireBundle::PLIO;
4682 if (port.bundle != WireBundle::Core && port.bundle != WireBundle::DMA &&
4683 !shimPort)
4684 return success();
4685 auto tileOp = dyn_cast_or_null<TileOp>(tile.getDefiningOp());
4686 if (!tileOp)
4687 return success();
4688 size_t channels;
4689 if (shimPort) {
4690 const auto &targetModel = getTargetModel(op);
4691 int col = tileOp.getCol(), row = tileOp.getRow();
4692 if (!targetModel.isShimNOCorPLTile(col, row) ||
4693 targetModel.hasShimMux(col, row))
4694 return success();
4695 channels =
4696 isSource
4697 ? targetModel.getNumSourceSwitchboxConnections(col, row,
4698 port.bundle)
4699 : targetModel.getNumDestSwitchboxConnections(col, row, port.bundle);
4700 } else {
4701 channels = isSource ? tileOp.getNumDestConnections(port.bundle)
4702 : tileOp.getNumSourceConnections(port.bundle);
4703 }
4704 if (static_cast<size_t>(port.channel) < channels)
4705 return success();
4706 return op->emitOpError() << (isSource ? "source " : "destination ")
4707 << stringifyWireBundle(port.bundle) << ":"
4708 << port.channel << " does not exist: tile ("
4709 << tileOp.getCol() << ", " << tileOp.getRow()
4710 << ") has " << channels << " "
4711 << stringifyWireBundle(port.bundle) << " port"
4712 << (channels == 1 ? "" : "s")
4713 << (isSource ? " into" : " out of")
4714 << " its stream switch";
4715}
4716
4717static LogicalResult verifyFlowVias(Operation *op, OperandRange vias,
4718 DenseI32ArrayAttr ingressBundles,
4719 DenseI32ArrayAttr ingressChannels,
4720 DenseI32ArrayAttr egressBundles,
4721 DenseI32ArrayAttr egressChannels) {
4722 size_t numVias = vias.size();
4723 DenseI32ArrayAttr arrays[] = {ingressBundles, ingressChannels, egressBundles,
4724 egressChannels};
4725 for (DenseI32ArrayAttr array : arrays) {
4726 size_t size = array ? array.size() : 0;
4727 if (size != numVias) {
4728 return op->emitOpError("has ")
4729 << numVias << " via tile(s) but a via port array of size " << size;
4730 }
4731 }
4732 if (numVias == 0) {
4733 return success();
4734 }
4735
4736 for (auto [index, via] : llvm::enumerate(vias)) {
4737 if (!isa_and_nonnull<TileLike>(via.getDefiningOp())) {
4738 return op->emitOpError("has via operand at index ")
4739 << index << " that is not defined by a tile-like operation";
4740 }
4741 }
4742
4743 auto verifyBundles = [&](DenseI32ArrayAttr bundles,
4744 StringRef direction) -> LogicalResult {
4745 for (auto [index, bundle] : llvm::enumerate(bundles.asArrayRef())) {
4746 if (bundle < 0 ||
4747 bundle > static_cast<int32_t>(getMaxEnumValForWireBundle())) {
4748 return op->emitOpError("has invalid via ")
4749 << direction << " bundle " << bundle << " at index " << index;
4750 }
4751 }
4752 return success();
4753 };
4754 auto verifyChannels = [&](DenseI32ArrayAttr channels,
4755 StringRef direction) -> LogicalResult {
4756 for (auto [index, channel] : llvm::enumerate(channels.asArrayRef())) {
4757 if (channel < 0) {
4758 return op->emitOpError("has negative via ")
4759 << direction << " channel " << channel << " at index " << index;
4760 }
4761 }
4762 return success();
4763 };
4764 if (failed(verifyBundles(ingressBundles, "ingress")) ||
4765 failed(verifyChannels(ingressChannels, "ingress")) ||
4766 failed(verifyBundles(egressBundles, "egress")) ||
4767 failed(verifyChannels(egressChannels, "egress"))) {
4768 return failure();
4769 }
4770 return success();
4771}
4772
4773LogicalResult FlowOp::verify() {
4774 if (failed(verifyFlowEndpoint(*this, getSource(),
4775 {getSourceBundle(), sourceIndex()}, true)))
4776 return failure();
4777 if (failed(verifyFlowEndpoint(*this, getDest(),
4778 {getDestBundle(), destIndex()}, false))) {
4779 return failure();
4780 }
4781
4782 return verifyFlowVias(*this, getVias(), getViaIngressBundlesAttr(),
4783 getViaIngressChannelsAttr(), getViaEgressBundlesAttr(),
4784 getViaEgressChannelsAttr());
4785}
4786
4787LogicalResult PacketSourceOp::verify() {
4788 return verifyFlowEndpoint(*this, getTile(), port(), true);
4789}
4790
4791LogicalResult PacketDestOp::verify() {
4792 return verifyFlowEndpoint(*this, getTile(), port(), false);
4793}
4794
4795LogicalResult PacketFlowOp::verify() {
4796 Region &body = getPorts();
4797 if (body.empty())
4798 return emitOpError("should have non-empty body");
4799
4800 int numSources = 0, numDests = 0;
4801 for (auto &ops : body.front()) {
4802 if (!isa<PacketSourceOp, PacketDestOp, EndOp>(ops))
4803 return ops.emitOpError("cannot be contained in a PacketFlow op");
4804 if (isa<PacketSourceOp>(ops))
4805 ++numSources;
4806 if (isa<PacketDestOp>(ops))
4807 ++numDests;
4808 }
4809
4810 if (numSources < 1)
4811 return emitOpError("must have at least one aie.packet_source");
4812 if (numDests < 1)
4813 return emitOpError("must have at least one aie.packet_dest");
4814 if (!getVias().empty() && numSources != 1) {
4815 return emitOpError(
4816 "with via waypoints must have exactly one aie.packet_source");
4817 }
4818 if (!getVias().empty() && numDests != 1) {
4819 return emitOpError(
4820 "with via waypoints must have exactly one aie.packet_dest");
4821 }
4822
4823 uint8_t id = getID();
4824 if (uint32_t maxId = getTargetModel(getOperation()).getMaxPacketId();
4825 id > maxId)
4826 return emitOpError("packet id ")
4827 << static_cast<int>(id) << " exceeds the maximum of " << maxId;
4828
4829 // A slave port accepts a packet when `incoming & mask == ID`, so a bit set
4830 // in ID and clear in the mask rejects every packet.
4831 if (std::optional<uint8_t> mask = getMask()) {
4832 if ((id & *mask) != id) {
4833 return emitOpError("has ID 0x")
4834 << llvm::utohexstr(id) << " outside mask 0x"
4835 << llvm::utohexstr(*mask) << ", which no packet can match";
4836 }
4837 }
4838
4839 return verifyFlowVias(*this, getVias(), getViaIngressBundlesAttr(),
4840 getViaIngressChannelsAttr(), getViaEgressBundlesAttr(),
4841 getViaEgressChannelsAttr());
4842}
4843
4844//===----------------------------------------------------------------------===//
4845// CoreOp
4846//===----------------------------------------------------------------------===//
4847
4848/// The channels a core's own tile has in `direction`.
4849static uint32_t channelsOfOwnTile(TileOp tile, DMAChannelDir direction,
4850 const AIETargetModel &targetModel) {
4851 return targetModel.getNumDMAChannels(tile.getCol(), tile.getRow(), direction);
4852}
4853
4854LogicalResult DmaPushQueueOp::verify() {
4855 if (getOutOfOrder() && getDirection() != DMAChannelDir::S2MM)
4856 return emitOpError("out_of_order is only supported on S2MM channels");
4857 if (getBdId().has_value() == getBdTag().has_value())
4858 return emitOpError("names the descriptor it pushes either by bd_id or, "
4859 "before aie-assign-bd-ids runs, by bd_tag");
4860 auto core = (*this)->getParentOfType<CoreOp>();
4861 const AIETargetModel &targetModel = getTargetModel(*this);
4862 if (auto tile = core.getTile().getDefiningOp<TileOp>()) {
4863 uint32_t channels = channelsOfOwnTile(tile, getDirection(), targetModel);
4864 if (getChannel() >= static_cast<int32_t>(channels))
4865 return emitOpError("pushes onto ")
4866 << stringifyDMAChannelDir(getDirection()) << " channel "
4867 << getChannel() << ", but tile (" << tile.getCol() << ", "
4868 << tile.getRow() << ") has " << channels;
4869 }
4870 uint32_t maxRepeat = targetModel.getMaxRepeatCount();
4871 if (getRepeatCount() < 0 ||
4872 static_cast<uint32_t>(getRepeatCount()) > maxRepeat)
4873 return emitOpError("repeat_count must be in [0, ") << maxRepeat << "]";
4874 return success();
4875}
4876
4877LogicalResult DmaPollForQueueSpaceOp::verify() {
4878 auto core = (*this)->getParentOfType<CoreOp>();
4879 const AIETargetModel &targetModel = getTargetModel(*this);
4880 if (auto tile = core.getTile().getDefiningOp<TileOp>()) {
4881 uint32_t channels = channelsOfOwnTile(tile, getDirection(), targetModel);
4882 if (getChannel() >= static_cast<int32_t>(channels))
4883 return emitOpError("waits on ")
4884 << stringifyDMAChannelDir(getDirection()) << " channel "
4885 << getChannel() << ", but tile (" << tile.getCol() << ", "
4886 << tile.getRow() << ") has " << channels;
4887 }
4888 if (targetModel.getDmaTaskQueueDepth() == 0)
4889 return emitOpError("waits on a task queue, which this device has none of");
4890 return success();
4891}
4892
4893LogicalResult CoreOp::verify() {
4894 if (getBody().empty())
4895 return emitOpError("should have non-empty body");
4896 if (getElfFile()) {
4897 // If an ELF file is specified, no MLIR body is allowed (to remove
4898 // ambiguity); the ELF file will fully dictate what runs on the
4899 // core and any MLIR would be ignored.
4900 if (!isEmpty()) {
4901 return emitOpError(
4902 "When `elf_file` attribute is specified, core body must be empty "
4903 "(consist of exactly one `aie.end` op).");
4904 }
4905 }
4906 if (getLinkWith() && getLinkFiles())
4907 return emitOpError(
4908 "cannot specify both 'link_with' (deprecated) and 'link_files' "
4909 "on the same core; run aie-assign-core-link-files to migrate");
4910 if (getLinkWith() && getLinkMergeFiles())
4911 return emitOpError(
4912 "cannot specify both 'link_with' (deprecated) and 'link_merge_files' "
4913 "on the same core; run aie-assign-core-link-files to migrate");
4914 // An artifact is either merged into the core's LLVM module or handed to the
4915 // final link, never both: doing both would define its symbols twice.
4916 if (auto linkFiles = getLinkFiles())
4917 if (auto mergeFiles = getLinkMergeFiles()) {
4918 llvm::SmallSet<StringRef, 8> linked;
4919 for (auto f : linkFiles->getAsRange<StringAttr>())
4920 linked.insert(f.getValue());
4921 for (auto f : mergeFiles->getAsRange<StringAttr>())
4922 if (linked.count(f.getValue()))
4923 return emitOpError("artifact '")
4924 << f.getValue()
4925 << "' appears in both 'link_files' and 'link_merge_files'; an "
4926 "artifact must be either merged or linked, not both";
4927 }
4928 // The core's own sections live in a `core_data` aie.buffer, so the buffer
4929 // verifier covers their placement. Size and measured alignment belong here.
4930 if (auto measured = getMeasuredDataSize())
4931 if (auto declared = getDataSize(); declared && *declared < *measured)
4932 return emitOpError("data_size ")
4933 << *declared << " is smaller than the " << *measured
4934 << " bytes this core's linked sections occupy";
4935 // Where the stack sits. A pin the allocator could never honor is a user
4936 // constraint, so it is rejected here rather than at placement.
4937 const auto &targetModel = getTargetModel(*this);
4938 if (auto summary = getLockAcquiresAttr()) {
4939 for (LockAcquireAttr acquire : summary.getAcquires()) {
4940 int32_t column = acquire.getColumn();
4941 int32_t row = acquire.getRow();
4942 if (column >= targetModel.columns() || row >= targetModel.rows())
4943 return emitOpError(
4944 "lock_acquires references a tile outside the device: ")
4945 << "(" << column << ", " << row << ")";
4946 if (static_cast<uint32_t>(acquire.getLockId()) >=
4947 targetModel.getNumLocks(column, row))
4948 return emitOpError("lock_acquires references an invalid lock ID ")
4949 << acquire.getLockId() << " on tile (" << column << ", " << row
4950 << ")";
4951 if (acquire.getAction() == LockAction::AcquireGreaterEqual &&
4952 !targetModel.hasProperty(AIETargetModel::UsesSemaphoreLocks))
4953 return emitOpError(
4954 "lock_acquires uses AcquireGreaterEqual on a target without "
4955 "semaphore locks");
4956 }
4957 }
4958 int64_t localMem = targetModel.getLocalMemorySize();
4959 auto validAlignment = [localMem](int64_t alignment) {
4960 return alignment > 0 && alignment <= localMem &&
4961 llvm::isPowerOf2_64(alignment);
4962 };
4963 if (auto alignment = getMeasuredDataAlignment();
4964 alignment && !validAlignment(*alignment))
4965 return emitOpError("measured_data_alignment must be a power of two between "
4966 "1 and ")
4967 << localMem << " bytes";
4968 if (auto alignments = getMeasuredBankAlignments())
4969 if (!llvm::all_of(*alignments, validAlignment))
4970 return emitOpError("measured_bank_alignments must contain only powers of "
4971 "two between 1 and ")
4972 << localMem << " bytes";
4973 MemoryRun stackRun = getStackRun();
4974 auto tile = dyn_cast_if_present<TileOp>(getTile().getDefiningOp());
4975 int64_t numBanks =
4976 tile ? targetModel.getNumBanks(tile.getCol(), tile.getRow()) : 0;
4977 int64_t bankSize =
4978 numBanks > 0 ? targetModel.getLocalMemorySize() / numBanks : 0;
4979 if (auto bank = getStackBank()) {
4980 if (tile && *bank >= numBanks)
4981 return emitOpError("stack_bank ")
4982 << *bank << " does not exist; this tile has " << numBanks
4983 << " banks";
4984 // Bank-specific stack accesses must stay inside the selected bank.
4985 if (bankSize > 0 && stackRun.size > bankSize)
4986 return emitOpError("stack_bank pins a ")
4987 << stackRun.size << "-byte stack to bank " << *bank
4988 << ", which holds " << bankSize
4989 << " bytes; omit stack_bank and stack_address for legacy "
4990 "placement";
4991 if (getStackAddress() && bankSize > 0 && stackRun.start / bankSize != *bank)
4992 return emitOpError("stack_address 0x")
4993 << llvm::utohexstr(stackRun.start) << " lies in bank "
4994 << stackRun.start / bankSize << ", but stack_bank requests bank "
4995 << *bank;
4996 if (getStackAddress() && bankSize > 0 &&
4997 stackRun.end() > (*bank + 1) * bankSize)
4998 return emitOpError("a ")
4999 << stackRun.size << "-byte stack at 0x"
5000 << llvm::utohexstr(stackRun.start) << " runs past stack_bank "
5001 << *bank << " (ending at 0x"
5002 << llvm::utohexstr((*bank + 1) * bankSize) << ")";
5003 }
5004 // Checked last so they do not pre-empt the diagnostics above on an op with
5005 // more than one defect. Size and placement are separate faults: a stack can
5006 // fit the tile yet be placed so it runs off the end.
5007 if (stackRun.size >= localMem)
5008 return emitOpError(getStackSize() ? "stack_size "
5009 : "measured stack requirement ")
5010 << stackRun.size
5011 << " leaves no local memory for this tile's buffers (" << localMem
5012 << " bytes total)";
5013 if (stackRun.end() > localMem)
5014 return emitOpError("a ") << stackRun.size << "-byte stack at 0x"
5015 << llvm::utohexstr(stackRun.start)
5016 << " runs past this tile's local memory ("
5017 << localMem << " bytes total)";
5018 if (getStackAddress() &&
5019 stackRun.start % targetModel.getCoreStackAlignment() != 0)
5020 return emitOpError("stack_address must be aligned to ")
5021 << targetModel.getCoreStackAlignment()
5022 << " bytes for this target's stack ABI";
5023 return success();
5024}
5025
5026bool CoreOp::isEmpty() {
5027 Region &body = getBody();
5028 // Return iff. core body contains exactly one block with exactly one AIE.EndOp
5029 return (body.hasOneBlock() && body.front().getOperations().size() == 1 &&
5030 llvm::isa<AIE::EndOp>(body.front().front()));
5031}
5032
5033TileOp CoreOp::getTileOp() {
5034 return cast<TileElement>(this->getOperation()).getTileOp();
5035}
5036
5037uint32_t CoreOp::getEffectiveStackSize() {
5038 if (auto declared = getStackSize())
5039 return *declared;
5040 const auto &targetModel = getTargetModel(*this);
5041 uint32_t fallback = targetModel.getDefaultCoreStackSize();
5042 if (auto measured = getMeasuredStackSize())
5043 return std::max<uint32_t>(
5044 fallback,
5045 llvm::alignTo(*measured, targetModel.getCoreStackAlignment()));
5046 return fallback;
5047}
5048
5049MemoryRun CoreOp::getStackRun() {
5050 return {getStackAddress().value_or(0), getEffectiveStackSize()};
5051}
5052
5053int64_t CoreOp::getSectionAlignment(std::optional<int32_t> bank) {
5054 if (!bank)
5055 return getMeasuredDataAlignment().value_or(1);
5056 auto alignments = getMeasuredBankAlignments();
5057 if (alignments && *bank >= 0 &&
5058 static_cast<size_t>(*bank) < alignments->size())
5059 return std::max<int64_t>((*alignments)[*bank], 1);
5060 return 1;
5061}
5062
5063SmallVector<BufferOp> CoreOp::getSectionReservationBuffers(
5064 ArrayRef<CoreSectionReservation> reservations) {
5065 using Kind = CoreSectionReservation::Kind;
5066 SmallVector<BufferOp> onTile;
5067 (*this)->getParentOp()->walk([&](BufferOp buffer) {
5068 if (buffer.getTile() == getTile())
5069 onTile.push_back(buffer);
5070 });
5071 SmallVector<BufferOp> holders;
5072 DenseSet<Operation *> claimed;
5073 for (const CoreSectionReservation &held : reservations) {
5074 auto holds = [&](BufferOp buffer) {
5075 if (claimed.contains(buffer) || buffer.getAllocationSize() != held.bytes)
5076 return false;
5077 if (held.kind == Kind::DataRegion)
5078 return static_cast<bool>(buffer.getCoreData());
5079 return buffer.getBankReserved() &&
5080 buffer.getAligned() == held.aligned() &&
5081 (held.kind == Kind::Bank ? buffer.getMemBank() == held.at
5082 : buffer.getAddress() == held.at);
5083 };
5084 auto *it = llvm::find_if(onTile, holds);
5085 holders.push_back(it == onTile.end() ? BufferOp() : *it);
5086 if (it != onTile.end())
5087 claimed.insert(*it);
5088 }
5089 return holders;
5090}
5091
5092SmallVector<CoreSectionReservation> CoreOp::getSectionReservations() {
5093 using Kind = CoreSectionReservation::Kind;
5094 SmallVector<CoreSectionReservation> held;
5095 // A declared data_size wins over the measurement: it is a reservation the
5096 // design asked for, and may deliberately exceed what this build measures.
5097 int64_t data = getDataSize().value_or(getMeasuredDataSize().value_or(0));
5098 if (data > 0)
5099 held.push_back(
5100 {Kind::DataRegion, data, 0, getSectionAlignment(std::nullopt)});
5101 if (auto sizes = getMeasuredBankSizes())
5102 for (auto [index, size] : llvm::enumerate(*sizes)) {
5103 auto bank = static_cast<int32_t>(index);
5104 if (size > 0)
5105 held.push_back({Kind::Bank, size, bank, getSectionAlignment(bank)});
5106 }
5107 if (auto ranges = getMeasuredDataRanges())
5108 for (size_t i = 0; i + 1 < ranges->size(); i += 2)
5109 if ((*ranges)[i + 1] > 0)
5110 held.push_back({Kind::Prebaked, (*ranges)[i + 1], (*ranges)[i]});
5111 return held;
5112}
5113
5114//===----------------------------------------------------------------------===//
5115// BufferOp
5116//===----------------------------------------------------------------------===//
5117
5118int64_t BufferOp::getSectionAlignment() {
5119 if (!getCoreData() && !getBankReserved())
5120 return 1;
5121 for (Operation *user : getTile().getUsers())
5122 if (auto core = dyn_cast<CoreOp>(user)) {
5123 if (getCoreData())
5124 return core.getSectionAlignment(std::nullopt);
5125 std::optional<int32_t> bank = getMemBank();
5126 return bank ? core.getSectionAlignment(bank) : 1;
5127 }
5128 return 1;
5129}
5130
5131int64_t BufferOp::getAllocationSize() {
5132 return getMemRefSizeInBytes(llvm::cast<MemRefType>(getType()),
5133 DataLayout::closest(getOperation()));
5134}
5135
5136LogicalResult BufferOp::verify() {
5137 if (UsesAreAccessible::verifyTrait(*this).failed()) {
5138 return failure();
5139 }
5140
5141 if (auto init = getInitialValue()) {
5142 auto initType = cast<ShapedType>(init->getType());
5143 MemRefType type = getType();
5144 if (initType.getShape() != type.getShape() ||
5145 initType.getElementType() != type.getElementType())
5146 return emitOpError("initial value of type ")
5147 << initType << " does not cover the buffer's " << type;
5148 }
5149
5150 if (FlatSymbolRefAttr resident = getResidentAttr()) {
5151 auto module = (*this)->getParentOfType<mlir::ModuleOp>();
5152 auto global = dyn_cast_or_null<memref::GlobalOp>(
5153 module ? SymbolTable::lookupSymbolIn(module, resident.getValue())
5154 : nullptr);
5155 if (!global)
5156 return emitOpError("resident names no memref.global ")
5157 << resident << " at module scope";
5158 if (global.getType() != getType())
5159 return emitOpError("resident ")
5160 << resident << "'s type " << global.getType()
5161 << " does not match this buffer's " << getType();
5162 }
5163
5164 // Each marks space held for a different reservation of the core's sections.
5165 if (getCoreData() && getBankReserved()) {
5166 return emitOpError("cannot be both core_data and bank_reserved; a buffer "
5167 "holds one reservation of a core's sections");
5168 }
5169
5170 // A bank pin no placement can satisfy: one its address space excludes, or
5171 // one past the banks of its tile type.
5172 if (std::optional<int32_t> memBank = getMemBank()) {
5173 SmallVector<int, 2> banks = banksFromMemorySpace(getType());
5174 if (!banks.empty() && !llvm::is_contained(banks, *memBank)) {
5175 auto diag = emitOpError("has address space for bank ") << banks.front();
5176 if (banks.size() > 1)
5177 diag << " or " << banks.back();
5178 return diag << " but is pinned to bank " << *memBank
5179 << ". These constraints disagree";
5180 }
5181 if (auto tileLike =
5182 dyn_cast_if_present<TileLike>(getTile().getDefiningOp());
5183 tileLike && (tileLike.isCoreTile() || tileLike.isMemTile())) {
5184 const AIETargetModel &targetModel = getTargetModel(*this);
5185 std::optional<int> col = tileLike.tryGetCol();
5186 std::optional<int> row = tileLike.tryGetRow();
5187 for (int c = 0; !(col && row) && c < targetModel.columns(); ++c)
5188 for (int r = 0; !(col && row) && r < targetModel.rows(); ++r)
5189 if (targetModel.getTileType(c, r) == tileLike.getTileType()) {
5190 col = c;
5191 row = r;
5192 }
5193 if (col && row &&
5194 (*memBank < 0 ||
5195 *memBank >=
5196 static_cast<int32_t>(targetModel.getNumBanks(*col, *row))))
5197 return emitOpError("mem_bank attribute value is out of range");
5198 }
5199 }
5200
5201 // A logical tile stands for a placement the compiler has yet to choose, so
5202 // neither check below has a tile to reason about.
5203 auto tile = dyn_cast_if_present<TileOp>(getTile().getDefiningOp());
5204 if (!tile) {
5205 return success();
5206 }
5207
5208 // A tile has one data region, so the code that looks the buffer up takes the
5209 // first match.
5210 if (getCoreData()) {
5211 for (Operation *user : tile.getResult().getUsers()) {
5212 auto other = dyn_cast<BufferOp>(user);
5213 if (other && other != *this && other.getCoreData()) {
5214 return emitOpError("is a second core_data buffer on tile (")
5215 << tile.getCol() << ", " << tile.getRow()
5216 << "); the core's data region is one extent";
5217 }
5218 }
5219 }
5220
5221 // A pin the allocator cannot honor: the address is outside the bank, so one
5222 // of the two is stale. A zero-sized buffer covers no byte, and one at the top
5223 // of the tile holds the one-past-the-end address, which is in no bank.
5224 std::optional<int32_t> address = getAddress();
5225 std::optional<int32_t> memBank = getMemBank();
5226 if (address && memBank && getAllocationSize() > 0) {
5227 const auto &targetModel = getTargetModel(*this);
5228 int64_t numBanks = targetModel.getNumBanks(tile.getCol(), tile.getRow());
5229 int64_t memSize = tile.isMemTile() ? targetModel.getMemTileSize()
5230 : targetModel.getLocalMemorySize();
5231 if (numBanks > 0) {
5232 int64_t bankSize = memSize / numBanks;
5233 int64_t bankOfAddress = *address / bankSize;
5234 if (bankOfAddress != *memBank) {
5235 return emitOpError("address 0x")
5236 << llvm::utohexstr(*address) << " lies in bank " << bankOfAddress
5237 << ", but mem_bank requests bank " << *memBank;
5238 }
5239 }
5240 }
5241 return success();
5242}
5243
5244// Peano models a bank as an address space (`aiebase_resources.h`: a..d are
5245// 5..8, 9..14 are pairs) and schedules loads on the strength of the qualifier,
5246// while nothing placed the buffer to match. Reading it here makes that
5247// assumption true rather than merely asserted.
5248SmallVector<int, 2> xilinx::AIE::banksFromMemorySpace(Type type) {
5249 auto memref = dyn_cast<MemRefType>(type);
5250 if (!memref) {
5251 return {};
5252 }
5253 auto space = dyn_cast_or_null<IntegerAttr>(memref.getMemorySpace());
5254 if (!space) {
5255 return {};
5256 }
5257 int64_t value = space.getInt();
5258 if (value >= 5 && value <= 8) {
5259 return {static_cast<int>(value - 5)};
5260 }
5261 switch (value) {
5262 case 9:
5263 return {0, 1};
5264 case 10:
5265 return {0, 2};
5266 case 11:
5267 return {0, 3};
5268 case 12:
5269 return {1, 2};
5270 case 13:
5271 return {1, 3};
5272 case 14:
5273 return {2, 3};
5274 default:
5275 return {};
5276 }
5277}
5278
5279// FIXME: make address assignment for buffers explicit and move this function to
5280// an interface
5281int32_t xilinx::AIE::getBufferBaseAddress(Operation *bufOp) {
5282 if (auto buf = dyn_cast<BufferOp>(bufOp)) {
5283 std::optional<int32_t> address = buf.getAddress();
5284 assert(address.has_value() && "buffer must have address assigned");
5285 return *address;
5286 }
5287 if (isa_and_nonnull<ExternalBufferOp>(bufOp))
5288 llvm::report_fatal_error(
5289 "External buffer addresses are assigned at runtime.");
5290 llvm::report_fatal_error("unknown buffer type");
5291}
5292
5293void xilinx::AIE::collectTiles(DeviceOp &device,
5294 DenseMap<TileID, Operation *> &tiles) {
5295 for (auto tile : device.getOps<TileOp>()) {
5296 tiles[tile.getTileID()] = tile;
5297 }
5298}
5299
5301 DeviceOp &device,
5302 DenseMap<Operation *, SmallVector<BufferOp, 4>> &buffers) {
5303 for (BufferOp buffer : device.getOps<BufferOp>()) {
5304 Operation *tileOp = buffer.getTile().getDefiningOp();
5305 buffers[tileOp].push_back(buffer);
5306 }
5307}
5308
5309static void printBufferInitialValue(OpAsmPrinter &p, BufferOp op, Type type,
5310 Attribute initialValue) {
5311 if (op.getInitialValue()) {
5312 p << "= ";
5313 p.printAttributeWithoutType(initialValue);
5314 }
5315}
5316
5317static ParseResult parseBufferInitialValue(OpAsmParser &parser, Type &type,
5318 Attribute &initialValue) {
5319 auto memrefType = llvm::cast<MemRefType>(type);
5320 if (!memrefType.hasStaticShape())
5321 return parser.emitError(parser.getNameLoc())
5322 << "type should be static shaped memref, but got " << type;
5323
5324 if (parser.parseOptionalEqual())
5325 return success();
5326
5327 Type tensorType = mlir::memref::getTensorTypeFromMemRefType(memrefType);
5328 if (parser.parseAttribute(initialValue, tensorType))
5329 return failure();
5330 if (!llvm::isa<ElementsAttr>(initialValue))
5331 return parser.emitError(parser.getNameLoc())
5332 << "initial value should be an elements attribute";
5333 return success();
5334}
5335
5336TileOp BufferOp::getTileOp() {
5337 return cast<TileElement>(this->getOperation()).getTileOp();
5338}
5339
5340//===----------------------------------------------------------------------===//
5341// MemOp
5342//===----------------------------------------------------------------------===//
5343
5344LogicalResult MemOp::verify() {
5345 Region &body = getBody();
5347 .failed())
5348 return failure();
5349
5350 for (auto &bodyOp : body.getOps()) {
5351 if (auto allocOp = dyn_cast<memref::AllocOp>(bodyOp))
5352 if (!allocOp->getAttr("id"))
5353 return allocOp.emitOpError()
5354 << "allocOp in MemOp region should have an id attribute";
5355 }
5356 return success();
5357}
5358
5359TileOp MemOp::getTileOp() {
5360 return cast<TileElement>(this->getOperation()).getTileOp();
5361}
5362
5363//===----------------------------------------------------------------------===//
5364// MemTileDMAOp
5365//===----------------------------------------------------------------------===//
5366
5367LogicalResult MemTileDMAOp::verify() {
5368 assert(getOperation()->getNumRegions() == 1 &&
5369 "MemTileDMAOp has zero region!");
5370
5372 .failed())
5373 return failure();
5374
5375 for (auto &bodyOp : getBody().getOps()) {
5376 if (auto allocOp = dyn_cast<memref::AllocOp>(bodyOp)) {
5377 if (!allocOp->getAttr("id"))
5378 return allocOp.emitOpError()
5379 << "allocOp in MemTileDMAOp region should have an id attribute";
5380 }
5381 if (auto startOp = dyn_cast<DMAStartOp>(bodyOp)) {
5382 // An endpoint's channel is not known yet; allocation keeps one whose
5383 // BDs reach another tile's memory off the local-only channels.
5384 if (!startOp.getEndpoint() && startOp.getChannelIndex() > 3) {
5385 // Channels 4 and 5 in a memtile are restricted to only access local
5386 // buffers and locks.
5387
5388 // TODO: Move this code to the dialect
5389 // Set of blocks found to be reachable within a given region.
5390 llvm::SmallSet<Block *, 16> reachable;
5391 SmallVector<Block *, 16> worklist;
5392 Block *firstBD = startOp.getSuccessor(0);
5393 reachable.insert(firstBD);
5394 worklist.push_back(firstBD);
5395 while (!worklist.empty()) {
5396 Block *block = worklist.pop_back_val();
5397 if (block->empty())
5398 continue;
5399 auto successors = block->getTerminator()->getSuccessors();
5400 for (auto *i : successors) {
5401 if (!reachable.contains(i)) {
5402 reachable.insert(i);
5403 worklist.push_back(i);
5404 }
5405 }
5406 }
5407 // This runs before the BDs' and use_locks' own verifiers, so an
5408 // operand that is not an aie.buffer, aie.external_buffer or aie.lock
5409 // (a block argument, say) is left for them to reject.
5410 for (Block *b : reachable) {
5411 for (DMABDOp bd : b->getOps<DMABDOp>()) {
5412 Operation *bufferDef = bd.getBuffer().getDefiningOp();
5413 if (!isa_and_nonnull<BufferOp, ExternalBufferOp>(bufferDef))
5414 continue;
5415 if (auto bufferOp = dyn_cast<BufferOp>(bufferDef);
5416 !bufferOp || bufferOp.getTile() != getTile()) {
5417 InFlightDiagnostic err =
5418 bd.emitOpError()
5419 << "is reachable from DMA channel "
5420 << startOp.getChannelIndex()
5421 << " and attempts to access a non-local buffer\n";
5422 err.attachNote(startOp->getLoc()) << "channel";
5423 err.attachNote(bufferDef->getLoc()) << "buffer";
5424 return err;
5425 }
5426 }
5427 for (auto useLock : b->getOps<UseLockOp>()) {
5428 if (auto lockOp = useLock.getLock().getDefiningOp<LockOp>();
5429 lockOp && lockOp.getTile() != getTile()) {
5430 InFlightDiagnostic err =
5431 useLock.emitOpError()
5432 << "is reachable from DMA channel "
5433 << startOp.getChannelIndex()
5434 << " and attempts to access a non-local lock\n";
5435 err.attachNote(startOp->getLoc()) << "channel";
5436 err.attachNote(lockOp->getLoc()) << "lock";
5437 return err;
5438 }
5439 }
5440 }
5441 }
5442 }
5443 }
5444
5445 return success();
5446}
5447
5448TileOp MemTileDMAOp::getTileOp() {
5449 return cast<TileElement>(this->getOperation()).getTileOp();
5450}
5451
5452//===----------------------------------------------------------------------===//
5453// DMAOp
5454//===----------------------------------------------------------------------===//
5455
5456static bool isBdPacketEnabled(DMABDOp bd) {
5457 if (bd.getPacket().has_value())
5458 return true;
5459 if (Block *blk = bd->getBlock())
5460 return !blk->getOps<DMABDPACKETOp>().empty();
5461 return false;
5462}
5463
5464// `channel` is below the tile's `channels` DMA channels in `dir`.
5465static LogicalResult verifyDMAChannelInRange(Operation *op, DMAChannelDir dir,
5466 int64_t channel,
5467 int64_t channels) {
5468 if (channel >= 0 && channel < channels)
5469 return success();
5470 return op->emitOpError() << stringifyDMAChannelDir(dir) << " channel "
5471 << channel << " is out of range: the tile has "
5472 << channels << " " << stringifyDMAChannelDir(dir)
5473 << " channels";
5474}
5475
5476LogicalResult xilinx::AIE::verifyDMAChannelIndex(Operation *op, TileLike tile,
5477 DMAChannelDir dir,
5478 int64_t channel) {
5479 if (getDMAChannelBundle(dir) != WireBundle::DMA)
5480 return verifyControlOrTraceDMAChannel(op, tile, dir, channel);
5481 int64_t channels = dir == DMAChannelDir::MM2S
5482 ? tile.getNumDestConnections(WireBundle::DMA)
5483 : tile.getNumSourceConnections(WireBundle::DMA);
5484 return verifyDMAChannelInRange(op, dir, channel, channels);
5485}
5486
5487// A shim PL tile connects the stream switch to the PL and has no DMA, though
5488// the target model gives it the shim's DMA stream ports.
5489static LogicalResult emitShimPLTileHasNoDMA(Operation *op,
5490 std::optional<int> col,
5491 std::optional<int> row) {
5492 if (col && row)
5493 return op->emitOpError("tile (")
5494 << *col << ", " << *row << ") is a shim PL tile and has no DMA";
5495 return op->emitOpError("the tile is a shim PL tile and has no DMA");
5496}
5497
5498LogicalResult xilinx::AIE::verifyDMAChannel(Operation *op, TileLike tile,
5499 DMAChannelDir dir,
5500 int64_t channel) {
5501 if (tile.isShimPLTile())
5502 return emitShimPLTileHasNoDMA(op, tile.tryGetCol(), tile.tryGetRow());
5503 return verifyDMAChannelIndex(op, tile, dir, channel);
5504}
5505
5506LogicalResult xilinx::AIE::verifyDMAChannel(Operation *op,
5507 const AIETargetModel &targetModel,
5508 int col, int row, DMAChannelDir dir,
5509 int64_t channel) {
5510 if (targetModel.isShimPLTile(col, row))
5511 return emitShimPLTileHasNoDMA(op, col, row);
5512 if (getDMAChannelBundle(dir) != WireBundle::DMA)
5513 return verifyControlOrTraceDMAChannel(op, targetModel, col, row, dir,
5514 channel);
5515 return verifyDMAChannelInRange(op, dir, channel,
5516 targetModel.getNumDMAChannels(col, row, dir));
5517}
5518
5519LogicalResult xilinx::AIE::verifyAssignedPacket(Operation *op,
5520 PacketInfoAttr packet,
5521 StringRef what) {
5522 if (packet && !packet.isAssigned())
5523 return op->emitOpError()
5524 << what
5525 << " has no pkt_id; allocation assigns one, so a header at "
5526 "this level must carry it";
5527 return success();
5528}
5529
5530LogicalResult
5531xilinx::AIE::verifyDMABDOutOfOrderId(DMABDOp bd, bool packetEnabledByContext) {
5532 std::optional<int32_t> oooId = bd.getOutOfOrderId();
5533 if (!oooId.has_value())
5534 return success();
5535 const AIETargetModel &targetModel = getTargetModel(bd.getOperation());
5537 return bd.emitOpError("out_of_order_id is not supported on this device");
5538 if (!packetEnabledByContext && !isBdPacketEnabled(bd))
5539 return bd.emitOpError("out_of_order_id requires a packet-enabled BD");
5540 uint32_t maxOooId = targetModel.getMaxOutOfOrderId();
5541 if (*oooId < 0 || static_cast<uint32_t>(*oooId) > maxOooId)
5542 return bd.emitOpError("out_of_order_id must be in [0, ") << maxOooId << "]";
5543 return success();
5544}
5545
5546// BD iteration bounds. Values are true/element (aie-codegen encodes value-1);
5547// size <= 1 disables iteration (stride ignored). The stride is checked in
5548// whole 32-bit words against the tile-specific step field. aiex.npu.writebd
5549// checks the same tile-correct step limit (getDmaBdStepBits) inline in its own
5550// raw-register terms.
5551LogicalResult xilinx::AIE::verifyDMABDIteration(DMABDOp bd,
5552 AIETileType tileType) {
5553 std::optional<BDIterationAttr> iter = bd.getIteration();
5554 if (!iter)
5555 return success();
5556 const AIETargetModel &targetModel = getTargetModel(bd.getOperation());
5558 return bd.emitOpError("BD iteration is not supported on this target");
5559 uint32_t size = iter->getSize(), current = iter->getCurrent();
5560 uint32_t maxSize = 1u << targetModel.getDmaBdIterBits(tileType);
5561 if (size < 1 || size > maxSize)
5562 return bd.emitOpError("BD iteration size must be in [1, ")
5563 << maxSize << "]";
5564 if (size > 1) {
5565 int64_t strideInBytes = static_cast<int64_t>(iter->getStride()) *
5566 bd.getBufferElementTypeWidthInBytes();
5567 if (strideInBytes % 4)
5568 return bd.emitOpError(
5569 "BD iteration stride must be aligned to 32-bit words");
5570 int64_t stepInWords = strideInBytes / 4;
5571 int64_t maxStep = (1LL << targetModel.getDmaBdStepBits(tileType)) - 1 +
5572 targetModel.getDmaBdStepBias(tileType);
5573 if (stepInWords < 1 || stepInWords > maxStep)
5574 return bd.emitOpError() << "BD iteration stride must be in [1, "
5575 << maxStep << "] 32-bit words";
5576 }
5577 if (current >= size)
5578 return bd.emitOpError("BD iteration current must be in [0, size)");
5579 return success();
5580}
5581
5582static LogicalResult verifyDMARepeatCount(Operation *op, int32_t repeatCount) {
5583 uint32_t maxRepeat = getTargetModel(op).getMaxRepeatCount();
5584 if (maxRepeat == 0) {
5585 if (repeatCount != 0)
5586 return op->emitOpError("repeat_count is not supported on this target");
5587 return success();
5588 }
5589 if (repeatCount < 0 || static_cast<uint32_t>(repeatCount) > maxRepeat)
5590 return op->emitOpError("repeat_count ")
5591 << repeatCount << " is out of range [0, " << maxRepeat
5592 << "] for this target";
5593 return success();
5594}
5595
5597 Operation *op, const AIETargetModel &targetModel, int col, int row,
5598 DMAChannelDir dir, int64_t channel) {
5599 if (getDMAChannelBundle(dir) == WireBundle::DMA)
5600 return success();
5601 int64_t channels = targetModel.getNumDMAChannels(col, row, dir);
5602 if (channel >= 0 && channel < channels)
5603 return success();
5604 return op->emitOpError() << stringifyDMAChannelDir(dir) << " channel "
5605 << channel << " is out of range: the tile has "
5606 << channels << " " << stringifyDMAChannelDir(dir)
5607 << " channels";
5608}
5609
5610LogicalResult xilinx::AIE::verifyControlOrTraceDMAChannel(Operation *op,
5611 TileLike tile,
5612 DMAChannelDir dir,
5613 int64_t channel) {
5614 std::optional<int> col = tile.tryGetCol();
5615 std::optional<int> row = tile.tryGetRow();
5616 if (!col || !row)
5617 return success();
5618 return verifyControlOrTraceDMAChannel(op, getTargetModel(op), *col, *row, dir,
5619 channel);
5620}
5621
5622LogicalResult
5623xilinx::AIE::verifyOutOfOrderChannel(Operation *op, DMAChannelDir dir,
5624 bool outOfOrder, ArrayRef<DMABDOp> bds,
5625 bool packetEnabledByContext) {
5626 if (!outOfOrder)
5627 return success();
5628 if (dir != DMAChannelDir::S2MM)
5629 return op->emitOpError("out_of_order is only valid on an S2MM channel");
5631 return op->emitOpError(
5632 "out-of-order S2MM DMA is not supported on this device");
5633 if (bds.empty())
5634 return op->emitOpError("out-of-order S2MM channel must have at least one "
5635 "receive buffer descriptor"); // else stall
5636 for (DMABDOp bd : bds) {
5637 if (!packetEnabledByContext && !isBdPacketEnabled(bd))
5638 return bd.emitOpError(
5639 "out-of-order S2MM receive buffer descriptor must be packet-enabled");
5640 if (bd.getOutOfOrderId().has_value())
5641 return bd.emitOpError(
5642 "out_of_order_id belongs on the sender buffer descriptor, not an "
5643 "out-of-order S2MM receive buffer descriptor");
5644 }
5645 // an inter-BD lock dependency can deadlock because arrival order is unknown
5646 DenseMap<Operation *, Operation *> releasedByRecvBd;
5647 for (DMABDOp bd : bds)
5648 for (auto useLock : bd->getBlock()->getOps<UseLockOp>())
5649 if (useLock.release())
5650 if (Operation *lockDef = useLock.getLock().getDefiningOp())
5651 releasedByRecvBd.try_emplace(lockDef, bd.getOperation());
5652 for (DMABDOp bd : bds)
5653 for (auto useLock : bd->getBlock()->getOps<UseLockOp>())
5654 if (useLock.acquire() || useLock.acquireGE())
5655 if (Operation *lockDef = useLock.getLock().getDefiningOp()) {
5656 auto it = releasedByRecvBd.find(lockDef);
5657 if (it != releasedByRecvBd.end() && it->second != bd.getOperation())
5658 return bd.emitOpError(
5659 "out-of-order S2MM prohibits inter-BD lock dependencies; "
5660 "can deadlock");
5661 }
5662 return success();
5663}
5664
5665LogicalResult xilinx::AIE::verifyBdLockPair(Block &block, bool outOfOrder,
5666 UseLockOp &acquire,
5667 UseLockOp &release) {
5668 acquire = nullptr;
5669 release = nullptr;
5670 auto reject = [&](UseLockOp at) {
5671 auto diag = at.emitOpError(
5672 "does not fit its buffer descriptor, which has one lock-acquire field "
5673 "and one lock-release field; a buffer descriptor block uses either no "
5674 "lock or one use_lock(acquire) and one use_lock(release)");
5675 if (outOfOrder)
5676 diag << ", or a use_lock(release) alone when out-of-order";
5677 return diag;
5678 };
5679 for (UseLockOp op : block.getOps<UseLockOp>()) {
5680 UseLockOp &slot = op.release() ? release : acquire;
5681 if (slot)
5682 return reject(op);
5683 slot = op;
5684 }
5685 if (!acquire && !release)
5686 return success();
5687 if (release && (acquire || outOfOrder))
5688 return success();
5689 return reject(acquire ? acquire : release);
5690}
5691
5692LogicalResult DMAOp::verify() {
5693 auto *parentOp = getOperation()->getParentOp();
5694 if (parentOp->getRegion(0).getBlocks().size() > 1)
5695 return emitOpError("DMAOp can only appear in single block region");
5696 if (!parentOp->getRegion(0).getOps<DMAStartOp>().empty())
5697 return emitOpError("DMAOp is not compatible with DMAStart ops");
5698 if (auto program = dyn_cast<DmaBody>(parentOp);
5699 program &&
5700 failed(verifyDMAChannelIndex(
5701 getOperation(), cast<TileLike>(program.getTile().getDefiningOp()),
5702 getChannelDir(), getChannelIndex())))
5703 return failure();
5704 auto bdRegions = getBds();
5705 for (auto &bdRegion : bdRegions) {
5706 if (!bdRegion.hasOneBlock())
5707 return emitOpError("DMAOp regions must have only one block");
5708 auto bds = llvm::to_vector_of<DMABDOp>(bdRegion.front().getOps<DMABDOp>());
5709 if (bds.size() != 1)
5710 return emitOpError("DMAOp regions/blocks must have exactly one DMABDOp");
5711 auto useLocks =
5712 llvm::to_vector_of<UseLockOp>(bdRegion.front().getOps<UseLockOp>());
5713 if (useLocks.size() != 2)
5714 return emitOpError(
5715 "DMAOp regions/blocks must have exactly two UseLock ops");
5716 }
5717 if (getPadValue() != 0) {
5718 if (!isa<MemTileDMAOp>(parentOp))
5719 return emitOpError("pad_value is only supported on memtile DMA channels");
5720 if (getChannelDir() != DMAChannelDir::MM2S)
5721 return emitOpError("pad_value is only supported on MM2S DMA channels");
5722 if (!getTargetModel(getOperation()).isMemTilePadValueSupported())
5723 return emitOpError("pad_value requires the CONSTANT_PAD_VALUE register, "
5724 "unavailable on this target");
5725 }
5726 if (auto program = dyn_cast<TileElement>(parentOp))
5728 getOperation(), program.getTileLike(), getChannelDir(),
5729 getChannelIndex())))
5730 return failure();
5731 if (failed(verifyDMARepeatCount(getOperation(), getRepeatCount())))
5732 return failure();
5733 SmallVector<DMABDOp> bds;
5734 for (auto &bdRegion : getBds())
5735 llvm::append_range(bds, bdRegion.front().getOps<DMABDOp>());
5736 return verifyOutOfOrderChannel(getOperation(), getChannelDir(),
5737 getOutOfOrder(), bds);
5738}
5739
5740//===----------------------------------------------------------------------===//
5741// DMABDOp
5742//===----------------------------------------------------------------------===//
5743
5744BufferOp DMABDOp::getBufferOp() {
5745 return cast<BufferOp>(getBuffer().getDefiningOp());
5746}
5747
5748// The optional `: type` after an SSA operand, defaulting to `defaultType`, so
5749// the common width keeps its untyped spelling.
5750static ParseResult parseOptionalOperandType(OpAsmParser &parser, Type &type,
5751 Type defaultType) {
5752 type = defaultType;
5753 if (succeeded(parser.parseOptionalColon()))
5754 return parser.parseType(type);
5755 return success();
5756}
5757
5758static void printOptionallyTypedOperand(OpAsmPrinter &printer, Value operand,
5759 Type defaultType) {
5760 printer << operand;
5761 if (operand.getType() != defaultType)
5762 printer << " : " << operand.getType();
5763}
5764
5765// Parse/print hooks for the custom<DynamicScalar>($operand, $static_attr,
5766// type($operand)) directive: a single scalar that is either an SSA value
5767// (runtime, `%v` for i32 or `%v : type`) or a compile-time integer constant
5768// (folded into the attribute), so a constant never materializes an operand.
5769// The scalar analog of custom<TypedDynamicIndexList>.
5770static ParseResult
5771parseDynamicScalar(OpAsmParser &parser,
5772 std::optional<OpAsmParser::UnresolvedOperand> &operand,
5773 IntegerAttr &staticAttr, Type &type) {
5774 int64_t intValue;
5775 OptionalParseResult intResult = parser.parseOptionalInteger(intValue);
5776 if (intResult.has_value()) {
5777 if (failed(*intResult))
5778 return failure();
5779 staticAttr =
5780 parser.getBuilder().getI32IntegerAttr(static_cast<int32_t>(intValue));
5781 return success();
5782 }
5783 OpAsmParser::UnresolvedOperand op;
5784 if (parser.parseOperand(op) ||
5785 parseOptionalOperandType(parser, type, parser.getBuilder().getI32Type()))
5786 return failure();
5787 operand = op;
5788 return success();
5789}
5790
5791static void printDynamicScalar(OpAsmPrinter &printer, Operation *,
5792 Value operand, IntegerAttr staticAttr, Type) {
5793 if (operand)
5794 printOptionallyTypedOperand(printer, operand,
5795 IntegerType::get(operand.getContext(), 32));
5796 else
5797 printer << staticAttr.getInt();
5798}
5799
5801 OpAsmParser &parser,
5802 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &values,
5803 DenseI64ArrayAttr &integers, SmallVectorImpl<Type> &types) {
5804 SmallVector<int64_t> ints;
5805 auto parseEntry = [&]() -> ParseResult {
5806 OpAsmParser::UnresolvedOperand operand;
5807 OptionalParseResult isOperand = parser.parseOptionalOperand(operand);
5808 if (!isOperand.has_value())
5809 return parser.parseInteger(ints.emplace_back());
5810 Type type;
5811 if (failed(*isOperand) ||
5812 parseOptionalOperandType(parser, type,
5813 parser.getBuilder().getI64Type()))
5814 return failure();
5815 values.push_back(operand);
5816 types.push_back(type);
5817 ints.push_back(ShapedType::kDynamic);
5818 return success();
5819 };
5820 if (parser.parseCommaSeparatedList(AsmParser::Delimiter::Square, parseEntry))
5821 return failure();
5822 integers = parser.getBuilder().getDenseI64ArrayAttr(ints);
5823 return success();
5824}
5825
5826void xilinx::AIE::printTypedDynamicIndexList(OpAsmPrinter &printer, Operation *,
5827 OperandRange values,
5828 ArrayRef<int64_t> integers,
5829 TypeRange) {
5830 printer << '[';
5831 auto value = values.begin();
5832 llvm::interleaveComma(integers, printer, [&](int64_t i) {
5833 if (!ShapedType::isDynamic(i)) {
5834 printer << i;
5835 return;
5836 }
5837 Value v = *value++;
5838 printOptionallyTypedOperand(printer, v,
5839 IntegerType::get(v.getContext(), 64));
5840 });
5841 printer << ']';
5842}
5843
5844// Split a scalar OpFoldResult into an operand (runtime value) or an i32
5845// attribute (compile-time constant). A null OpFoldResult leaves both unset.
5846static void splitScalarOfr(mlir::OpBuilder &builder, mlir::OpFoldResult ofr,
5847 mlir::Value &operand, mlir::IntegerAttr &attr) {
5848 operand = nullptr;
5849 attr = nullptr;
5850 if (!ofr)
5851 return;
5852 if (auto v = llvm::dyn_cast_if_present<mlir::Value>(ofr)) {
5853 operand = v;
5854 return;
5855 }
5856 auto intAttr =
5857 llvm::cast<mlir::IntegerAttr>(llvm::cast<mlir::Attribute>(ofr));
5858 attr = builder.getI32IntegerAttr(static_cast<int32_t>(intAttr.getInt()));
5859}
5860
5861void DMABDOp::buildMixed(mlir::OpBuilder &builder, mlir::OperationState &state,
5862 mlir::Value buffer, mlir::OpFoldResult offset,
5863 mlir::OpFoldResult len,
5864 llvm::ArrayRef<mlir::OpFoldResult> sizes,
5865 llvm::ArrayRef<mlir::OpFoldResult> strides,
5866 BDPadLayoutArrayAttr padDims, PacketInfoAttr packet) {
5867 // Split each mixed list into its dynamic operands + static array (with the
5868 // ShapedType::kDynamic sentinel for the runtime entries).
5869 llvm::SmallVector<int64_t> staticSizes, staticStrides;
5870 llvm::SmallVector<mlir::Value> dynSizes, dynStrides;
5871 mlir::dispatchIndexOpFoldResults(sizes, dynSizes, staticSizes);
5872 mlir::dispatchIndexOpFoldResults(strides, dynStrides, staticStrides);
5873
5874 // Leave the static arrays unset when there is no ND layout so they elide
5875 // from the printed form.
5876 DenseI64ArrayAttr staticSizesAttr =
5877 staticSizes.empty() ? DenseI64ArrayAttr{}
5878 : builder.getDenseI64ArrayAttr(staticSizes);
5879 DenseI64ArrayAttr staticStridesAttr =
5880 staticStrides.empty() ? DenseI64ArrayAttr{}
5881 : builder.getDenseI64ArrayAttr(staticStrides);
5882
5883 // A constant offset/len lands in the static_* attribute; a runtime value
5884 // becomes the operand (same operand-vs-attr split as sizes/strides).
5885 mlir::Value offsetVal, lenVal;
5886 mlir::IntegerAttr offsetAttr, lenAttr;
5887 splitScalarOfr(builder, offset, offsetVal, offsetAttr);
5888 splitScalarOfr(builder, len, lenVal, lenAttr);
5889
5890 build(builder, state, buffer, /*offset=*/offsetVal, /*len=*/lenVal,
5891 /*static_offset=*/offsetAttr, /*static_len=*/lenAttr,
5892 /*sizes=*/dynSizes, /*strides=*/dynStrides,
5893 /*static_sizes=*/staticSizesAttr,
5894 /*static_strides=*/staticStridesAttr,
5895 /*pad_dimensions=*/padDims,
5896 /*bd_id_val=*/nullptr,
5897 /*bd_id=*/nullptr,
5898 /*packet=*/packet,
5899 /*out_of_order_id=*/nullptr,
5900 /*bd_tag=*/nullptr,
5901 /*out_of_order_tag=*/nullptr,
5902 /*burst_length=*/nullptr,
5903 /*axcache=*/nullptr,
5904 /*iteration=*/nullptr,
5905 /*offset_parameter=*/nullptr,
5906 /*offset_state_table_idx=*/nullptr,
5907 /*length_parameter=*/nullptr,
5908 /*length_unit=*/nullptr,
5909 /*length_state_table_idx=*/nullptr,
5910 /*length_core_encoded=*/nullptr,
5911 /*next_bd_id=*/nullptr);
5912}
5913
5914void DMABDOp::buildWithConstants(mlir::OpBuilder &builder,
5915 mlir::OperationState &state,
5916 mlir::Value buffer, int32_t offset,
5917 int32_t len, BDDimLayoutArrayAttr dims,
5918 BDPadLayoutArrayAttr padDims,
5919 PacketInfoAttr packet) {
5920 // Constant offset/len flow to the static_offset/static_len attributes (no
5921 // arith.constant materialized). i32 matches AIEI32Attr, keeping the cast
5922 // sign-exact for negative offsets.
5923 mlir::OpFoldResult offsetOfr = builder.getI32IntegerAttr(offset);
5924 mlir::OpFoldResult lenOfr = builder.getI32IntegerAttr(len);
5925
5926 // Turn the outermost-first BDDimLayoutArrayAttr into all-constant
5927 // OpFoldResults for buildMixed.
5928 llvm::SmallVector<mlir::OpFoldResult> sizes, strides;
5929 if (dims) {
5930 for (BDDimLayoutAttr d : dims) {
5931 sizes.push_back(builder.getI64IntegerAttr(d.getSize()));
5932 strides.push_back(builder.getI64IntegerAttr(d.getStride()));
5933 }
5934 }
5935 buildMixed(builder, state, buffer, offsetOfr, lenOfr, sizes, strides, padDims,
5936 packet);
5937}
5938
5939llvm::SmallVector<mlir::OpFoldResult> DMABDOp::getMixedSizes() {
5940 return ::mlir::getMixedValues(
5941 getStaticSizes().value_or(llvm::ArrayRef<int64_t>{}), getSizes(),
5942 getContext());
5943}
5944
5945llvm::SmallVector<mlir::OpFoldResult> DMABDOp::getMixedStrides() {
5946 return ::mlir::getMixedValues(
5947 getStaticStrides().value_or(llvm::ArrayRef<int64_t>{}), getStrides(),
5948 getContext());
5949}
5950
5951LogicalResult DMABDOp::verifyMixedSizesAndStrides() {
5952 llvm::ArrayRef<int64_t> staticSizes =
5953 getStaticSizes().value_or(llvm::ArrayRef<int64_t>{});
5954 llvm::ArrayRef<int64_t> staticStrides =
5955 getStaticStrides().value_or(llvm::ArrayRef<int64_t>{});
5956 if (failed(mlir::verifyListOfOperandsOrIntegers(
5957 *this, "sizes", staticSizes.size(), staticSizes, getSizes())))
5958 return failure();
5959 if (failed(mlir::verifyListOfOperandsOrIntegers(
5960 *this, "strides", staticStrides.size(), staticStrides, getStrides())))
5961 return failure();
5962 if (staticSizes.size() != staticStrides.size())
5963 return emitOpError("expected the same number of sizes (")
5964 << staticSizes.size() << ") and strides (" << staticStrides.size()
5965 << ")";
5966 return success();
5967}
5968
5969std::optional<llvm::SmallVector<BDDimLayoutAttr>> DMABDOp::getFoldedDimensions(
5970 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) {
5971 llvm::ArrayRef<int64_t> sizes =
5972 getStaticSizes().value_or(llvm::ArrayRef<int64_t>{});
5973 llvm::ArrayRef<int64_t> strides =
5974 getStaticStrides().value_or(llvm::ArrayRef<int64_t>{});
5975 if (sizes.size() != strides.size()) {
5976 emitError() << "expected the same number of sizes (" << sizes.size()
5977 << ") and strides (" << strides.size() << ")";
5978 return std::nullopt;
5979 }
5980 mlir::OperandRange dynSizes = getSizes(), dynStrides = getStrides();
5981 unsigned nextSize = 0, nextStride = 0;
5982 llvm::SmallVector<BDDimLayoutAttr> dims;
5983 dims.reserve(sizes.size());
5984 for (auto [s, t] : llvm::zip(sizes, strides)) {
5985 std::optional<int64_t> sc =
5986 ShapedType::isDynamic(s)
5987 ? mlir::getConstantIntValue(dynSizes[nextSize++])
5988 : s;
5989 std::optional<int64_t> tc =
5990 ShapedType::isDynamic(t)
5991 ? mlir::getConstantIntValue(dynStrides[nextStride++])
5992 : t;
5993 if (!sc || !tc) {
5994 emitError() << "buffer descriptor size/stride is a runtime value; a "
5995 "compile-time constant is required on this path";
5996 return std::nullopt;
5997 }
5998 dims.push_back(BDDimLayoutAttr::get(
5999 getContext(), static_cast<uint32_t>(*sc), static_cast<uint32_t>(*tc)));
6000 }
6001 return dims;
6002}
6003
6004std::optional<llvm::SmallVector<BDDimLayoutAttr>>
6005DMABDOp::getConstantDimensions() {
6006 return getFoldedDimensions([&]() { return emitOpError(); });
6007}
6008
6009// With dims the furthest index bounds the access (a stride-0 dim may transfer
6010// more elements than the buffer holds); without them the length does. A
6011// runtime-sequence argument's type does not bound the host buffer behind it.
6012LogicalResult DMABDOp::verifyTransferInBounds() {
6013 auto buffer = llvm::dyn_cast<MemRefType>(getBuffer().getType());
6014 if (!buffer || !buffer.hasStaticShape() ||
6015 llvm::isa<BlockArgument>(getBuffer()))
6016 return success();
6017 if ((getOffsetParameterAttr() || getOffsetStateTableIdxAttr()) && !hasLen())
6018 return emitOpError("offset_parameter requires an explicit `len` on a local "
6019 "buffer; the default whole-buffer length runs past the "
6020 "end for any nonzero runtime offset");
6021 std::optional<int32_t> offset = hasOffset() ? getConstantOffset() : 0;
6022 if (!offset || *offset < 0)
6023 return success();
6024 int64_t numElements = buffer.getNumElements();
6025 SmallVector<OpFoldResult> sizes = getMixedSizes();
6026 SmallVector<OpFoldResult> strides = getMixedStrides();
6027 if (sizes.empty()) {
6028 std::optional<int64_t> len =
6029 hasLen() ? std::optional<int64_t>(getConstantLen()) : numElements;
6030 if (!len || *len <= 0 || *offset + *len <= numElements)
6031 return success();
6032 InFlightDiagnostic err = emitOpError("transfer of ")
6033 << *len << " elements at offset " << *offset
6034 << " runs past the end of the " << numElements
6035 << "-element buffer";
6036 if (!hasLen())
6037 err.attachNote() << "an omitted `len` is the whole buffer; give the "
6038 "length to transfer from this offset";
6039 return err;
6040 }
6041 int64_t maxIdx = *offset;
6042 for (auto [size, stride] : llvm::zip(sizes, strides)) {
6043 std::optional<int64_t> s = getConstantIntValue(size);
6044 std::optional<int64_t> t = getConstantIntValue(stride);
6045 if (!s || !t)
6046 return success();
6047 maxIdx += *t * (*s - 1);
6048 }
6049 if (maxIdx < numElements)
6050 return success();
6051 return emitOpError() << "Specified stride(s) and size(s) result in out of "
6052 "bounds access in buffer, for index "
6053 << maxIdx << " in memref of length " << numElements
6054 << ".";
6055}
6056
6057// A BDDimLayoutAttr array (outermost-first) describes a contiguous row-major
6058// scan when the innermost stride is 1 and each outer stride equals the product
6059// of all inner sizes. Used by both DMABDOp verification and canonicalization.
6060int64_t xilinx::AIE::paddedSize(llvm::ArrayRef<BDDimLayoutAttr> dims,
6061 llvm::ArrayRef<BDPadLayoutAttr> pads,
6062 int64_t fallback) {
6063 if (dims.empty() || pads.empty())
6064 return fallback;
6065 int64_t size = 1;
6066 for (auto [dim, pad] : llvm::zip(dims, pads))
6067 size *= dim.getSize() + pad.getConstPadBefore() + pad.getConstPadAfter();
6068 return size;
6069}
6070
6071bool xilinx::AIE::isContiguousBDTransfer(llvm::ArrayRef<BDDimLayoutAttr> dims) {
6072 if (dims.empty())
6073 return true; // no ND layout = trivially contiguous
6074 // Innermost (last) stride must be 1.
6075 if (dims.back().getStride() != 1)
6076 return false;
6077 // Each outer stride must equal the product of all inner sizes.
6078 // Use uint64_t throughout to match the unsigned getSize()/getStride() types.
6079 uint64_t product = 1;
6080 for (int i = static_cast<int>(dims.size()) - 1; i >= 1; --i) {
6081 product *= dims[i].getSize();
6082 // A size-1 dimension's stride is irrelevant (it is never stepped).
6083 if (dims[i - 1].getSize() > 1 && dims[i - 1].getStride() != product)
6084 return false;
6085 }
6086 return true;
6087}
6088
6089std::optional<SmallVector<BDDimLayoutAttr>>
6090xilinx::AIE::normalizedBDDims(ArrayRef<BDDimLayoutAttr> dims, int64_t len) {
6091 SmallVector<BDDimLayoutAttr> kept;
6092 int64_t product = 1;
6093 for (BDDimLayoutAttr dim : dims) {
6094 product *= dim.getSize();
6095 if (dim.getSize() != 1)
6096 kept.push_back(dim);
6097 }
6098 if (kept.size() == dims.size() || len != product)
6099 return std::nullopt;
6100 if (isContiguousBDTransfer(kept))
6101 return SmallVector<BDDimLayoutAttr>{};
6102 return kept;
6103}
6104
6105// The firmware's UPDATE_REG reads the 32-bit length word with its low two bits
6106// cleared, adds the delta, and writes the sum back with them cleared again.
6107// The length word counts 32-bit words, so both the static length and every
6108// added unit must be multiples of four words (16 bytes) to survive.
6109FailureOr<int64_t> xilinx::AIE::getLengthUnitBytes(Operation *op,
6110 int64_t lengthUnit,
6111 BaseMemRefType buffer) {
6112 uint64_t elemBitWidth = buffer.getElementTypeBitWidth();
6113 if (elemBitWidth == 0 || (elemBitWidth % 8) != 0)
6114 return op->emitOpError("length_parameter requires a whole-byte element "
6115 "type");
6116 std::optional<int64_t> unitBytes =
6117 llvm::checkedMul(lengthUnit, static_cast<int64_t>(elemBitWidth / 8));
6118 if (!unitBytes || *unitBytes / 4 > std::numeric_limits<uint32_t>::max())
6119 return op->emitOpError("length_unit (")
6120 << lengthUnit
6121 << " elements) exceeds the 32-bit word count of a BD length";
6122 if (*unitBytes % 16 != 0)
6123 return op->emitOpError("length_unit must be a multiple of 16 bytes, got ")
6124 << *unitBytes << " bytes";
6125 return *unitBytes;
6126}
6127
6129 Operation *op, std::optional<int64_t> lengthUnit, BaseMemRefType buffer,
6130 std::optional<int64_t> lenElems, bool contiguous,
6131 llvm::ArrayRef<int64_t> innerSizes) {
6132 if (!lengthUnit)
6133 return op->emitOpError("length_parameter requires length_unit");
6134 if (failed(getLengthUnitBytes(op, *lengthUnit, buffer)))
6135 return failure();
6136 int64_t elemBytes = buffer.getElementTypeBitWidth() / 8;
6137 if (!lenElems)
6138 return op->emitOpError("length_parameter requires a constant length");
6139 if ((*lenElems * elemBytes) % 16 != 0)
6140 return op->emitOpError("length_parameter requires a static length that is "
6141 "a multiple of 16 bytes, got ")
6142 << *lenElems * elemBytes << " bytes";
6143 if (contiguous)
6144 return success();
6145 llvm::SmallVector<int64_t, 3> sizes(innerSizes);
6146 llvm::SmallVector<int64_t, 3> strides(3, 0);
6147 placeRuntimeLengthDimension(sizes, strides);
6148 if (sizes[2] <= 1)
6149 return op->emitOpError("length_parameter on a non-contiguous pattern "
6150 "requires its second or third dimension to have a "
6151 "size above one: the added length continues it");
6152 int64_t rowElems = sizes[0] * sizes[1];
6153 if (*lengthUnit % rowElems != 0)
6154 return op->emitOpError("length_unit (")
6155 << *lengthUnit << " elements) must be a multiple of the " << rowElems
6156 << " elements moved per step of the dimension the added length "
6157 "continues";
6158 return success();
6159}
6160
6162 llvm::MutableArrayRef<int64_t> sizes,
6163 llvm::MutableArrayRef<int64_t> strides) {
6164 if (sizes[2] > 1 || sizes[1] <= 1)
6165 return;
6166 sizes[2] = sizes[1];
6167 strides[2] = strides[1];
6168 sizes[1] = 1;
6169 strides[1] = 0;
6170}
6171
6173 Operation *op, const AIETargetModel &targetModel, int col, int row) {
6174 AIEArch arch = targetModel.getTargetArch();
6175 if (arch != AIEArch::AIE2 && arch != AIEArch::AIE2p)
6176 return op->emitOpError("length_parameter is only supported on AIE2 and "
6177 "AIE2P devices");
6178 if (!targetModel.isShimNOCTile(col, row))
6179 return op->emitOpError("length_parameter is only supported on shim NOC "
6180 "tiles, got tile (")
6181 << col << ", " << row << ")";
6182 const DmaBdLayout *layout = targetModel.getDmaBdLayout(col, row);
6183 if (!layout || layout->bufferLength.shift != 0 ||
6184 layout->bufferLength.width != 32)
6185 return op->emitOpError("length_parameter requires a BD whose buffer "
6186 "length fills a 32-bit register");
6187 return success();
6188}
6189
6190llvm::SmallVector<uint32_t> xilinx::AIE::getAssignedBdIds(DmaBody program) {
6191 llvm::SmallVector<uint32_t> ids;
6192 program.getDmaBody().walk([&](DMABDOp bd) {
6193 if (auto id = bd.getBdId())
6194 ids.push_back(*id);
6195 });
6196 return ids;
6197}
6198
6199LogicalResult DMABDOp::verify() {
6200 if (getOffsetParameterAttr() || getOffsetStateTableIdxAttr()) {
6201 uint64_t elemBitWidth = llvm::cast<BaseMemRefType>(getBuffer().getType())
6202 .getElementTypeBitWidth();
6203 if (elemBitWidth == 0 || (elemBitWidth % 8) != 0)
6204 return emitOpError("offset_parameter requires a whole-byte element type");
6205 }
6206
6207 if (getLengthParameterAttr() || getLengthStateTableIdxAttr()) {
6208 // The length is patched by a runtime-sequence instruction, so only a BD
6209 // the runtime sequence configures can have one.
6210 if (llvm::isa<MemOp, MemTileDMAOp, ShimDMAOp, DMAOp>(
6211 (*this)->getParentOp()))
6212 return emitOpError("length_parameter is only supported on a BD in a "
6213 "runtime sequence");
6214 std::optional<llvm::SmallVector<BDDimLayoutAttr>> dims =
6215 getFoldedDimensions([&]() {
6216 return emitOpError("length_parameter requires a static pattern: ");
6217 });
6218 if (!dims)
6219 return failure();
6220 // aie-decompose-large-dma-bd leaves a runtime-length BD whole.
6221 if (dims->size() > 4)
6222 return emitOpError("length_parameter requires at most 4 dimensions, got ")
6223 << dims->size();
6224 // The outermost of four dimensions is the iteration, which repeats the
6225 // whole length.
6226 llvm::ArrayRef<BDDimLayoutAttr> inner(*dims);
6227 if (inner.size() == 4)
6228 inner = inner.drop_front();
6229 llvm::SmallVector<int64_t, 3> innerSizes(3, 1);
6230 for (auto [i, dim] : llvm::enumerate(llvm::reverse(inner)))
6231 innerSizes[i] = dim.getSize();
6232 auto buffer = llvm::cast<BaseMemRefType>(getBuffer().getType());
6233 std::optional<int64_t> lenElems;
6234 if (std::optional<int32_t> len = getConstantLen())
6235 lenElems = *len;
6236 else if (!hasLen() && buffer.hasStaticShape())
6237 lenElems = buffer.getNumElements();
6238 if (failed(verifyLengthParameter(*this, getLengthUnit(), buffer, lenElems,
6240 innerSizes)))
6241 return failure();
6242 }
6243
6244 // Skip verification of the BDOp outside of mem operations.
6245 // BDOps may appear elsewhere and subsequent lowerings will place them in the
6246 // correct mem ops.
6247 Operation *p = (*this)->getParentOp();
6248 if (!llvm::isa<MemOp, MemTileDMAOp, ShimDMAOp, DMAOp>(*p)) {
6249 return success();
6250 }
6251
6252 // Check if buffer is an unranked memref (e.g., from function argument)
6253 bool isUnrankedMemRef = llvm::isa<UnrankedMemRefType>(getBuffer().getType());
6254
6255 // For unranked memrefs, we can't verify as strictly since we don't know
6256 // the buffer's defining op or its full type at compile time
6257 if (!isUnrankedMemRef) {
6258 if (!isa_and_nonnull<BufferOp, ExternalBufferOp>(
6259 getBuffer().getDefiningOp()))
6260 return emitOpError(
6261 "BDs only support BufferOp or ExternalBufferOp operands.");
6262 }
6263
6264 if (getLenInBytes() % 4)
6265 return emitOpError("transfer length must be multiple of 4 (i.e., represent "
6266 "4 byte aligned address)");
6267
6268 TileElement parentTileElement = getParentTileElement(getOperation());
6269 TileLike parentTile = parentTileElement.getTileLike();
6270 if (!parentTile)
6271 return emitOpError("parent tile must implement TileLike interface");
6272
6273 if (!isUnrankedMemRef && getOperation()->getParentOfType<MemOp>() &&
6274 (!isa<BufferOp>(getBuffer().getDefiningOp()) ||
6275 getBufferOp().getTile() != parentTileElement.getTile()))
6276 return emitOpError(
6277 "Core tile DMAs can only access a buffer in the same tile.");
6278
6279 const AIETargetModel &targetModel = getTargetModel(getOperation());
6280
6281 uint32_t maxBds = targetModel.getNumBDs(parentTile.getTileType());
6282 if (std::optional<int32_t> bdId = getBdId();
6283 bdId.has_value() && static_cast<uint32_t>(*bdId) >= maxBds)
6284 return emitOpError("bdId attribute exceeds max: ") << maxBds - 1;
6285 if (std::optional<int32_t> nextBdId = getNextBdId();
6286 nextBdId.has_value() && static_cast<uint32_t>(*nextBdId) >= maxBds)
6287 return emitOpError("nextBdId attribute exceeds max: ") << maxBds - 1;
6288
6289 if (getBdIdVal() && getBdId().has_value())
6290 return emitOpError("bd_id and bd_id_val are mutually exclusive");
6291
6292 // Issue #1097: the buffer_length field of a DMA buffer descriptor has a
6293 // tile-type-specific bit width (e.g. on AIE2: 32-bit shim, 17-bit mem tile,
6294 // 14-bit core tile). The hardware field counts address-generation granules
6295 // (32-bit words), so convert the byte length accordingly and reject
6296 // transfers that would overflow the field (they would otherwise be silently
6297 // truncated during lowering). Only checkable when the length is statically
6298 // known: either an explicit constant `len`, or (when no `len` is given) a
6299 // statically-shaped buffer whose full size is used.
6300 {
6301 bool lenStaticallyKnown = getConstantLen().has_value();
6302 if (!lenStaticallyKnown && !hasLen()) {
6303 if (auto shaped = llvm::dyn_cast<mlir::ShapedType>(getBuffer().getType()))
6304 lenStaticallyKnown = shaped.hasStaticShape();
6305 }
6306 // Skip validation for non-positive constant lengths: negative values
6307 // indicate a separate issue (e.g. distribute-link offset inference) and
6308 // would wrap to huge values via getLenInBytes().
6309 if (lenStaticallyKnown) {
6310 if (auto constLen = getConstantLen();
6311 constLen.has_value() && *constLen <= 0) {
6312 // non-positive explicit length — skip overflow check
6313 } else {
6314 uint64_t lenInBytes = getLenInBytes();
6315 uint32_t granularity = targetModel.getAddressGenGranularity();
6316 if (granularity != 0) {
6317 uint64_t lenInWords = lenInBytes * 8 / granularity;
6318 uint64_t maxLen =
6319 targetModel.getDmaBdMaxLen(parentTile.getTileType());
6320 if (lenInWords > maxLen)
6321 return emitOpError()
6322 << "buffer descriptor length (" << lenInWords
6323 << " 32-bit words) exceeds the maximum of " << maxLen
6324 << " words supported by this tile type";
6325 }
6326 }
6327 }
6328 }
6329
6330 if (failed(verifyMixedSizesAndStrides()) || failed(verifyTransferInBounds()))
6331 return failure();
6332
6333 // Fold the mixed sizes/strides to a constant BDDimLayoutAttr list for
6334 // verification; a runtime size/stride yields nullopt plus a diagnostic.
6335 std::optional<llvm::SmallVector<BDDimLayoutAttr>> dims;
6336 if (!getMixedSizes().empty()) {
6337 dims = getConstantDimensions();
6338 if (!dims.has_value())
6339 return failure();
6340 }
6341 if (dims.has_value()) {
6342 // The per-BD ND access-pattern limit is a hardware property of the tile;
6343 // query it from the target model by tile type rather than inferring it
6344 // from the parent op type.
6345 size_t maxNDims = targetModel.getBDMaxDims(parentTile.getTileType());
6346 if (dims->size() > maxNDims)
6347 return emitOpError() << "Cannot give more than "
6348 << std::to_string(maxNDims)
6349 << " dimensions for step sizes and wraps on this "
6350 "tile (got "
6351 << std::to_string(dims->size()) << " dimensions).";
6352
6353 auto buffer = llvm::dyn_cast<MemRefType>(getBuffer().getType());
6354 if (!buffer)
6355 return emitOpError() << "dimensions attribute cannot be used with "
6356 "unranked memref buffer type.";
6357 // A contiguous row-major access on a shim tile is lowered to linear mode
6358 // by aie-dma-tasks-to-npu / aie-dma-to-npu, using the wide buffer_length
6359 // register which is exempt from the 10-bit ND wrap-size limit.
6360 // Skip the per-dimension size check when the BD is on a shim tile and the
6361 // access is contiguous, so the natural ND form can be written without
6362 // triggering a spurious verifier error before lowering.
6363 //
6364 // Note: the verifier early-exit above means we only reach this code when
6365 // the parent op is MemOp, MemTileDMAOp, ShimDMAOp, or DMAOp -- all of
6366 // which are TileElements, so parentTile is always non-null here.
6367 bool skipSizeCheck =
6368 parentTile.isShimTile() && xilinx::AIE::isContiguousBDTransfer(*dims);
6369
6370 // The wrap (size) and step (stride) field widths are tile-type specific
6371 // (e.g. on AIE2: core tiles have an 8-bit wrap, mem/shim tiles 10-bit).
6372 // Wrap fields are unbiased, so a W-bit wrap field admits sizes up to
6373 // 2^W - 1. Step fields are hardware-encoded as actual-1, so an S-bit
6374 // step field admits actual (unbiased, as declared here) strides up to
6375 // 2^S. Deriving the limits from the target model (instead of a single
6376 // hardcoded shim-sized constant) keeps this check correct for all tile
6377 // types, and computing the message from the same value it checks
6378 // against means the two can never disagree again. Unbiased (AIE4) steps
6379 // admit up to 2^S - 1.
6380 uint32_t wrapBits = targetModel.getDmaBdWrapBits(parentTile.getTileType());
6381 uint32_t stepBits = targetModel.getDmaBdStepBits(parentTile.getTileType());
6382 uint64_t maxSize = wrapBits > 0 ? (1ULL << wrapBits) - 1 : 0;
6383 uint64_t maxStride =
6384 stepBits > 0
6385 ? (1ULL << stepBits) - 1 +
6386 targetModel.getDmaBdStepBias(parentTile.getTileType())
6387 : 0;
6388
6389 for (BDDimLayoutAttr dim : *dims) {
6390 if (0 == dim.getStride() && dim.getSize() != 1)
6391 return emitOpError()
6392 << "Invalid step size; must be a positive integer.";
6393 if (dim.getStride() > buffer.getNumElements())
6394 return emitOpError() << "Step size " << std::to_string(dim.getStride())
6395 << " exceeds memref size "
6396 << std::to_string(buffer.getNumElements());
6397 if (!skipSizeCheck && dim.getSize() > maxSize)
6398 return emitOpError() << "Size may not exceed " << maxSize << ".";
6399 if (dim.getStride() > maxStride)
6400 return emitOpError() << "Stride may not exceed " << maxStride << ".";
6401 }
6402
6403 // Since streams read 32b words, there's no way to read eg 16b with stride
6404 // of 2 (ie lower halfs of each 32b). So force it to be 1 (and then in
6405 // CDODirect/XAIEV2 scale the size by 4/getBufferElementTypeWidthInBytes).
6406 if (getBufferElementTypeWidthInBytes() < 4 && dims->back().getStride() != 1)
6407 return emitOpError(
6408 "For <32b width datatypes, inner-most dim stride must be 1");
6409
6410 if (getBufferElementTypeWidthInBytes() > 4 && dims->back().getStride() != 1)
6411 return emitOpError(
6412 "For >32b width datatypes, inner-most dim stride must be 1");
6413
6414 // AIE4 BDs have no d0 step field, so a D0 stride would be dropped.
6415 if (const DmaBdLayout *layout =
6416 targetModel.getDmaBdLayout(parentTile.getTileType());
6417 layout && !layout->d0Stride.exists() && dims->back().getSize() > 1 &&
6418 dims->back().getStride() != 1)
6419 return emitOpError("AIE4 D0 stride is fixed by hardware and must be 1.");
6420
6421 // The hardware stepsize/wrap registers are denominated in 32-bit words.
6422 // lib/Targets/AIERT.cpp's static/CDO lowering converts element-
6423 // granularity strides/sizes to words by scaling by
6424 // elementWidthInBytes/4.0 and truncating via an unguarded static_cast;
6425 // when that scale factor isn't an integer, a declared value that isn't
6426 // itself a whole number of words is silently replaced by a different,
6427 // hardware-expressible value instead of being rejected. Reject those
6428 // values here instead, since they are genuinely inexpressible in the
6429 // hardware's word-granularity registers. The trigger condition is
6430 // "element width not a multiple of 4 bytes" rather than "< 4 bytes" so
6431 // that this also covers the `bfp` block-floating-point types, whose
6432 // widths (9 and 17 bytes) are >4 bytes but still not word multiples.
6433 // Dimensions with size == 1 are skipped: the loop runs once so stride is
6434 // never stepped and that dimension's size/stride do not affect hardware
6435 // address generation; word alignment is not required for them.
6436 //
6437 // Which dim is "innermost" is determined by the last dim with size > 1,
6438 // not by array position: `dims` is outermost-first, and trailing dims
6439 // with size == 1 (which never step) do not change which dim actually
6440 // performs the finest-granularity access. If every dim has size == 1,
6441 // there is no innermost dim to check and the whole block is skipped.
6442 int32_t elementWidthInBytes = getBufferElementTypeWidthInBytes();
6443 if (elementWidthInBytes % 4 != 0) {
6444 std::optional<size_t> effectiveInnermost;
6445 for (size_t i = 0; i < dims->size(); i++)
6446 if ((*dims)[i].getSize() > 1)
6447 effectiveInnermost = i;
6448 if (effectiveInnermost.has_value()) {
6449 for (size_t i = 0; i < dims->size(); i++) {
6450 BDDimLayoutAttr dim = (*dims)[i];
6451 if (dim.getSize() <= 1)
6452 continue;
6453 if (i == *effectiveInnermost) {
6454 // Effective innermost dim: the size (element count transferred
6455 // at this level) must itself be a whole number of 32-bit words.
6456 if ((dim.getSize() * elementWidthInBytes) % 4)
6457 return emitOpError()
6458 << "Innermost dim size (" << dim.getSize() << ") * "
6459 << elementWidthInBytes << "-byte element width = "
6460 << (dim.getSize() * elementWidthInBytes)
6461 << " bytes: innermost dim size must be a multiple of 4 "
6462 "bytes for sub-32b element types (the hardware size "
6463 "register is 32-bit-word granularity).";
6464 } else {
6465 // Dim outside the effective innermost dim: the stride (address
6466 // step between elements at this level) must itself be a whole
6467 // number of 32-bit words.
6468 if ((dim.getStride() * elementWidthInBytes) % 4)
6469 return emitOpError()
6470 << "Dim " << i << " stride (" << dim.getStride() << ") * "
6471 << elementWidthInBytes << "-byte element width = "
6472 << (dim.getStride() * elementWidthInBytes)
6473 << " bytes: non-innermost dim stride must be a multiple "
6474 "of 4 bytes for sub-32b element types (the hardware "
6475 "stepsize register is 32-bit-word granularity).";
6476 }
6477 }
6478 }
6479 }
6480 }
6481 if (auto paddims = getPadDimensions(); paddims.has_value()) {
6482 if (!dims.has_value())
6483 return emitOpError() << "Padding requires n-d data layouts expressed as"
6484 << " wrap(s) and stride(s).";
6485 const DmaBdLayout *layout =
6486 targetModel.getDmaBdLayout(parentTile.getTileType());
6487 llvm::SmallVector<std::pair<DmaBdField, DmaBdField>, 3> padFields;
6488 if (layout)
6489 padFields = layout->padFields();
6490 if (padFields.empty())
6491 return emitOpError() << "Padding is only supported by memtile dma bds.";
6492 if (dims->size() != paddims->size())
6493 return emitOpError() << "Mismatch number of dimensions between padding(s)"
6494 << " and wrap(s) and stride(s).";
6495 size_t numPadded = padFields.size();
6496 for (auto [d, pad] : llvm::enumerate(llvm::reverse(*paddims)))
6497 if (d >= numPadded && (pad.getConstPadBefore() || pad.getConstPadAfter()))
6498 return emitOpError()
6499 << "a " << paddims->size() << "-dimensional walk pads only its "
6500 << numPadded << " innermost dimensions";
6501 int actuallen = 1;
6502 for (unsigned i = 0; i < paddims->size(); i++) {
6503 auto dim = (*dims)[i];
6504 auto paddim = (*paddims)[i];
6505 actuallen *= paddim.getConstPadBefore() + paddim.getConstPadAfter() +
6506 dim.getSize();
6507 if (std::optional<int32_t> len = getConstantLen(); len.has_value()) {
6508 if (actuallen > *len)
6509 return emitOpError() << "Data exceeds len after padding.";
6510 } else if (getLen()) {
6511 return emitOpError()
6512 << "Padding with a runtime len operand is not yet supported; "
6513 "use a compile-time constant len with padded BDs.";
6514 }
6515 }
6516 if ((paddims->back().getConstPadBefore() *
6517 getBufferElementTypeWidthInBytes()) %
6518 4)
6519 return emitOpError() << "Inner-most padding-before count must result in"
6520 << " padding in 32-bit words.";
6521 if ((paddims->back().getConstPadAfter() *
6522 getBufferElementTypeWidthInBytes()) %
6523 4)
6524 return emitOpError() << "Inner-most padding-after count must result in"
6525 << " padding in 32-bit words.";
6526 for (auto [d, pad] : llvm::enumerate(llvm::reverse(*paddims))) {
6527 if (d >= numPadded)
6528 break;
6529 int64_t before = pad.getConstPadBefore();
6530 int64_t after = pad.getConstPadAfter();
6531 if (d == 0) {
6532 before = before * getBufferElementTypeWidthInBytes() / 4;
6533 after = after * getBufferElementTypeWidthInBytes() / 4;
6534 }
6535 uint32_t maxBefore = padFields[d].first.mask();
6536 uint32_t maxAfter = padFields[d].second.mask();
6537 if (before > maxBefore || after > maxAfter)
6538 return emitOpError()
6539 << "D" << d << " pad_before/pad_after exceeds the [0:"
6540 << (before > maxBefore ? maxBefore : maxAfter) << "] range"
6541 << (d == 0 ? " of 32-bit words." : ".");
6542 }
6543 }
6544 if (!isUnrankedMemRef &&
6545 (parentTile.isMemTile() || parentTile.isCoreTile())) {
6546 // Only a shim DMA reaches an aie.external_buffer.
6547 auto bufferOp = getBuffer().getDefiningOp<BufferOp>();
6548 if (!bufferOp)
6549 return emitOpError("Memtile and core tile DMAs can only access an "
6550 "aie.buffer, not an aie.external_buffer.");
6551 if (auto baseAddr = bufferOp.getAddress(); baseAddr.has_value()) {
6552 int64_t offsetInBytes = *baseAddr + getOffsetInBytes();
6553 if (offsetInBytes % 4)
6554 return emitOpError("bd address must be 4 byte (32b) aligned; got "
6555 "base+offset: ")
6556 << offsetInBytes << " (bytes)";
6557 }
6558 }
6559 if (auto packetInfo = getPacket()) {
6560 if (failed(verifyAssignedPacket(*this, *packetInfo)))
6561 return failure();
6562 if (packetInfo->getPktType() > 7)
6563 return emitOpError("Packet type field can only hold 3 bits.");
6564 if (packetInfo->assignedId() >
6565 getTargetModel(getOperation()).getMaxPacketId())
6566 return emitOpError("Packet ID field can only hold 5 bits.");
6567 }
6568
6569 if (failed(verifyDMABDOutOfOrderId(*this)))
6570 return failure();
6571
6572 // A runtime len operand or the static_len attribute both count as having a
6573 // length here.
6574 if (!hasLen() && !getBuffer().getType().hasStaticShape())
6575 return emitOpError() << "buffer with dynamic shape requires static length.";
6576
6577 if (getBurstLength() != 0 && !parentTile.isShimNOCTile())
6578 return emitOpError("Burst length is only supported in Shim NOC tiles that "
6579 "are connected to the memory-mapped NOC.");
6580
6581 if (auto axcache = getAxcache()) {
6582 if (!parentTile.isShimNOCTile()) {
6583 return emitOpError("AxCACHE is only supported in Shim NOC tiles "
6584 "that are connected to the memory-mapped NOC.");
6585 }
6586 if (axcache > 0xF) {
6587 return emitOpError("AxCache value out of 4-bit range.");
6588 }
6589 }
6590
6591 return verifyDMABDIteration(*this, parentTile.getTileType());
6592}
6593
6594LogicalResult DMABDPACKETOp::verify() {
6595 // Both fields read back signed (AIEI32Attr), so the range is two-sided even
6596 // though the hardware fields are unsigned: aie.dma_bd_packet(-1, -1) parses.
6597 if (getPacketType() < 0 || getPacketType() > 7)
6598 return emitOpError("Packet type field can only hold 3 bits.");
6599 if (getPacketID() < 0 ||
6600 getPacketID() >
6601 static_cast<int32_t>(getTargetModel(getOperation()).getMaxPacketId()))
6602 return emitOpError("Packet ID field can only hold 5 bits.");
6603 return success();
6604}
6605
6606std::optional<int64_t> DMABDOp::getStaticLenInBytes() {
6607 int64_t elems;
6608 if (std::optional<int32_t> len = getConstantLen()) {
6609 elems = static_cast<uint32_t>(*len);
6610 } else {
6611 // With runtime sizes/strides, an omitted len is their inner extent
6612 // (AIEDMATasksToNPU), not the whole buffer.
6613 if (hasLen() || !getSizes().empty() || !getStrides().empty())
6614 return std::nullopt;
6615 auto buffer = dyn_cast<MemRefType>(getBuffer().getType());
6616 if (!buffer || !buffer.hasStaticShape())
6617 return std::nullopt;
6618 elems = buffer.getNumElements();
6619 }
6620 return llvm::checkedMul(
6621 elems, static_cast<int64_t>(getBufferElementTypeWidthInBytes()));
6622}
6623
6624uint32_t DMABDOp::getAxcacheOrDefault() {
6625 return getAxcache().value_or(
6626 getTargetModel(getOperation()).getDefaultAxCache());
6627}
6628
6629//===----------------------------------------------------------------------===//
6630// DMAStartOp
6631//===----------------------------------------------------------------------===//
6632
6633static LogicalResult FoldDMAStartOp(DMAStartOp op, PatternRewriter &rewriter) {
6634
6635 llvm::SetVector<Block *> reachable;
6636 SmallVector<Block *, 16> worklist;
6637 Block *firstBD = op.getSuccessor(0);
6638 reachable.insert(firstBD);
6639 worklist.push_back(firstBD);
6640 while (!worklist.empty()) {
6641 Block *block = worklist.pop_back_val();
6642 if (block->empty())
6643 continue;
6644 auto successors = block->getTerminator()->getSuccessors();
6645 for (auto *i : successors) {
6646 if (!reachable.contains(i)) {
6647 reachable.insert(i);
6648 worklist.push_back(i);
6649 }
6650 }
6651 }
6652
6653 // BD chain ends with an EndOp, indicating non-repeating pattern: BD chain
6654 // folding not applicable.
6655 if (isa<EndOp>((reachable.back())->getTerminator()))
6656 return failure();
6657
6658 // Check for identical bds.
6659 auto areEquivalentBDs = [](Block *b1, Block *b2) {
6660 auto b1OpRange = b1->without_terminator();
6661 auto b2OpRange = b2->without_terminator();
6662 if (llvm::range_size(b1OpRange) != llvm::range_size(b2OpRange))
6663 return false;
6664 if (!llvm::all_of(llvm::zip_equal(b1OpRange, b2OpRange),
6665 [](std::tuple<Operation &, Operation &> pair) {
6666 return OperationEquivalence::isEquivalentTo(
6667 &std::get<0>(pair), &std::get<1>(pair),
6668 OperationEquivalence::IgnoreLocations);
6669 }))
6670 return false;
6671 return true;
6672 };
6673
6674 // Get a vector of unique BDs.
6675 SmallVector<Block *> uniquePattern;
6676 const auto *patternIt = reachable.begin();
6677 while (patternIt != reachable.end() &&
6678 llvm::none_of(uniquePattern, [patternIt, areEquivalentBDs](Block *b1) {
6679 return areEquivalentBDs(*patternIt, b1);
6680 })) {
6681 uniquePattern.push_back(*patternIt);
6682 patternIt++;
6683 }
6684
6685 // No block repeats, so there is no sub-chain to collapse.
6686 if (patternIt == reachable.end())
6687 return failure();
6688
6689 unsigned idx = 0;
6690 while (patternIt != reachable.end()) {
6691 // BD repetition found. Check if repeating pattern.
6692 if (!areEquivalentBDs(*patternIt, uniquePattern[idx]))
6693 return failure();
6694 patternIt++;
6695 idx = (idx + 1) % uniquePattern.size();
6696 }
6697
6698 // Repeating BD chains detected. Erasing repetitions.
6699 auto lastBDTerm = cast<NextBDOp>(reachable.back()->getTerminator());
6700 auto lastUniqueBDTerm = cast<NextBDOp>(uniquePattern.back()->getTerminator());
6701 rewriter.modifyOpInPlace(lastUniqueBDTerm, [&] {
6702 lastUniqueBDTerm.setSuccessor(lastBDTerm.getSuccessor());
6703 });
6704
6705 return success();
6706}
6707
6708// Canonicalization pattern for DMABDOp: on shim tiles, fold a contiguous
6709// row-major ND access pattern into canonical linear form (no dimensions
6710// attribute), so that the hardware uses the wide buffer_length register.
6711namespace {
6712struct LinearizeContiguousBDTransfer : public mlir::OpRewritePattern<DMABDOp> {
6713 using OpRewritePattern::OpRewritePattern;
6714
6715 mlir::LogicalResult
6716 matchAndRewrite(DMABDOp op, mlir::PatternRewriter &rewriter) const override {
6717 if (op.getStaticSizes().value_or(llvm::ArrayRef<int64_t>{}).empty())
6718 return mlir::failure();
6719
6720 // Only fire for shim DMA BDs: ExternalBufferOp buffer
6721 // (dma_configure_task_for stage), parent TileElement is shim
6722 // (dma_configure_task stage), or inside ShimDMAOp (after full lowering).
6723 bool bufferIsExternal =
6724 isa_and_nonnull<ExternalBufferOp>(op.getBuffer().getDefiningOp());
6725 TileElement parentElem = getParentTileElement(op.getOperation());
6726 TileLike parentTileLike =
6727 parentElem ? parentElem.getTileLike() : TileLike{};
6728 bool parentIsShim = parentTileLike && parentTileLike.isShimTile();
6729 bool inShimDMA = (bool)op->getParentOfType<ShimDMAOp>();
6730 if (!bufferIsExternal && !parentIsShim && !inShimDMA)
6731 return mlir::failure();
6732
6733 // Only ND dimensions that are all-constant can be linearized; decline
6734 // silently on runtime-valued sizes/strides so valid dynamic IR doesn't get
6735 // a spurious diagnostic.
6736 auto isConstant = [](mlir::Value v) {
6737 return mlir::getConstantIntValue(v).has_value();
6738 };
6739 if (!llvm::all_of(op.getSizes(), isConstant) ||
6740 !llvm::all_of(op.getStrides(), isConstant))
6741 return mlir::failure();
6742 std::optional<llvm::SmallVector<BDDimLayoutAttr>> dims =
6743 op.getFoldedDimensions([&]() { return op.emitError(); });
6744 if (!dims.has_value() || dims->empty())
6745 return mlir::failure();
6747 return mlir::failure();
6748 // Already linear (single dimension with stride 1)?
6749 if (dims->size() == 1 && dims->front().getStride() == 1)
6750 return mlir::failure();
6751
6752 int64_t product = 1;
6753 for (BDDimLayoutAttr dim : *dims)
6754 product *= dim.getSize();
6755
6756 // len < product: the outermost dim describes a hardware BD iteration
6757 // (preserved downstream as iteration_size/stride). Don't fold it away.
6758 // A runtime len can't be compared, so bail. Also bail if len is absent but
6759 // the buffer is unranked (can't safely infer product == full transfer).
6760 if (!op.hasLen() && !op.getBuffer().getType().hasStaticShape())
6761 return mlir::failure();
6762 std::optional<int32_t> lenVal = op.getConstantLen();
6763 if (lenVal.has_value() && static_cast<int64_t>(*lenVal) != product)
6764 return mlir::failure();
6765 int32_t len = static_cast<int32_t>(product);
6766
6767 // Rewrite to a linear BD: len as the static_len attribute, sizes/strides
6768 // cleared. Other attributes are preserved.
6769 rewriter.modifyOpInPlace(op, [&]() {
6770 op.getLenMutable().clear();
6771 op.setStaticLen(len);
6772 op.getSizesMutable().clear();
6773 op.getStridesMutable().clear();
6774 op.setStaticSizes(std::nullopt);
6775 op.setStaticStrides(std::nullopt);
6776 });
6777 return mlir::success();
6778 }
6779};
6780} // namespace
6781
6782// Canonicalization pattern for DMABDOp: fold a constant offset/len/size/stride
6783// operand back into the corresponding static_* attribute, removing the operand.
6784namespace {
6785struct FoldConstantBDDimList : public mlir::OpRewritePattern<DMABDOp> {
6786 using OpRewritePattern::OpRewritePattern;
6787
6788 mlir::LogicalResult
6789 matchAndRewrite(DMABDOp op, mlir::PatternRewriter &rewriter) const override {
6790 if (op.getSizes().empty() && op.getStrides().empty() && !op.getOffset() &&
6791 !op.getLen())
6792 return mlir::failure();
6793 llvm::SmallVector<mlir::OpFoldResult> sizes = op.getMixedSizes();
6794 llvm::SmallVector<mlir::OpFoldResult> strides = op.getMixedStrides();
6795 // foldDynamicIndexList returns success() only if it replaced a dynamic
6796 // entry with a constant. Bitwise (not logical) OR is deliberate: both
6797 // calls must run unconditionally, so strides still folds even once
6798 // sizes already succeeded.
6799 // NOLINTNEXTLINE(clang-diagnostic-bitwise-instead-of-logical)
6800 bool changed = succeeded(mlir::foldDynamicIndexList(sizes)) |
6801 succeeded(mlir::foldDynamicIndexList(strides));
6802
6803 // Fold a constant offset/len operand into its static_* attribute.
6804 std::optional<int32_t> foldOffset, foldLen;
6805 if (op.getOffset())
6806 if (auto c = mlir::getConstantIntValue(op.getOffset()))
6807 foldOffset = static_cast<int32_t>(*c);
6808 if (op.getLen())
6809 if (auto c = mlir::getConstantIntValue(op.getLen()))
6810 foldLen = static_cast<int32_t>(*c);
6811 changed |= foldOffset.has_value() || foldLen.has_value();
6812
6813 if (!changed)
6814 return mlir::failure();
6815
6816 llvm::SmallVector<int64_t> staticSizes, staticStrides;
6817 llvm::SmallVector<mlir::Value> dynSizes, dynStrides;
6818 mlir::dispatchIndexOpFoldResults(sizes, dynSizes, staticSizes);
6819 mlir::dispatchIndexOpFoldResults(strides, dynStrides, staticStrides);
6820
6821 // Without `len`, a BD with runtime dims transfers their d0*d1*d2 extent,
6822 // but a fully static one transfers its whole buffer. Pin the extent
6823 // before the last runtime dim folds away so the transfer keeps its size.
6824 bool wasDynamic = !op.getSizes().empty() || !op.getStrides().empty();
6825 if (!op.hasLen() && wasDynamic && dynSizes.empty() && dynStrides.empty() &&
6826 !staticSizes.empty()) {
6827 int64_t extent = 1;
6828 for (int64_t s : llvm::ArrayRef(staticSizes).take_back(3))
6829 extent *= s;
6830 foldLen = static_cast<int32_t>(extent);
6831 }
6832
6833 rewriter.modifyOpInPlace(op, [&]() {
6834 op.getSizesMutable().assign(dynSizes);
6835 op.getStridesMutable().assign(dynStrides);
6836 // Leave the static arrays unset when there is no ND layout so they elide.
6837 if (staticSizes.empty())
6838 op.removeStaticSizesAttr();
6839 else
6840 op.setStaticSizes(staticSizes);
6841 if (staticStrides.empty())
6842 op.removeStaticStridesAttr();
6843 else
6844 op.setStaticStrides(staticStrides);
6845 if (foldOffset) {
6846 op.getOffsetMutable().clear();
6847 op.setStaticOffset(foldOffset);
6848 }
6849 if (foldLen) {
6850 op.getLenMutable().clear();
6851 op.setStaticLen(foldLen);
6852 }
6853 });
6854 return mlir::success();
6855 }
6856};
6857} // namespace
6858
6859void DMABDOp::getCanonicalizationPatterns(RewritePatternSet &results,
6860 MLIRContext *context) {
6861 results.add<FoldConstantBDDimList, LinearizeContiguousBDTransfer>(context);
6862}
6863
6864void DMAStartOp::getCanonicalizationPatterns(RewritePatternSet &results,
6865 MLIRContext *context) {
6866 results.add(FoldDMAStartOp);
6867}
6868
6869RouteEndpointOp DMAStartOp::getEndpointOp() {
6870 FlatSymbolRefAttr name = getEndpoint();
6871 if (!name)
6872 return nullptr;
6873 return SymbolTable::lookupNearestSymbolFrom<RouteEndpointOp>(*this, name);
6874}
6875
6876LogicalResult DMAStartOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
6877 FlatSymbolRefAttr name = getEndpoint();
6878 if (!name)
6879 return success();
6880 auto program = dyn_cast<DmaBody>((*this)->getParentOp());
6881 auto device = (*this)->getParentOfType<DeviceOp>();
6882 if (!program || !device)
6883 return emitOpError("only a tile's DMA program may name its channel by a "
6884 "route endpoint");
6885 auto endpoint = symbolTable.lookupSymbolIn<RouteEndpointOp>(device, name);
6886 if (!endpoint)
6887 return emitOpError() << name << " is not an aie.route_endpoint";
6888 if (endpoint.getBundle() != WireBundle::DMA)
6889 return emitOpError() << name << " names a "
6890 << stringifyWireBundle(endpoint.getBundle())
6891 << " port, not a DMA channel";
6892 auto here = cast<TileLike>(program.getTile().getDefiningOp());
6893 TileLike there = endpoint.getTileLike();
6894 bool sameTile = endpoint.getTile() == program.getTile() ||
6895 (here.tryGetCol() && here.tryGetRow() &&
6896 here.tryGetCol() == there.tryGetCol() &&
6897 here.tryGetRow() == there.tryGetRow());
6898 if (!sameTile)
6899 return emitOpError() << name
6900 << " is on a different tile than this DMA program";
6901 return success();
6902}
6903
6904LogicalResult DMAStartOp::verify() {
6905 if (getPadValue() != 0) {
6906 if (!isa<MemTileDMAOp>(getOperation()->getParentOp()))
6907 return emitOpError("pad_value is only supported on memtile DMA channels");
6908 if (getChannelDir() != DMAChannelDir::MM2S)
6909 return emitOpError("pad_value is only supported on MM2S DMA channels");
6910 if (!getTargetModel(getOperation()).isMemTilePadValueSupported())
6911 return emitOpError("pad_value requires the CONSTANT_PAD_VALUE register, "
6912 "unavailable on this target");
6913 }
6914 if (auto program = dyn_cast<TileElement>((*this)->getParentOp());
6915 program && !getEndpoint())
6917 getOperation(), program.getTileLike(), getChannelDir(),
6918 getChannelIndex())))
6919 return failure();
6920 if (failed(verifyDMARepeatCount(getOperation(), getRepeatCount())))
6921 return failure();
6922 if (auto program = dyn_cast<DmaBody>((*this)->getParentOp());
6923 program && !getEndpoint() &&
6924 failed(verifyDMAChannelIndex(
6925 getOperation(), cast<TileLike>(program.getTile().getDefiningOp()),
6926 getChannelDir(), getChannelIndex())))
6927 return failure();
6928 SmallVector<DMABDOp> bds;
6929 if (getOutOfOrder()) {
6930 llvm::SmallPtrSet<Block *, 8> visited;
6931 for (Block *b = getDest(); b && visited.insert(b).second;
6932 b = b->getNumSuccessors() > 0 ? b->getSuccessor(0) : nullptr)
6933 llvm::append_range(bds, b->getOps<DMABDOp>());
6934 }
6935 return verifyOutOfOrderChannel(getOperation(), getChannelDir(),
6936 getOutOfOrder(), bds);
6937}
6938
6939//===----------------------------------------------------------------------===//
6940// SwitchboxOp
6941//===----------------------------------------------------------------------===//
6942
6943LogicalResult SwitchboxOp::verify() {
6944 // The remaining checks (port bounds, legal-connection rules) are all keyed
6945 // off the target model for a placed tile. Before --aie-place-tiles runs the
6946 // tile is still an aie.logical_tile, so defer those checks to the
6947 // post-placement re-verify -- mirroring how UsesAreAccessible and FlowOp
6948 // skip target-model checks on logical tiles.
6949 if (!isa<TileOp>(getTile().getDefiningOp()))
6950 return success();
6951
6952 Region &body = getConnections();
6953 DenseSet<Port> sourceset;
6954 DenseSet<Port> destset;
6955 auto tile = getTileOp();
6956 const auto &targetModel = getTargetModel(tile);
6957 if (body.empty())
6958 return emitOpError("should have non-empty body");
6959 // A circuit connection claims its source port wherever it appears.
6960 for (auto connectOp : body.front().getOps<ConnectOp>())
6961 sourceset.insert({connectOp.getSourceBundle(), connectOp.sourceIndex()});
6962 for (auto &ops : body.front()) {
6963 // Would be simpler if this could be templatized.
6964 auto checkBound = [&ops](StringRef dir, WireBundle bundle, int index,
6965 int bound) -> LogicalResult {
6966 if (index >= bound) {
6967 if (bound > 0)
6968 return ops.emitOpError("index ")
6969 << index << " for " << dir << " bundle "
6970 << stringifyWireBundle(bundle) << " must be less than "
6971 << bound;
6972 return ops.emitOpError()
6973 << dir << " bundle " << stringifyWireBundle(bundle)
6974 << " not supported; index: " << index << ", bound: " << bound;
6975 }
6976 return success();
6977 };
6978
6979 if (auto connectOp = dyn_cast<ConnectOp>(ops)) {
6980 Port source = {connectOp.getSourceBundle(), connectOp.sourceIndex()};
6981
6982 Port dest = {connectOp.getDestBundle(), connectOp.destIndex()};
6983 if (destset.count(dest)) {
6984 return connectOp.emitOpError()
6985 << "; connecting " << to_string(source) << " to "
6986 << to_string(dest) << " on "
6987 << to_string(this->getTileOp().getTileID())
6988 << " targets same dst as another connect op; existing "
6989 "destinations: "
6990 << llvm::join(llvm::map_range(
6991 destset, [](auto &p) { return to_string(p); }),
6992 ", ");
6993 }
6994 destset.insert(dest);
6995
6996 if (connectOp.sourceIndex() < 0)
6997 return connectOp.emitOpError("source index cannot be less than zero");
6998
6999 if (checkBound("source", connectOp.getSourceBundle(),
7000 connectOp.sourceIndex(),
7001 getNumSourceConnections(connectOp.getSourceBundle()))
7002 .failed())
7003 return failure();
7004
7005 if (connectOp.destIndex() < 0)
7006 return connectOp.emitOpError("dest index cannot be less than zero");
7007
7008 if (checkBound("dest", connectOp.getDestBundle(), connectOp.destIndex(),
7009 getNumDestConnections(connectOp.getDestBundle()))
7010 .failed())
7011 return failure();
7012
7013 // Stream switch connection constraints
7014 if (!isLegalTileConnection(tile, targetModel, connectOp))
7015 return connectOp.emitOpError("illegal stream switch connection");
7016
7017 } else if (auto connectOp = dyn_cast<MasterSetOp>(ops)) {
7018 Port dest = {connectOp.getDestBundle(), connectOp.destIndex()};
7019 if (destset.count(dest))
7020 return connectOp.emitOpError("targets same destination ")
7021 << stringifyWireBundle(dest.bundle) << ": " << dest.channel
7022 << " as another connect or masterset operation";
7023 destset.insert(dest);
7024
7025 if (connectOp.destIndex() < 0)
7026 return connectOp.emitOpError("dest index cannot be less than zero");
7027
7028 if (checkBound("dest", connectOp.getDestBundle(), connectOp.destIndex(),
7029 getNumDestConnections(connectOp.getDestBundle()))
7030 .failed())
7031 return failure();
7032
7033 // The single-arbiter invariant is checked by MasterSetOp::verify.
7034 } else if (auto connectOp = dyn_cast<PacketRulesOp>(ops)) {
7035 Port source = {connectOp.getSourceBundle(), connectOp.sourceIndex()};
7036 if (sourceset.count(source))
7037 return connectOp.emitOpError("packet switched source ")
7038 << stringifyWireBundle(source.bundle) << source.channel
7039 << " cannot match another connect or masterset operation";
7040 sourceset.insert(source);
7041
7042 } else if (auto amselOp = dyn_cast<AMSelOp>(ops)) {
7043 std::vector<MasterSetOp> mstrs;
7044 std::vector<PacketRulesOp> slvs;
7045 for (auto *user : amselOp.getResult().getUsers()) {
7046 if (auto s = dyn_cast<PacketRuleOp>(user)) {
7047 auto pktRules = cast<PacketRulesOp>(s->getParentOp());
7048 slvs.push_back(pktRules);
7049 } else if (auto m = dyn_cast<MasterSetOp>(user))
7050 mstrs.push_back(m);
7051 }
7052 for (auto m : mstrs) {
7053 for (auto s : slvs) {
7054 // Stream switch connection constraints
7055 if (!isLegalTileConnection(tile, targetModel, m, s)) {
7056 return amselOp->emitOpError("illegal stream switch connection");
7057 }
7058 }
7059 }
7060 } else if (isa<EndOp>(ops)) {
7061 // continue;
7062 } else {
7063 return ops.emitOpError("cannot be contained in a Switchbox op");
7064 }
7065 }
7066
7067 return success();
7068}
7069
7070template <typename... ParentOpTypes>
7072 static LogicalResult verifyTrait(Operation *op) {
7073 Operation *operation = op->getParentOp();
7074 while (operation) {
7075 if (llvm::isa_and_nonnull<ParentOpTypes...>(operation))
7076 return success();
7077 operation = operation->getParentOp();
7078 }
7079 return failure();
7080 }
7081};
7082
7083TileOp LockOp::getTileOp() {
7084 return cast<TileElement>(this->getOperation()).getTileOp();
7085}
7086
7087LogicalResult LockOp::verify() {
7088 if (auto result = UsesAreAccessible::verifyTrait(*this); result.failed())
7089 return result;
7090
7091 if (auto lockID = getLockID()) {
7092 TileLike tileLike = getTileLike();
7093 if (!tileLike)
7094 return emitOpError("tile operand must implement TileLike interface");
7095 const auto &targetModel = getTargetModel(*this);
7096 auto tileType = tileLike.getTileType();
7097 if (int numLocks = targetModel.getNumLocks(tileType); *lockID >= numLocks)
7098 return emitOpError("lock assigned invalid id (maximum is ")
7099 << numLocks - 1 << ")";
7100 }
7101
7102 if (std::optional<int32_t> init = getInit()) {
7103 int64_t max = getTargetModel(*this).getMaxLockValue();
7104 if (*init < 0 || *init > max)
7105 return emitOpError("init value ")
7106 << *init << " is outside the lock's range [0, " << max << "]";
7107 }
7108
7109 return success();
7110}
7111
7112// Look up for compile-time constant lock values, if any.
7113// Returns std::nullopt if lock value does not reference an `arith.constant`.
7114static std::optional<int32_t> getConstantLockValue(UseLockOp op) {
7115 if (auto constant = op.getValue().getDefiningOp<arith::ConstantOp>())
7116 if (auto intAttr = llvm::dyn_cast<IntegerAttr>(constant.getValue()))
7117 return (int32_t)intAttr.getInt();
7118 return std::nullopt;
7119}
7120
7122 static LogicalResult verifyTrait(Operation *op) {
7123 auto *block = op->getBlock();
7124 int lockID = -1;
7125 for (auto op : block->getOps<UseLockOp>()) {
7126 // A sibling whose lock is not an aie.lock is rejected by its own
7127 // verifier.
7128 if (auto lock = op.getLock().getDefiningOp<LockOp>();
7129 lock && lock.getLockID().has_value()) {
7130 if (lockID != -1 && lockID != lock.getLockIDValue())
7131 return failure();
7132 lockID = lock.getLockIDValue();
7133 }
7134 }
7135 return success();
7136 }
7137};
7138
7140 static LogicalResult verifyTrait(Operation *op) {
7141 auto *block = op->getBlock();
7142 int acqValue = -1, relValue = -1;
7143 for (auto op : block->getOps<UseLockOp>()) {
7144 // Non-constant lock values cannot be compared here; the passes that
7145 // require a constant enforce that separately via getConstantValue().
7146 auto value = getConstantLockValue(op);
7147 if (!value)
7148 continue;
7149 if (op.acquire() || op.acquireGE()) {
7150 if (acqValue != -1 && acqValue != *value) {
7151 return failure();
7152 }
7153 acqValue = *value;
7154 } else if (op.release()) {
7155 if (relValue != -1 && relValue != *value) {
7156 return failure();
7157 }
7158 relValue = *value;
7159 }
7160 }
7161 return success();
7162 }
7163};
7164
7166 static LogicalResult verifyTrait(Operation *op) {
7167 if (auto memOp = op->getParentOfType<MemOp>()) {
7168 auto useLock = cast<UseLockOp>(op);
7169 if (auto lock = useLock.getLockOp(); lock.getTile() != memOp.getTile())
7170 return failure();
7171 }
7172 return success();
7173 }
7174};
7175
7176// Whether `op` is in an aiex.dma_configure_task(_for). Checked by name to avoid
7177// a dependency on the AIEX dialect.
7178static bool isInRuntimeDmaTask(Operation *op) {
7179 for (Operation *parent = op->getParentOp(); parent;
7180 parent = parent->getParentOp()) {
7181 StringRef name = parent->getName().getStringRef();
7182 if (name == "aiex.dma_configure_task" ||
7183 name == "aiex.dma_configure_task_for")
7184 return true;
7185 }
7186 return false;
7187}
7188
7189LogicalResult UseLockOp::verify() {
7190 // AIE.useLock cannot be used at the top level
7191 if (llvm::isa_and_nonnull<DeviceOp, ModuleOp>((*this)->getParentOp()))
7192 return (*this)->emitOpError("must be used in a core or memory operation.");
7193
7194 bool inDmaBlock =
7196 .succeeded();
7197 // A BD's lock fields are programmed from the aie.lock. In a core or a
7198 // function the operand is a lock ID that may be a runtime value
7199 // (--aie-localize-locks makes it a constant index), so it is not checked.
7200 if ((inDmaBlock || isInRuntimeDmaTask(*this)) &&
7201 !getLock().getDefiningOp<LockOp>())
7202 return (*this)->emitOpError("lock operand is not an aie.lock");
7203
7204 const auto &targetModel = getTargetModel(*this);
7205 if (targetModel.getTargetArch() == AIEArch::AIE1 && acquireGE())
7206 return (*this)->emitOpError(
7207 "AcquireGreaterEqual is not supported in AIE1.");
7208
7209 // Locks used inside a DMA/BD block are configured via static register writes
7210 // and therefore require a compile-time constant value.
7211 if (inDmaBlock && !getConstantLockValue(*this))
7212 return (*this)->emitOpError(
7213 "lock value in a DMA/BD block must be a compile-time constant "
7214 "(defined by an arith.constant).");
7215
7216 // Otherwise, AIE.useLock should be inside MemOp, MemTileDMAOp, or
7217 // ShimDMAOp,
7218 if (inDmaBlock) {
7219 if (!(*this)->getBlock())
7220 return (*this)->emitOpError("is not in a block.");
7221
7222 if (targetModel.getTargetArch() == AIEArch::AIE1 &&
7223 UsesOneLockInDMABlock::verifyTrait(*this).failed())
7224 return (*this)->emitOpError(
7225 "used in a DMA block that have multiple locks.");
7226
7228 return (*this)->emitOpError("acquires/releases the lock in a DMA block "
7229 "from/to multiple states.");
7230
7231 if (HasSomeParent<MemOp>::verifyTrait(*this).succeeded() &&
7232 AccessesLocalLocks::verifyTrait(*this).failed())
7233 return (*this)->emitOpError("can only access a lock in the same tile");
7234 return success();
7235
7236 // Or it can be in a CoreOp, or some FuncOp called from a CoreOp
7237 }
7238 if (HasSomeParent<CoreOp, func::FuncOp>::verifyTrait(*this).succeeded()) {
7239 return success();
7240 }
7241 // Or it can be in a DMAConfigureTaskOp or DMAConfigureTaskForOp (for runtime
7242 // DMA configuration).
7243 if (isInRuntimeDmaTask(*this))
7244 return success();
7245 return (*this)->emitOpError()
7246 << "expects some parent op to be one of "
7247 << "AIE::device, AIE::core, func::func, AIE::mem, AIE::shimDMA, or "
7248 "AIEX::dma_configure_task";
7249}
7250
7251#include "aie/Dialect/AIE/IR/AIEEnums.cpp.inc"
7252#include "aie/Dialect/AIE/IR/AIEInterfaces.cpp.inc"
7253
7254//===----------------------------------------------------------------------===//
7255// TraceEventAttr
7256//===----------------------------------------------------------------------===//
7257
7258// Custom parser for TraceEventAttr value (uses shared helper)
7259static ParseResult parseTraceEventValue(AsmParser &parser, Attribute &value) {
7260 return xilinx::AIE::parseTraceEvent(parser, value);
7261}
7262
7263// Custom printer for TraceEventAttr value (uses shared helper)
7264static void printTraceEventValue(AsmPrinter &printer, Attribute value) {
7265 xilinx::AIE::printTraceEventEnum(printer, value);
7266}
7267
7268// Custom parser for TraceEventAttr value (uses shared helper)
7269static ParseResult parseTraceRegValue(OpAsmParser &parser, Attribute &value) {
7270
7271 // Try to parse as number
7272 int64_t intValue;
7273 OptionalParseResult parseResult = parser.parseOptionalInteger(intValue);
7274 if (parseResult.has_value() && succeeded(parseResult.value())) {
7275 MLIRContext *ctx = parser.getContext();
7276 value = IntegerAttr::get(IntegerType::get(ctx, 32), intValue);
7277 return success();
7278 }
7279 return xilinx::AIE::parseTraceEvent(parser, value);
7280}
7281
7282// Custom printer for TraceEventAttr value (uses shared helper)
7283static void printTraceRegValue(OpAsmPrinter &printer, Operation *op,
7284 Attribute value) {
7285 // if it's an intattr
7286 if (auto intAttr = llvm::dyn_cast<IntegerAttr>(value)) {
7287 printer << intAttr.getInt();
7288 return;
7289 }
7290 xilinx::AIE::printTraceEventEnum(printer, value);
7291}
7292
7293// Helper to parse a LockBlocking enum keyword.
7294#define GET_OP_CLASSES
7295#include "aie/Dialect/AIE/IR/AIEOps.cpp.inc"
7296
7297FailureOr<int32_t> UseLockOp::getConstantValue() {
7298 if (auto value = getConstantLockValue(*this))
7299 return *value;
7300 return emitOpError("expected the lock value to be a compile-time constant "
7301 "(defined by an arith.constant).");
7302}
7303
7304LogicalResult UseLockOp::canonicalize(UseLockOp op, PatternRewriter &rewriter) {
7305 // An AcquireGreaterEqual by a compile-time-constant 0 is a no-op: the lock is
7306 // already >= 0 (semaphore values are non-negative) and it decrements the lock
7307 // by 0. A buffer descriptor's acquire is kept: its release needs the pair.
7308 if (op.acquireGE() && op->getBlock()->getOps<DMABDOp>().empty()) {
7309 if (auto value = getConstantLockValue(op); value && *value == 0) {
7310 rewriter.eraseOp(op);
7311 return success();
7312 }
7313 }
7314 return failure();
7315}
7316
7317TileOp SwitchboxOp::getTileOp() {
7318 return cast<TileElement>(this->getOperation()).getTileOp();
7319}
7320
7321size_t SwitchboxOp::getNumSourceConnections(WireBundle bundle) {
7322 auto tile = getTileOp();
7323 const auto &targetModel = getTargetModel(*this);
7324 return targetModel.getNumSourceSwitchboxConnections(tile.getCol(),
7325 tile.getRow(), bundle);
7326}
7327
7328size_t SwitchboxOp::getNumDestConnections(WireBundle bundle) {
7329 auto tile = getTileOp();
7330 const auto &targetModel = getTargetModel(*this);
7331 return targetModel.getNumDestSwitchboxConnections(tile.getCol(),
7332 tile.getRow(), bundle);
7333}
7334
7335TileOp ShimMuxOp::getTileOp() {
7336 return cast<TileElement>(this->getOperation()).getTileOp();
7337}
7338
7339WireBundle xilinx::AIE::getConnectingBundle(WireBundle dir) {
7340 switch (dir) {
7341 case WireBundle::North:
7342 return WireBundle::South;
7343 case WireBundle::South:
7344 return WireBundle::North;
7345 case WireBundle::East:
7346 return WireBundle::West;
7347 case WireBundle::West:
7348 return WireBundle::East;
7349 case WireBundle::North32:
7350 return WireBundle::South32;
7351 case WireBundle::South32:
7352 return WireBundle::North32;
7353 case WireBundle::East32:
7354 return WireBundle::West32;
7355 case WireBundle::West32:
7356 return WireBundle::East32;
7357 case WireBundle::NorthControl:
7358 return WireBundle::SouthControl;
7359 case WireBundle::SouthControl:
7360 return WireBundle::NorthControl;
7361 default:
7362 return dir;
7363 }
7364}
7365
7366std::optional<std::pair<TileID, Port>>
7368 switch (output.bundle) {
7369 case WireBundle::North:
7370 tile.row++;
7371 break;
7372 case WireBundle::South:
7373 tile.row--;
7374 break;
7375 case WireBundle::East:
7376 tile.col++;
7377 break;
7378 case WireBundle::West:
7379 tile.col--;
7380 break;
7381 default:
7382 return std::nullopt;
7383 }
7384 return std::pair(tile,
7385 Port{getConnectingBundle(output.bundle), output.channel});
7386}
7387
7388std::optional<std::pair<TileID, Port>>
7390 TileID tile, Port port) {
7391 auto endpoint = getLinkedInput(tile, port);
7392 if (!endpoint || !targetModel.isValidTile(endpoint->first))
7393 return std::nullopt;
7394 return endpoint;
7395}
7396
7397//===----------------------------------------------------------------------===//
7398// BDChainOp
7399//===----------------------------------------------------------------------===//
7400
7401ParseResult BDChainOp::parse(OpAsmParser &parser, OperationState &result) {
7402 SmallVector<OpAsmParser::Argument> entryArgs;
7403
7404 // Symbol name, e.g. @my_chain
7405 StringAttr symNameAttr;
7406 if (parser.parseSymbolName(symNameAttr, SymbolTable::getSymbolAttrName(),
7407 result.attributes)) {
7408 return failure();
7409 }
7410
7411 // Entry arguments (placeholders), e.g. (%addr: memref<1xi32>)
7412 ParseResult argParseResult = parser.parseCommaSeparatedList(
7413 OpAsmParser::Delimiter::Paren, [&]() -> ParseResult {
7414 OpAsmParser::Argument argument;
7415 if (parser.parseArgument(argument, true, true)) {
7416 return failure();
7417 }
7418 entryArgs.push_back(argument);
7419 return success();
7420 });
7421 if (argParseResult) {
7422 return argParseResult;
7423 }
7424
7425 // BD Chain Body
7426 auto *body = result.addRegion();
7427 ParseResult bodyParseResult = parser.parseRegion(*body, entryArgs, false);
7428 if (bodyParseResult) {
7429 return bodyParseResult;
7430 }
7431
7432 return success();
7433}
7434
7435void BDChainOp::print(OpAsmPrinter &printer) {
7436 auto taskName =
7437 (*this)
7438 ->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
7439 .getValue();
7440 printer << ' ';
7441 printer.printSymbolName(taskName);
7442
7443 Region &body = getRegion();
7444 auto argsIter = body.getArguments();
7445 printer << '(';
7446 for (auto *it = argsIter.begin(); it != argsIter.end(); ++it) {
7447 if (it != argsIter.begin()) {
7448 printer << ", ";
7449 }
7450 printer.printRegionArgument(*it);
7451 }
7452 printer << ')';
7453
7454 printer << ' ';
7455 printer.printRegion(body, false, true);
7456}
7457
7458//===----------------------------------------------------------------------===//
7459// ShimDMAAllocationOp
7460//===----------------------------------------------------------------------===//
7461
7462LogicalResult ShimDMAAllocationOp::verify() {
7463 // A block argument has no defining op.
7464 TileLike tileLike =
7465 llvm::dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
7466 if (!tileLike) {
7467 return emitOpError("tile operand must implement TileLike interface");
7468 }
7469
7470 if (!tileLike.isShimNOCorPLTile()) {
7471 // if placed, provide detailed error message
7472 auto col = tileLike.tryGetCol();
7473 auto row = tileLike.tryGetRow();
7474 if (col && row) {
7475 return emitOpError("tile must be a shim tile, but got tile(")
7476 << *col << ", " << *row << ")";
7477 }
7478 return emitOpError("tile must be a shim tile");
7479 }
7480
7481 if (!getPlio()) {
7482 // Refuse a missing channel here; AIE4 lowering cannot look up its regs.
7483 if (failed(verifyDMAChannel(getOperation(), tileLike, getChannelDir(),
7484 getChannelIndex())))
7485 return failure();
7486 } else if (getDMAChannelBundle(getChannelDir()) != WireBundle::DMA) {
7487 return emitOpError("a PLIO allocation must be MM2S or S2MM");
7488 }
7489
7490 if (ArrayAttr proofs = getConsumedByAttr()) {
7491 auto device = (*this)->getParentOfType<DeviceOp>();
7492 if (failed(verifyConsumedBy(
7493 *this, proofs, getChannelDir() == DMAChannelDir::MM2S,
7494 "aie.shim_dma_allocation", [&](FlatSymbolRefAttr symbol) {
7495 auto output = getForSymbol(device, symbol.getValue());
7496 return output && output.getChannelDir() == DMAChannelDir::S2MM;
7497 })))
7498 return failure();
7499 }
7500
7501 if (failed(verifyAssignedPacket(*this, getPacketAttr())))
7502 return failure();
7503 if (!getPlio())
7504 return success();
7505 std::optional<int> col = tileLike.tryGetCol();
7506 std::optional<int> row = tileLike.tryGetRow();
7507 if (!col || !row)
7508 return success();
7509 const AIETargetModel &targetModel = getTargetModel(getOperation());
7510 // MM2S is a PLIO source of the shim mux, or the switchbox without one.
7511 bool mm2s = getChannelDir() == DMAChannelDir::MM2S;
7512 uint32_t ports = targetModel.hasShimMux(*col, *row)
7513 ? (mm2s ? targetModel.getNumSourceShimMuxConnections(
7514 *col, *row, WireBundle::PLIO)
7515 : targetModel.getNumDestShimMuxConnections(
7516 *col, *row, WireBundle::PLIO))
7517 : (mm2s ? targetModel.getNumSourceSwitchboxConnections(
7518 *col, *row, WireBundle::PLIO)
7519 : targetModel.getNumDestSwitchboxConnections(
7520 *col, *row, WireBundle::PLIO));
7521 int64_t channel = getChannelIndex();
7522 if (channel < 0 || channel >= static_cast<int64_t>(ports))
7523 return emitOpError("PLIO channel ")
7524 << channel << " is out of range: the tile has " << ports << " "
7525 << stringifyDMAChannelDir(getChannelDir()) << " PLIO ports";
7526 return success();
7527}
7528
7529TileOp ShimDMAAllocationOp::getTileOp() {
7530 return dyn_cast_or_null<TileOp>(getTile().getDefiningOp());
7531}
7532
7533ShimDMAAllocationOp ShimDMAAllocationOp::getForSymbol(DeviceOp device,
7534 llvm::StringRef symbol) {
7535 Operation *maybeOp = device.lookupSymbol(symbol);
7536 if (maybeOp) {
7537 if (ShimDMAAllocationOp op = dyn_cast<ShimDMAAllocationOp>(maybeOp)) {
7538 return op;
7539 }
7540 }
7541 return nullptr;
7542}
7543
7544//===----------------------------------------------------------------------===//
7545// ObjectFifoRearmBindingOp
7546//===----------------------------------------------------------------------===//
7547
7548LogicalResult ObjectFifoRearmBindingOp::verify() {
7549 if (getChannelDirs().size() != getChannelTiles().size())
7550 return emitOpError("expected one channel_dirs entry per channel tile (")
7551 << getChannelTiles().size() << " tiles, " << getChannelDirs().size()
7552 << " dirs)";
7553 if (getChannelIndices().size() != getChannelTiles().size())
7554 return emitOpError("expected one channel_indices entry per channel tile (")
7555 << getChannelTiles().size() << " tiles, "
7556 << getChannelIndices().size() << " indices)";
7557 if (getLockInits().size() != getLocks().size())
7558 return emitOpError("expected one lock_inits entry per lock (")
7559 << getLocks().size() << " locks, " << getLockInits().size()
7560 << " inits)";
7561 // head_bd_ids / repeat_counts are optional (populated by
7562 // --aie-assign-bd-ids), but if present they are one-per-channel and travel as
7563 // a pair: the re-push needs both, so a binding carrying one without the other
7564 // is malformed.
7565 if (getHeadBdIds().has_value() != getRepeatCounts().has_value())
7566 return emitOpError("head_bd_ids and repeat_counts must both be set or both "
7567 "be absent");
7568 if (auto headBdIds = getHeadBdIds();
7569 headBdIds.has_value() && headBdIds->size() != getChannelTiles().size())
7570 return emitOpError("expected one head_bd_ids entry per channel tile (")
7571 << getChannelTiles().size() << " tiles, " << headBdIds->size()
7572 << " ids)";
7573 if (auto repeatCounts = getRepeatCounts();
7574 repeatCounts.has_value() &&
7575 repeatCounts->size() != getChannelTiles().size())
7576 return emitOpError("expected one repeat_counts entry per channel tile (")
7577 << getChannelTiles().size() << " tiles, " << repeatCounts->size()
7578 << " counts)";
7579 for (int32_t dir : getChannelDirs())
7580 if (dir != 0 && dir != 1)
7581 return emitOpError("channel_dirs entries must be 0 (S2MM) or 1 (MM2S), "
7582 "got ")
7583 << dir;
7584 // The lowering resolves each operand to its aie.tile / aie.lock, so reject a
7585 // binding whose operands are not those (otherwise the lowering would cast a
7586 // non-lock/non-tile operand and abort).
7587 for (Value tile : getChannelTiles()) {
7588 auto tileOp = tile.getDefiningOp<TileOp>();
7589 if (!tileOp)
7590 return emitOpError("channel_tiles operands must be aie.tile values");
7591 // A shim DMA endpoint is host-managed: the host re-pushes its BD program
7592 // and re-arms its locks. Re-arming it here would fight the host, so a
7593 // re-arm binding only ever records non-shim channels -- reject a shim tile
7594 // even in a hand-authored binding.
7595 if (tileOp.isShimTile())
7596 return emitOpError("channel_tiles must be non-shim tiles; a shim DMA "
7597 "endpoint is host-managed and is not re-armed here");
7598 }
7599 for (Value lock : getLocks())
7600 if (!lock.getDefiningOp<LockOp>())
7601 return emitOpError("locks operands must be aie.lock values");
7602 // The re-push starts each channel on its head BD, which must be in the
7603 // channel's BD pool.
7604 if (std::optional<ArrayRef<int32_t>> headBdIds = getHeadBdIds()) {
7605 const auto &targetModel = getTargetModel(getOperation());
7606 for (auto [tile, channel, bdId] :
7607 llvm::zip(getChannelTiles(), getChannelIndices(), *headBdIds)) {
7608 auto tileOp = tile.getDefiningOp<TileOp>();
7609 if (bdId < 0 || !targetModel.isBdChannelAccessible(
7610 tileOp.getCol(), tileOp.getRow(), bdId, channel))
7611 return emitOpError("head BD ")
7612 << bdId << " is not accessible from channel " << channel
7613 << " of tile (" << tileOp.getCol() << ", " << tileOp.getRow()
7614 << ")";
7615 }
7616 }
7617 return success();
7618}
7619
7620//===----------------------------------------------------------------------===//
7621// RuntimeSequenceOp
7622//===----------------------------------------------------------------------===//
7623
7624ParseResult RuntimeSequenceOp::parse(OpAsmParser &parser,
7625 OperationState &result) {
7626
7627 // Name of this runtime sequence
7628 StringAttr nameAttr;
7629 (void)parser.parseOptionalSymbolName(
7630 nameAttr, mlir::SymbolTable::getSymbolAttrName(), result.attributes);
7631
7632 SmallVector<OpAsmParser::Argument> entryArgs;
7633
7634 // Entry arguments, e.g. (%addr: memref<1xi32>)
7635 ParseResult argParseResult = parser.parseCommaSeparatedList(
7636 OpAsmParser::Delimiter::Paren, [&]() -> ParseResult {
7637 OpAsmParser::Argument argument;
7638 if (parser.parseArgument(argument, true, true)) {
7639 return failure();
7640 }
7641 entryArgs.push_back(argument);
7642 return success();
7643 });
7644 if (argParseResult) {
7645 return argParseResult;
7646 }
7647
7648 // Optional `attributes { ... }` clause (before the body so it does not
7649 // conflict with the `{` that opens the region).
7650 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
7651 return failure();
7652
7653 // Body
7654 auto *body = result.addRegion();
7655 ParseResult bodyParseResult = parser.parseRegion(*body, entryArgs, false);
7656 if (bodyParseResult) {
7657 return bodyParseResult;
7658 }
7659
7660 return success();
7661}
7662
7663void RuntimeSequenceOp::print(OpAsmPrinter &printer) {
7664 Region &body = getRegion();
7665
7666 auto nameAttr = (*this)->getAttrOfType<StringAttr>(
7667 mlir::SymbolTable::getSymbolAttrName());
7668 if (nameAttr &&
7669 nameAttr != ::mlir::OpBuilder((*this)->getContext())
7670 .getStringAttr(getDefaultRuntimeSequenceName())) {
7671 printer << ' ';
7672 printer.printSymbolName(nameAttr);
7673 }
7674
7675 printer << '(';
7676 for (unsigned i = 0, n = body.getNumArguments(); i < n; i++) {
7677 if (i > 0) {
7678 printer << ", ";
7679 }
7680 printer.printRegionArgument(body.getArgument(i));
7681 }
7682 printer << ')';
7683
7684 printer.printOptionalAttrDictWithKeyword(
7685 (*this)->getAttrs(),
7686 /*elidedAttrs=*/{mlir::SymbolTable::getSymbolAttrName()});
7687
7688 printer << ' ';
7689 printer.printRegion(body, false, true);
7690}
7691
7692LogicalResult RuntimeSequenceOp::verify() {
7693 DeviceOp device = (*this)->getParentOfType<DeviceOp>();
7694 if (!device) {
7695 // this check is redudnant with the HasParent trait, but can't hurt
7696 (*this)->emitOpError() << "must be inside AIE device operation.";
7697 return failure();
7698 }
7699 return success();
7700}
7701
7702RuntimeSequenceOp
7703RuntimeSequenceOp::getForSymbolInDevice(DeviceOp deviceOp,
7704 llvm::StringRef symbol) {
7705 RuntimeSequenceOp runtimeSequenceOp;
7706 if (symbol.empty()) {
7707 auto range = deviceOp.getOps<RuntimeSequenceOp>();
7708 if (range.begin() == range.end()) {
7709 // No runtime sequence in the device; let the caller emit a diagnostic
7710 // rather than dereferencing an end iterator (which crashes).
7711 return nullptr;
7712 }
7713 runtimeSequenceOp = *range.begin();
7714 } else {
7715 Operation *maybeRuntimeSequenceOp =
7716 mlir::SymbolTable::lookupSymbolIn(deviceOp, symbol);
7717 if (!maybeRuntimeSequenceOp) {
7718 return nullptr;
7719 }
7720 runtimeSequenceOp =
7721 llvm::dyn_cast<RuntimeSequenceOp>(maybeRuntimeSequenceOp);
7722 }
7723 return runtimeSequenceOp;
7724}
7725
7726RuntimeSequenceOp
7727RuntimeSequenceOp::getForSymbolInDeviceOrError(DeviceOp deviceOp,
7728 llvm::StringRef symbol) {
7729 RuntimeSequenceOp runtimeSequenceOp = getForSymbolInDevice(deviceOp, symbol);
7730 if (!runtimeSequenceOp) {
7731 if (!symbol.empty()) {
7732 deviceOp.emitError("No such runtime sequence: ") << symbol;
7733 } else {
7734 deviceOp.emitError("No runtime sequence in device");
7735 }
7736 }
7737 return runtimeSequenceOp;
7738}
7739
7740LogicalResult RuntimeSequenceOp::verifyBeforeMaterialization() {
7741 // Check that all symbol references within the runtime sequence
7742 // are either to ShimDMAAllocationOp, DeviceOp or another RuntimeSequenceOp;
7743 // these are the only symbols that can be lowered with the NPU passes
7744 auto result = (*this)->walk([&](Operation *op) {
7745 for (NamedAttribute namedAttr : op->getAttrs()) {
7746 Attribute attr = namedAttr.getValue();
7747 auto walkResult = attr.walk([&](SymbolRefAttr symbolRef) {
7748 Operation *symbolDefOp =
7749 SymbolTable::lookupNearestSymbolFrom(*this, symbolRef);
7750 if (!symbolDefOp) {
7751 if (auto flat = dyn_cast<FlatSymbolRefAttr>(symbolRef)) {
7752 symbolDefOp = lookupNamedOp(*this, flat.getAttr());
7753 }
7754 }
7755 if (symbolDefOp) {
7756 if (!llvm::isa<ShimDMAAllocationOp>(symbolDefOp) &&
7757 !llvm::isa<DeviceOp>(symbolDefOp) &&
7758 !llvm::isa<RuntimeSequenceOp>(symbolDefOp) &&
7759 !llvm::isa<BufferOp>(symbolDefOp) &&
7760 !llvm::isa<ObjectFifoRearmBindingOp>(symbolDefOp) &&
7761 !llvm::isa<memref::GlobalOp>(symbolDefOp)) {
7762 op->emitOpError()
7763 << "references symbol '"
7764 << symbolRef.getRootReference().getValue()
7765 << "' which must be either a ShimDMAAllocationOp, DeviceOp, "
7766 "RuntimeSequenceOp, BufferOp, ObjectFifoRearmBindingOp, or "
7767 "GlobalOp, but got: "
7768 << symbolDefOp->getName().getStringRef();
7769 return WalkResult::interrupt();
7770 }
7771 if (BufferOp bufferOp = llvm::dyn_cast<BufferOp>(symbolDefOp)) {
7772 if (!bufferOp.getAddress()) {
7773 op->emitOpError()
7774 << "Unallocated buffer; fixed addresses are required before "
7775 "runtime sequence materialization.";
7776 return WalkResult::interrupt();
7777 }
7778 }
7779 }
7780 return WalkResult::advance();
7781 });
7782 if (walkResult.wasInterrupted()) {
7783 return WalkResult::interrupt();
7784 }
7785 }
7786 return WalkResult::advance();
7787 });
7788
7789 if (result.wasInterrupted()) {
7790 return failure();
7791 }
7792
7793 return success();
7794}
7795
7796// Include implementations for custom attributes
7797#define GET_ATTRDEF_CLASSES
7798#include "aie/Dialect/AIE/IR/AIEAttrs.cpp.inc"
7799
7800bool xilinx::AIE::hasCoreAccess(DeviceOp device, Value tile,
7801 ObjectFifoCreateOp objFifo,
7802 ObjectFifoPort port) {
7803 for (auto coreOp : device.getOps<CoreOp>()) {
7804 if (coreOp.getTile() != tile) {
7805 continue;
7806 }
7807 bool found = false;
7808 coreOp.walk([&](Operation *op) {
7809 if (auto acq = dyn_cast<ObjectFifoAcquireOp>(op)) {
7810 found |= acq.getObjectFifo() == objFifo && acq.getPort() == port;
7811 } else if (auto rel = dyn_cast<ObjectFifoReleaseOp>(op)) {
7812 found |= rel.getObjectFifo() == objFifo && rel.getPort() == port;
7813 }
7814 });
7815 if (found) {
7816 return true;
7817 }
7818 }
7819 return false;
7820}
uint32_t getDmaBdStepBias(AIETileType tileType) const
DmaBdLayout::stepBias, or 1 without a layout.
virtual uint64_t getDmaBdMaxLen(AIETileType tileType) const =0
Return the maximum transfer length, measured in address-generation granules (see getAddressGenGranula...
virtual const DmaBdLayout * getDmaBdLayout(AIETileType tileType) const
Return the register layout of a buffer descriptor on the given tile type, or null if the target has n...
virtual AIEArch getTargetArch() const =0
Return the target architecture.
virtual uint32_t getNumSourceShimMuxConnections(int col, int row, WireBundle bundle) const =0
Return the number of sources of connections inside a shimmux.
bool isMemTile(int col, int row) const
Return true if the given tile is a Mem tile.
virtual uint32_t getDmaBdWrapBits(AIETileType tileType) const =0
Return the bit width of the wrap (size) field in a DMA buffer descriptor for the given tile type.
virtual uint32_t getLocalMemorySize() const =0
Return the size (in bytes) of the local data memory of a core.
virtual uint32_t getNumLocks(AIETileType tileType) const =0
Return the number of lock objects for a given tile type.
uint32_t getNumBDsForChannel(int col, int row, int channel, DMAChannelDir dir) const
virtual uint32_t getTotalNumBDs(AIETileType tileType) const
Physical BDs over all pools; exceeds getNumBDs() where pools reuse ids.
virtual uint32_t getBdPoolId(int col, int row, int channel, DMAChannelDir dir) const
Return the pool channel in direction dir draws its BDs from.
virtual uint32_t getDmaBdIterBits(AIETileType tileType) const =0
Return the bit width of the iteration (repeat) wrap/stride fields in a DMA buffer descriptor for the ...
virtual uint32_t getBDMaxDims(AIETileType tileType) const =0
Return the maximum number of addressing dimensions (wraps/strides) a single buffer descriptor support...
virtual std::vector< std::pair< uint32_t, uint32_t > > getShimBurstEncodingsAndLengths() const =0
virtual bool isLegalTileConnection(int col, int row, WireBundle srcBundle, int srcChan, WireBundle dstBundle, int dstChan) const =0
virtual uint32_t getNumBanks(int col, int row) const =0
Return the number of memory banks of a given tile.
virtual uint32_t getDmaTaskQueueDepth() const =0
Return how many DMA tasks a single channel's task queue holds (unsupported = 0).
virtual uint32_t getDmaBdStepBits(AIETileType tileType) const =0
Return the bit width of the step (stride) field in a DMA buffer descriptor for the given tile type.
bool isShimPLTile(int col, int row) const
Return true if the given tile is a ShimPL tile.
bool isBdChannelAccessible(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
virtual uint32_t getAccumulatorCascadeSize() const =0
Return the size (in bits) of the accumulator/cascade.
virtual AIETileType getTileType(int col, int row) const =0
Return the tile type for the given tile coordinates.
virtual bool isValidTile(TileID src) const
Return true if the given tile ID is valid.
bool isShimNOCorPLTile(int col, int row) const
Return true if the given tile is either a ShimNOC or ShimPL tile.
virtual uint32_t getMaxRepeatCount() const =0
Return the largest DMA task repeat count (unsupported = 0).
bool isDmaChannelSupported(TileID tile, AIE::DMAChannelDir dir, int channel) const
virtual int rows() const =0
Return the number of rows in the device.
bool isShimNOCTile(int col, int row) const
Return true if the given tile is a ShimNOC tile.
virtual uint32_t getNumBDs(AIETileType tileType) const =0
Return the size of the BD id space of a tile type (see getTotalNumBDs()).
virtual uint32_t getMaxLockValue() const =0
Return the maximum value that can be stored in a lock register.
virtual uint32_t getMaxOutOfOrderId() const =0
Return the largest out-of-order BD id (unsupported = 0).
virtual uint32_t getBdPoolStartId(int col, int row, uint32_t poolId) const
bool hasProperty(ModelProperty Prop) const
uint32_t getNumDMAChannels(int col, int row, AIE::DMAChannelDir dir) const
Return the number of DMA channels a tile has in one direction.
virtual int columns() const =0
Return the number of columns in the device.
virtual uint32_t getNumBDsInPool(int col, int row, uint32_t poolId) const
virtual uint32_t getNumDestShimMuxConnections(int col, int row, WireBundle bundle) const =0
Return the number of destinations of connections inside a shimmux.
virtual uint32_t getNumDestSwitchboxConnections(int col, int row, WireBundle bundle) const =0
Return the number of destinations of connections inside a switchbox.
SharedMemory
Which of two tiles' memory modules both of them can address.
@ None
Neither tile can address the other's memory module.
SharedMemory getSharedMemory(TileID a, TileID b) const
Return the memory module a and b can both reach, if any.
virtual bool hasShimMux(int col, int row) const
True if the tile's DMA/NOC/PLIO ports sit behind an aie.shim_mux; otherwise its DMA is routed in the ...
virtual uint32_t getAddressGenGranularity() const =0
Return the data bus width of the device.
virtual uint32_t getMemTileSize() const =0
Return the size (in bytes) of a MemTile.
virtual uint32_t getNumSourceSwitchboxConnections(int col, int row, WireBundle bundle) const =0
Return the number of sources of connections inside a switchbox.
NamedOpTable(mlir::Operation *symbolTableOp)
std::string uniqueName(llvm::StringRef prefix, unsigned &counter) const
mlir::LogicalResult verifyDMAChannel(mlir::Operation *op, TileLike tile, DMAChannelDir dir, int64_t channel)
bool isContiguousBDTransfer(llvm::ArrayRef< BDDimLayoutAttr > dims)
mlir::ParseResult parseFlowVias(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< mlir::OpAsmParser::UnresolvedOperand > &vias, mlir::DenseI32ArrayAttr &ingressBundles, mlir::DenseI32ArrayAttr &ingressChannels, mlir::DenseI32ArrayAttr &egressBundles, mlir::DenseI32ArrayAttr &egressChannels)
void printObjectFifoProducerTile(mlir::OpAsmPrinter &printer, mlir::Operation *op, mlir::Value operand, BDDimLayoutArrayAttr dimensions)
void printTypedDynamicIndexList(mlir::OpAsmPrinter &printer, mlir::Operation *op, mlir::OperandRange values, llvm::ArrayRef< int64_t > integers, mlir::TypeRange types)
llvm::SmallVector< ObjectFifoDmaEndpointOp > turnEndpoints(ObjectFifoDmaEndpointOp end)
llvm::function_ref< std::optional< TileID >(mlir::Value)> TilePositions
Definition AIEDialect.h:428
std::optional< llvm::SmallVector< BDDimLayoutAttr > > normalizedBDDims(llvm::ArrayRef< BDDimLayoutAttr > dims, int64_t len)
bool hasCoreAccess(DeviceOp device, mlir::Value tile, ObjectFifoCreateOp fifo, ObjectFifoPort port)
mlir::LogicalResult verifyLengthParameterTile(mlir::Operation *op, const AIETargetModel &targetModel, int col, int row)
uint32_t getShimBurstLengthBytes(const AIE::AIETargetModel &tm, uint32_t burstLength)
void collectTiles(DeviceOp &device, llvm::DenseMap< TileID, mlir::Operation * > &tiles)
int64_t getMemRefSizeInBytes(mlir::MemRefType type, const mlir::DataLayout &layout)
llvm::SmallVector< int, 2 > banksFromMemorySpace(mlir::Type type)
void collectBuffers(DeviceOp &device, llvm::DenseMap< mlir::Operation *, llvm::SmallVector< BufferOp, 4 > > &buffers)
mlir::ParseResult parseTraceEvent(mlir::AsmParser &parser, mlir::Attribute &result)
void printObjectFifoAcquireObjects(mlir::OpAsmPrinter &printer, mlir::Operation *op, ObjectFifoPortAttr port, mlir::TypeRange objects)
mlir::LogicalResult verifyBdLockPair(mlir::Block &block, bool outOfOrder, UseLockOp &acquire, UseLockOp &release)
mlir::LogicalResult verifyAssignedPacket(mlir::Operation *op, PacketInfoAttr packet, llvm::StringRef what="packet")
mlir::ParseResult parseTypedDynamicIndexList(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< mlir::OpAsmParser::UnresolvedOperand > &values, mlir::DenseI64ArrayAttr &integers, llvm::SmallVectorImpl< mlir::Type > &types)
void printObjectFifoConsumerTiles(mlir::OpAsmPrinter &printer, mlir::Operation *op, mlir::OperandRange tiles, BDDimLayoutArrayArrayAttr dimsPerTileAttr)
mlir::Operation * lookupNamedOpIn(mlir::Operation *symbolTableOp, mlir::StringAttr name)
uint32_t getShimBurstLengthEncoding(const AIE::AIETargetModel &tm, uint32_t burstLength)
mlir::LogicalResult verifyDMABDOutOfOrderId(DMABDOp bd, bool packetEnabledByContext=false)
mlir::ParseResult parseObjectFifoAcquireObjects(mlir::OpAsmParser &parser, ObjectFifoPortAttr &port, llvm::SmallVectorImpl< mlir::Type > &objects)
mlir::LogicalResult verifyOutOfOrderChannel(mlir::Operation *op, DMAChannelDir dir, bool outOfOrder, llvm::ArrayRef< DMABDOp > bds, bool packetEnabledByContext=false)
struct Connect { Port src; Port dst; bool operator==(const Connect &rhs) const { return std::tie(src, dst)==std::tie(rhs.src, rhs.dst); } bool operator!=(const Connect &rhs) const { return !(*this==rhs);} bool operator<(const Connect &rhs) const { return std::tie(src, dst)< std::tie(rhs.src, rhs.dst); } } Connect
Definition AIEDialect.h:305
void printDMAStartChannel(mlir::OpAsmPrinter &printer, mlir::Operation *op, mlir::Attribute channel)
mlir::LogicalResult verifyLengthParameter(mlir::Operation *op, std::optional< int64_t > lengthUnit, mlir::BaseMemRefType buffer, std::optional< int64_t > lenElems, bool contiguous, llvm::ArrayRef< int64_t > innerSizes)
mlir::LogicalResult verifyDMAChannelIndex(mlir::Operation *op, TileLike tile, DMAChannelDir dir, int64_t channel)
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
int32_t getBufferBaseAddress(mlir::Operation *bufOp)
mlir::ParseResult parseDMAStartChannel(mlir::OpAsmParser &parser, mlir::Attribute &channel)
std::optional< std::pair< TileID, Port > > getLinkedInput(TileID tile, Port output)
The switchbox input driven by an output's physical wire, with the channel preserved.
llvm::SmallVector< uint32_t > getAssignedBdIds(DmaBody program)
llvm::SmallVector< StreamWindowStep > streamWindowSteps(const StreamWindow &w)
int64_t turnPasses(llvm::ArrayRef< std::pair< int64_t, int64_t > > ends)
const AIETargetModel & getTargetModel(mlir::Operation *op)
bool keepsPktHeader(TileID tile, Port master, std::optional< bool > keep)
struct DMAChannel { DMAChannelDir direction; int channel; bool operator==(const DMAChannel &rhs) const { return std::tie(direction, channel)==std::tie(rhs.direction, rhs.channel); } } DMAChannel
Definition AIEDialect.h:320
mlir::LogicalResult verifyDMAChannelsResolved(DeviceOp device)
mlir::Operation * lookupNamedOp(mlir::Operation *from, mlir::StringAttr name)
mlir::ParseResult parseObjectFifoProducerTile(mlir::OpAsmParser &parser, mlir::OpAsmParser::UnresolvedOperand &operand, BDDimLayoutArrayAttr &dimensions)
void printTraceEventEnum(mlir::AsmPrinter &printer, mlir::Attribute attr)
void placeRuntimeLengthDimension(llvm::MutableArrayRef< int64_t > sizes, llvm::MutableArrayRef< int64_t > strides)
mlir::LogicalResult myVerifyOffsetSizeAndStrideOp(mlir::OffsetSizeAndStrideOpInterface op)
mlir::LogicalResult inferStreamWindow(llvm::ArrayRef< BDDimLayoutAttr > dims, llvm::ArrayRef< BDPadLayoutAttr > pads, int64_t objectSize, llvm::function_ref< mlir::InFlightDiagnostic()> emitError, StreamWindow &window)
mlir::LogicalResult verifyDMABDIteration(DMABDOp bd, AIETileType tileType)
void printFlowVias(mlir::OpAsmPrinter &printer, mlir::Operation *op, mlir::OperandRange vias, mlir::DenseI32ArrayAttr ingressBundles, mlir::DenseI32ArrayAttr ingressChannels, mlir::DenseI32ArrayAttr egressBundles, mlir::DenseI32ArrayAttr egressChannels)
struct Port { WireBundle bundle; int channel; bool operator==(const Port &rhs) const { return std::tie(bundle, channel)==std::tie(rhs.bundle, rhs.channel); } bool operator!=(const Port &rhs) const { return !(*this==rhs);} bool operator<(const Port &rhs) const { return std::tie(bundle, channel)< std::tie(rhs.bundle, rhs.channel); } friend std::ostream &operator<<(std::ostream &os, const Port &port) { os<< "("; os<< stringifyWireBundle(port.bundle).str(); os<< ": "<< std::to_string(port.channel)<< ")"; return os; } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Port &port) { os<< to_string(port); return os; } } Port
Definition AIEDialect.h:265
mlir::ParseResult parseObjectFifoReleaseCount(mlir::OpAsmParser &parser, ObjectFifoPortAttr &port, mlir::IntegerAttr &size)
AIETargetModel::SharedMemory sharedMemory(TileOp a, TileOp b)
Which of a's and b's memory modules both tiles can address.
std::optional< std::pair< TileID, Port > > getConnectingWireEndpoint(const AIETargetModel &targetModel, TileID tile, Port port)
getLinkedInput, restricted to tiles on the device.
mlir::LogicalResult verifyControlOrTraceDMAChannel(mlir::Operation *op, const AIETargetModel &targetModel, int col, int row, DMAChannelDir dir, int64_t channel)
mlir::FailureOr< int64_t > getLengthUnitBytes(mlir::Operation *op, int64_t lengthUnit, mlir::BaseMemRefType buffer)
int64_t paddedSize(llvm::ArrayRef< BDDimLayoutAttr > dims, llvm::ArrayRef< BDPadLayoutAttr > pads, int64_t fallback)
mlir::ParseResult parseObjectFifoConsumerTiles(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< mlir::OpAsmParser::UnresolvedOperand > &tiles, BDDimLayoutArrayArrayAttr &dimensions)
void printObjectFifoReleaseCount(mlir::OpAsmPrinter &printer, mlir::Operation *op, ObjectFifoPortAttr port, mlir::IntegerAttr size)
WireBundle getConnectingBundle(WireBundle dir)
WireBundle getDMAChannelBundle(DMAChannelDir dir)
The stream-switch bundle the channels of dir use.
Definition AIEEnums.h:29
static LogicalResult verifyTrait(Operation *op)
static LogicalResult verifyTrait(Operation *op)
static LogicalResult verifyTrait(Operation *op)
static LogicalResult verifyTrait(Operation *op)
static LogicalResult verifyTrait(Operation *op)
The register layout of one tile type's DMA buffer descriptor.
llvm::SmallVector< std::pair< DmaBdField, DmaBdField >, 3 > padFields() const
The (before, after) zero-padding fields, innermost dimension first.
static mlir::LogicalResult verifyTrait(mlir::Operation *op)
static mlir::LogicalResult verifyTrait(mlir::Operation *op)
int64_t depthAt(const AIETargetModel &target, TilePositions positions) const
llvm::SmallVector< LinkPoolSharer > sharers
Definition AIEDialect.h:445
int64_t end() const
llvm::SmallVector< BDDimLayoutAttr > inner
Definition AIEDialect.h:420