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"
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"
44#include "aie/Dialect/AIE/IR/AIEDialect.cpp.inc"
46#define GET_TYPEDEF_CLASSES
47#include "aie/Dialect/AIE/IR/AIETypes.cpp.inc"
51struct AIEInlinerInterface : DialectInlinerInterface {
52 using DialectInlinerInterface::DialectInlinerInterface;
55 bool isLegalToInline(Region *dest, Region *src,
bool wouldBeCloned,
56 IRMapping &valueMapping)
const final {
62 bool isLegalToInline(Operation *op, Region *,
bool wouldBeCloned,
63 IRMapping &)
const final {
69 void handleTerminator(Operation *op, Block *newDest)
const final {}
73 void handleTerminator(Operation *op, ValueRange valuesToRepl)
const final {}
76struct AIEDialectFoldInterface : DialectFoldInterface {
77 using DialectFoldInterface::DialectFoldInterface;
82 bool shouldMaterializeInto(Region *region)
const final {
95 return isa<CoreOp, RuntimeSequenceOp, MemOp, MemTileDMAOp, ShimDMAOp>(
96 region->getParentOp());
102void AIEDialect::initialize() {
104#define GET_TYPEDEF_LIST
105#include "aie/Dialect/AIE/IR/AIETypes.cpp.inc"
108#define GET_ATTRDEF_LIST
109#include "aie/Dialect/AIE/IR/AIEAttrs.cpp.inc"
113#include "aie/Dialect/AIE/IR/AIEOps.cpp.inc"
115 addInterfaces<AIEInlinerInterface, AIEDialectFoldInterface>();
122static std::pair<uint32_t, uint32_t>
124 uint32_t burstLength) {
126 std::vector<std::pair<uint32_t, uint32_t>> bel =
131 if (burstLength == 0) {
132 return *llvm::max_element(bel, [](
auto pair1,
auto pair2) {
133 return pair1.second < pair2.second;
139 return *llvm::find_if(bel, [=](
auto p) {
return p.second == burstLength; });
143 uint32_t burstLength) {
145 return getShimBurstLength(tm, burstLength).second;
149 uint32_t burstLength) {
151 return getShimBurstLength(tm, burstLength).first;
156 if (!symbolTableOp->hasTrait<mlir::OpTrait::SymbolTable>() ||
157 symbolTableOp->getRegion(0).empty()) {
162 for (Operation &op : symbolTableOp->getRegion(0).front()) {
163 if (op.getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()) ==
172 : context(symbolTableOp->getContext()) {
173 if (!symbolTableOp->hasTrait<mlir::OpTrait::SymbolTable>() ||
174 symbolTableOp->getRegion(0).empty()) {
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);
188 StringAttr::get(symbolTableOp->getContext(), name));
192 Operation *symbolTableOp = mlir::SymbolTable::getNearestSymbolTable(from);
197 return lookupNamedOp(from, StringAttr::get(from->getContext(), name));
201 unsigned &counter)
const {
204 name = (prefix + llvm::Twine(counter++)).str();
205 }
while (ops.count(StringAttr::get(context, name)));
211 std::array<unsigned, 3> maxRanks = op.getArrayAttrMaxRanks();
217 if (failed(verifyListOfOperandsOrIntegers(
218 op,
"offset", maxRanks[0], op.getStaticOffsets(), op.getOffsets())))
220 if (failed(verifyListOfOperandsOrIntegers(
221 op,
"size", maxRanks[1], op.getStaticSizes(), op.getSizes())))
223 if (failed(verifyListOfOperandsOrIntegers(
224 op,
"stride", maxRanks[2], op.getStaticStrides(), op.getStrides())))
227 const size_t numMixedOffsets = op.getMixedOffsets().size();
228 const size_t numMixedSizes = op.getMixedSizes().size();
229 if (!(numMixedOffsets == 1 && maxRanks[0] == 1) &&
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 ")
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 ")
268 if (
auto t = dyn_cast<AIETarget>(op))
269 return t.getTargetModel();
270 if (
auto t = op->getParentOfType<AIETarget>())
271 return t.getTargetModel();
285 case AIEDevice::xcvc1902:
287 case AIEDevice::xcve2302:
289 case AIEDevice::xcve2802:
291 case AIEDevice::npu1:
293 case AIEDevice::npu1_1col:
295 case AIEDevice::npu1_2col:
297 case AIEDevice::npu1_3col:
299 case AIEDevice::npu2:
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:
317 case AIEDevice::npu3:
319 case AIEDevice::npu3_1col:
320 return NPU3model1col;
321 case AIEDevice::npu3_2col:
322 return NPU3model2col;
327 llvm::report_fatal_error(
"getTargetModel: unknown AIEDevice value " +
328 llvm::Twine(
static_cast<uint32_t
>(device)));
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))
338 parent = parent->getParentOp();
340 return llvm::dyn_cast<TileElement>(parent);
344static int64_t getDimsMaxIdx(ArrayRef<BDDimLayoutAttr> dims) {
346 for (BDDimLayoutAttr dim : dims) {
347 maxIdx += dim.getStride() * (dim.getSize() - 1);
353 int64_t elements = 1;
354 for (BDDimLayoutAttr dim :
inner)
355 elements *= dim.getSize();
360 ArrayRef<BDDimLayoutAttr> dims, ArrayRef<BDPadLayoutAttr> pads,
361 int64_t objectSize, function_ref<InFlightDiagnostic()> emitError,
364 return emitError() <<
"a walk over a stream needs an outer dimension of "
365 "outputs and at least one inner dimension";
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());
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";
388 reach += dim.getStride() * (dim.getSize() - 1);
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";
396 for (
auto [index, pad] : llvm::enumerate(pads)) {
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 "
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";
415SmallVector<StreamWindowStep>
417 SmallVector<StreamWindowStep> steps;
418 int64_t acquired = 0, released = 0;
419 for (int64_t j = 0; j < w.
outputs; j++) {
421 int64_t newest = std::max(
422 acquired, start + std::clamp<int64_t>(w.
objects - start, 0, w.
span));
425 ? std::clamp<int64_t>((j + 1) * w.
advance - w.
top, 0, newest)
427 next = std::max(released, next);
428 steps.push_back({j * w.
advance, newest - acquired, next - released});
437struct UsesAreAccessible {
438 static LogicalResult verifyTrait(Operation *op) {
439 auto thisElement = cast<TileElement>(op);
443 if (!isa<TileOp>(thisElement.getTile().getDefiningOp()))
446 auto thisID = thisElement.getTileID();
447 auto users = op->getResult(0).getUsers();
449 for (
auto *user : users) {
452 if (llvm::isa_and_nonnull<DeviceOp, ModuleOp>(user->getParentOp())) {
461 TileElement element = llvm::dyn_cast<TileElement>(user);
463 element = getParentTileElement(user);
467 return op->emitOpError(
"is accessed outside of a tile")
468 .attachNote(user->getLoc())
471 auto tileID = element.getTileID();
472 if (!targetModel.isLegalMemAffinity(tileID.col, tileID.row, thisID.col,
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())
490template <
typename... TerminatorOpTypes>
493 for (
auto ®ion : 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: ");
511static LogicalResult verifyBdPools(Operation *op, Region &body, TileLike tile,
513 std::optional<int> col = tile.tryGetCol();
514 std::optional<int> row = tile.tryGetRow();
518 DenseMap<Block *, SmallVector<DMAChannel, 1>> blockChannels;
519 for (Block &block : body) {
520 for (
auto dmaStart : block.getOps<DMAStartOp>()) {
522 if (dmaStart.getEndpoint())
524 DMAChannel chan = {dmaStart.getChannelDir(), dmaStart.getChannelIndex()};
526 {*col, *row}, chan.direction, chan.channel))
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)
534 blockChannels[bdBlock].push_back(chan);
535 if (bdBlock->mightHaveTerminator())
536 llvm::append_range(worklist,
537 bdBlock->getTerminator()->getSuccessors());
543 DenseMap<uint32_t, uint32_t> poolBdCount;
544 auto checkBds = [&](
DMAChannel chan, uint32_t pool,
545 MutableArrayRef<DMABDOp> bdOps) -> LogicalResult {
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");
555 auto checkBdId = [&](DMABDOp bdOp, std::optional<int32_t> id,
556 StringRef what) -> LogicalResult {
557 if (!
id || *
id < 0 ||
559 static_cast<uint32_t
>(*
id),
560 chan.channel, chan.direction))
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())
570 for (DMABDOp bdOp : bdOps) {
571 if (failed(checkBdId(bdOp, bdOp.getBdId(),
"bd_id")) ||
572 failed(checkBdId(bdOp, bdOp.getNextBdId(),
"next_bd_id")))
578 for (Block &block : body) {
579 auto it = blockChannels.find(&block);
580 if (it == blockChannels.end())
582 auto bdOps = llvm::to_vector_of<DMABDOp>(block.getOps<DMABDOp>());
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) !=
591 return (op->emitOpError(
"BD is reached from channels (")
592 << stringifyDMAChannelDir(chan.direction) <<
", "
593 << chan.channel <<
") and ("
594 << stringifyDMAChannelDir(other.direction) <<
", "
596 <<
"), which draw from different BD pools; one BD cannot "
598 .attachNote(bdOps.front().getLoc())
600 if (failed(checkBds(chan, pool, bdOps)))
605 for (
auto dma : body.getOps<DMAOp>()) {
607 static_cast<int>(dma.getChannelIndex())};
609 {*col, *row}, chan.direction, chan.channel))
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)))
624template <
typename ConcreteType>
626 auto element = cast<ConcreteType>(op);
629 TileLike tile = element.getTileLike();
631 return op->emitOpError(
"tile must implement TileLike interface");
633 if (isa<AIE4TargetModel>(targetModel) &&
634 failed(verifyBdPools(op, element.getBody(), tile, targetModel)))
640 for (
auto &block : element.getBody()) {
641 auto bdOps = llvm::to_vector_of<DMABDOp>(block.template getOps<DMABDOp>());
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");
656 if (bdOps.size() != 1) {
657 return (op->emitOpError(
"BD block must have exactly one DMABDOp, found ")
659 .attachNote(block.front().getLoc())
660 .append(
"in this BD block");
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())
671 else if (useLock.release())
675 if (acquireCount > 1) {
676 return (op->emitOpError(
677 "BD block must have at most one acquire UseLockOp, found ")
679 .attachNote(block.front().getLoc())
680 .append(
"in this BD block");
682 if (releaseCount > 1) {
683 return (op->emitOpError(
684 "BD block must have at most one release UseLockOp, found ")
686 .attachNote(block.front().getLoc())
687 .append(
"in this BD block");
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();
703 return op->emitOpError(
"should have non-empty body");
704 for (
auto &bodyOp : body.getOps()) {
706 if (
auto dmaStart = dyn_cast<DMAStartOp>(bodyOp)) {
707 if (FlatSymbolRefAttr endpoint = dmaStart.getEndpoint()) {
708 namedChannels.insert({dmaStart.getChannelDir(), endpoint.getAttr()});
711 DMAChannel dmaChan = {dmaStart.getChannelDir(),
712 dmaStart.getChannelIndex()};
718 if (dmaChan.direction == DMAChannelDir::S2MM)
719 inputChannels.insert(dmaChan);
721 outputChannels.insert(dmaChan);
725 TileLike tile = element.getTileLike();
727 return op->emitOpError(
"tile must implement TileLike interface");
729 auto named = [&](DMAChannelDir dir) ->
size_t {
730 return llvm::count_if(namedChannels,
731 [&](
auto channel) {
return channel.first == dir; });
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");
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");
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);
763ObjectFifoTransportAttr::verify(function_ref<InFlightDiagnostic()> emitError,
764 ObjectFifoTransportMode mode,
765 PacketInfoAttr packet,
bool out_of_order) {
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";
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 "
799ObjectFifoEndPortAttr::verify(function_ref<InFlightDiagnostic()> emitError,
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) {
808 return emitError() <<
"a Core end needs its stream port";
810 return emitError() <<
"a Core end's stream port is 0 or 1, not "
822static LogicalResult verifyInitValues(Operation *op, ArrayAttr initValues,
824 for (Attribute value : initValues) {
825 auto dense = dyn_cast<DenseElementsAttr>(value);
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;
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 ")
847 static constexpr std::pair<llvm::StringLiteral, llvm::StringLiteral>
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;
867 if (isa<ArrayAttr>(getElemNumber())) {
868 if (
size_t numDepths = dyn_cast<ArrayAttr>(getElemNumber()).size();
869 numDepths != getConsumerTiles().size() + 1)
870 return emitOpError(
"does not have enough depths specified for producer "
871 "and for each consumer.");
874 if (ArrayAttr consPorts = getConsPortsAttr();
875 consPorts && consPorts.size() != getConsumerTiles().size())
876 return emitOpError(
"`cons_ports` has ")
877 << consPorts.size() <<
" entries for " << getConsumerTiles().size()
882 auto getTileLikeFromValue = [](Value v) -> TileLike {
883 return llvm::dyn_cast_or_null<TileLike>(v.getDefiningOp());
886 TileLike producerTile = getTileLikeFromValue(getProducerTile());
888 return emitError(
"producer tile must implement TileLike interface");
891 if (producerTile.isShimTile() && !getDimensionsToStream().empty()) {
893 "`dimensionsToStream` data layout transformations are not supported "
894 "on shim tile producers");
896 for (
auto consTileVal : getConsumerTiles()) {
897 TileLike consTile = getTileLikeFromValue(consTileVal);
899 return emitError(
"consumer tile must implement TileLike interface");
900 if (consTile.isShimTile() &&
901 !getDimensionsFromStream(consTileVal).empty()) {
903 "`dimensionsFromStreamPerConsumer` data layout transformations are "
904 "not supported on shim tile consumers");
911 for (
auto [index, consumer] : llvm::enumerate(getConsumerTiles())) {
913 llvm::find(getConsumerTiles(), consumer) - getConsumerTiles().begin();
914 TileLike tile = getTileLikeFromValue(consumer);
915 if (first == index || tile.getTileType() != AIETileType::CoreTile ||
916 getConsumerLink(index))
918 InFlightDiagnostic diag = emitOpError(
"lists core tile ");
919 if (std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
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";
929 if (getRepeatCount().has_value()) {
930 if (producerTile.isShimTile())
931 return emitError(
"`repeat_count` unavailable for shim tiles");
934 if (getPadValue() != 0) {
935 if (!getPadDimensions().has_value())
936 return emitError(
"`padValue` requires `padDimensions`");
938 return emitError(
"`padValue` requires the CONSTANT_PAD_VALUE register, "
939 "unavailable on this target");
943 if (getConsumerTiles().size() > 1)
944 return emitError(
"a Core stream port end can only be used in 1-to-1 "
947 if (forcesSharedMemory())
948 return emitError(
"a Core stream port end sends over the stream, not "
949 "through shared memory");
951 if (streamsFromProducer()) {
952 if (producerTile.isShimTile() || producerTile.isMemTile())
954 "a Core stream port end is not available for shim and mem tiles");
956 if (getRepeatCount().has_value())
957 return emitError(
"`repeat_count` unavailable on stream end");
959 if (getInitValues().has_value())
960 return emitError(
"`init_values` unavailable on stream end");
962 if (getIterCount().has_value())
963 return emitError(
"`iter_count` unavailable on stream end");
965 if (!getDimensionsToStream().empty())
966 return emitError(
"`dimensionsToStream` data layout transformations are "
967 "unavailable on stream end");
970 if (streamsToConsumer(0)) {
971 TileLike consTile = getTileLikeFromValue(getConsumerTiles()[0]);
972 if (consTile && (consTile.isShimTile() || consTile.isMemTile()))
974 "a Core stream port end is not available for shim and mem tiles");
977 if (!getDimensionsFromStreamPerConsumer()[0].empty())
978 return emitError(
"`dimensionsFromStreamPerConsumer` data layout "
979 "transformations are unavailable on stream end");
982 if (getInitValues().has_value()) {
983 if (producerTile.isShimTile())
984 return emitError(
"`init_values` unavailable for shim tiles");
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(
992 cast<AIEObjectFifoType>(getElemType()).getElementType())))
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");
1002 if (
auto consumerElemType = getConsumerElemType()) {
1003 auto consType = llvm::dyn_cast<AIEObjectFifoType>(*consumerElemType);
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();
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 <<
")";
1028TileOp ObjectFifoCreateOp::getProducerTileOp() {
1029 return cast<TileOp>(getProducerTile().getDefiningOp());
1039template <
typename OpTy>
1040SmallVector<OpTy> lookupAll(Operation *from, std::optional<ArrayAttr> names) {
1041 SmallVector<OpTy> ops;
1043 for (
auto name : names->getAsRange<FlatSymbolRefAttr>()) {
1045 dyn_cast_or_null<OpTy>(
lookupNamedOp(from, name.getAttr()))) {
1055TileLike ObjectFifoPoolOp::getTileLike() {
1056 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1059int64_t ObjectFifoPoolOp::getObjectSize() {
1060 return llvm::cast<MemRefType>(getElemType()).getNumElements();
1063int64_t ObjectFifoPoolOp::getObjectsPerBuffer() {
1064 if (!getContiguous())
1066 int64_t objects = getDepth();
1067 if (
auto zeros = getZeroObjects())
1068 objects += (*zeros)[0] + (*zeros)[1];
1072LogicalResult ObjectFifoPoolOp::verify() {
1074 return emitOpError(
"tile operand is not an aie.tile or aie.logical_tile");
1075 auto &target = (*this)->getParentOfType<DeviceOp>().
getTargetModel();
1080 if (
auto locks = getLocks()) {
1081 if (semaphoreLocks) {
1082 return emitOpError(
"'locks' names binary locks, which this device has "
1085 if (
static_cast<int64_t
>(locks->size()) != getDepth()) {
1086 return emitOpError(
"expects one lock per buffer");
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 "
1097 if (
auto buffers = getBuffers()) {
1098 if (getContiguous() && buffers->size() != 1) {
1099 return emitOpError(
"expects one buffer holding its objects side by side");
1101 if (!getContiguous() &&
1102 static_cast<int64_t
>(buffers->size()) != getDepth()) {
1103 return emitOpError(
"expects 'depth' buffers");
1107 if (
auto initValues = getInitValues()) {
1108 if (
static_cast<int64_t
>(initValues->size()) > getDepth()) {
1109 return emitOpError(
"has more 'init_values' than 'depth' objects");
1111 if (failed(verifyInitValues(*
this, *initValues, getElemType())))
1115 std::vector<ObjectFifoSegmentOp> segments = getSegmentOps();
1116 if (segments.empty()) {
1117 return emitOpError(
"expects at least one segment");
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");
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");
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");
1139 if (covered != getObjectSize()) {
1140 return emitOpError(
"segments cover ")
1141 << covered <<
" of " << getObjectSize() <<
" elements";
1144 if (segments.size() > 1 && !semaphoreLocks) {
1146 "multi-segment pools are unsupported on binary lock architectures");
1153 const DataLayout &layout) {
1154 return type.getNumElements() * layout.getTypeSize(type.getElementType());
1157int64_t ObjectFifoPoolOp::getObjectSizeInBytes() {
1164static bool walksWholeDepth(
bool isMemTile, int64_t depth,
1165 int64_t maxLockValue) {
1166 return isMemTile && depth > 1 && depth <= maxLockValue;
1171static bool usesPushQueue(ObjectFifoCreateOp fifo) {
1172 return fifo.getReleaseStrategy() == ObjectFifoRelease::PushQueue ||
1173 fifo.sharesSendChannel();
1176std::vector<ObjectFifoSegmentOp> ObjectFifoPoolOp::getSegmentOps() {
1177 auto ops = getSegments().getOps<ObjectFifoSegmentOp>();
1178 return {ops.begin(), ops.end()};
1181Value BufferOp::getBufferTile() {
return getTile(); }
1183SmallVector<BufferLike> ObjectFifoPoolOp::getBufferOps() {
1186 return lookupAll<BufferLike>((*this)->getParentOfType<DeviceOp>(),
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) {
1198 locks.push_back(lock);
1206StringRef ObjectFifoPoolOp::getBaseName() {
1207 StringRef name = getSymName();
1208 return name.consume_back(
"__pool") ? name : getSymName();
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() &&
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()));
1236LogicalResult verifyEndpoint(Operation *op, ObjectFifoPoolOp pool,
1237 std::optional<ArrayAttr> segments) {
1238 std::vector<ObjectFifoSegmentOp> all = pool.getSegmentOps();
1240 if (all.size() > 1) {
1241 return op->emitOpError(
1242 "must list segments explicitly for a multi-segment pool");
1246 if (segments->empty()) {
1247 return op->emitOpError(
"expects at least one segment");
1250 int64_t previous = -1;
1251 for (
auto name : segments->getAsRange<FlatSymbolRefAttr>()) {
1252 auto segment = SymbolTable::lookupNearestSymbolFrom<ObjectFifoSegmentOp>(
1253 pool, name.getAttr());
1255 return op->emitOpError(
"references undefined segment '")
1256 << name.getValue() <<
"' in pool '" << pool.getSymName() <<
"'";
1260 if (
static_cast<int64_t
>(segment.getOffset()) <= previous) {
1261 return op->emitOpError(
"segments must be named in increasing offset "
1264 previous = segment.getOffset();
1269ObjectFifoPoolOp lookupPool(Operation *op, StringRef name) {
1270 auto device = op->getParentOfType<DeviceOp>();
1271 return SymbolTable::lookupNearestSymbolFrom<ObjectFifoPoolOp>(
1272 device, StringAttr::get(op->getContext(), name));
1279static std::vector<ObjectFifoSegmentOp>
1280selectSegments(ObjectFifoPoolOp pool, std::optional<ArrayAttr> selected) {
1284 std::vector<ObjectFifoSegmentOp> all = pool.getSegmentOps();
1286 return all.empty() ? std::vector<ObjectFifoSegmentOp>{}
1287 : std::vector<ObjectFifoSegmentOp>{all.front()};
1289 std::vector<ObjectFifoSegmentOp> chosen;
1290 for (
auto name : selected->getAsRange<FlatSymbolRefAttr>()) {
1292 SymbolTable::lookupNearestSymbolFrom<ObjectFifoSegmentOp>(
1293 pool, name.getAttr())) {
1294 chosen.push_back(segment);
1300TileLike ObjectFifoCoreEndpointOp::getTileLike() {
1301 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1304ObjectFifoPoolOp ObjectFifoCoreEndpointOp::getPoolOp() {
1305 return lookupPool(*
this, getPool());
1308std::vector<ObjectFifoSegmentOp>
1309ObjectFifoCoreEndpointOp::getSelectedSegments() {
1310 return selectSegments(getPoolOp(), getSegments());
1313LogicalResult ObjectFifoCoreEndpointOp::verify() {
1315 return emitOpError(
"tile operand is not an aie.tile or aie.logical_tile");
1316 ObjectFifoPoolOp pool = getPoolOp();
1318 return emitOpError(
"references undefined pool '") << getPool() <<
"'";
1320 if (failed(verifyEndpoint(*
this, pool, getSegments()))) {
1324 if (
auto push = getCorePushAttr()) {
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");
1338 for (ObjectFifoSegmentOp segment : getSelectedSegments()) {
1339 if (next >= 0 && segment.getOffset() != next) {
1340 return emitOpError(
"a core endpoint's segments must be contiguous");
1342 next = segment.getOffset() + segment.getSize();
1347std::pair<int64_t, int64_t> ObjectFifoCoreEndpointOp::getExtent() {
1348 std::vector<ObjectFifoSegmentOp> selected = getSelectedSegments();
1349 if (selected.empty()) {
1352 int64_t offset = selected.front().getOffset();
1353 int64_t end = selected.back().getOffset() + selected.back().getSize();
1354 return {offset, end - offset};
1357MemRefType ObjectFifoCoreEndpointOp::getAccessType() {
1358 MemRefType elemType = getPoolOp().getElemType();
1359 auto [offset, size] = getExtent();
1360 if (offset == 0 && size == elemType.getNumElements()) {
1363 return cast<MemRefType>(memref::SubViewOp::inferRankReducedResultType(
1364 {size}, elemType, {offset}, {size}, {1}));
1367TileLike ObjectFifoDmaEndpointOp::getTileLike() {
1368 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1371ObjectFifoPoolOp ObjectFifoDmaEndpointOp::getPoolOp() {
1372 return lookupPool(*
this, getPool());
1375std::vector<ObjectFifoSegmentOp>
1376ObjectFifoDmaEndpointOp::getSelectedSegments() {
1377 return selectSegments(getPoolOp(), getSegments());
1380int64_t ObjectFifoDmaEndpointOp::getNumDescriptors() {
1381 ObjectFifoPoolOp pool = getPoolOp();
1384 if (pool.getContiguous()) {
1386 if (!walksStream()) {
1387 SmallVector<ObjectFifoDmaEndpointOp> ends =
turnEndpoints(*
this);
1390 ArrayRef<Attribute> turns = getTurnsAttr().getValue();
1391 SmallVector<std::pair<int64_t, int64_t>> counts;
1392 for (ObjectFifoDmaEndpointOp end : ends)
1394 {llvm::count(turns, FlatSymbolRefAttr::get(end.getSymNameAttr())),
1395 end.getPoolOp().getContiguous() ? 0 : end.getNumDescriptors()});
1396 return llvm::count(turns, FlatSymbolRefAttr::get(getSymNameAttr())) *
1400 return succeeded(getStreamWindow(window)) ? window.
outputs : 0;
1402 return pool.getDepth() * getSelectedSegments().size();
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();
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();
1420 getPoolOp().getObjectSize(),
1421 [&] {
return emitOpError(); }, window);
1424int64_t ObjectFifoDmaEndpointOp::getRepeat() {
1425 ObjectFifoPoolOp pool = getPoolOp();
1427 return pool && drains() ? pool.getRepeatCount().value_or(1) : 1;
1430bool ObjectFifoDmaEndpointOp::repeatsInHardware() {
1431 return getRepeat() > 1 &&
1432 (getReleaseStrategy() == ObjectFifoRelease::PushQueue ||
1433 (getNumDescriptors() == 1 && !getIterCount()));
1436int64_t ObjectFifoDmaEndpointOp::getDispatchPasses() {
1437 ObjectFifoPoolOp pool = getPoolOp();
1438 std::optional<ArrayAttr> turns = getDispatch();
1439 if (!pool || !turns || turns->empty())
1441 int64_t depth = std::max<int64_t>(pool.getDepth(), 1);
1442 return std::lcm(depth,
static_cast<int64_t
>(turns->size())) / depth;
1445SmallVector<ObjectFifoDmaEndpointOp>
1447 SmallVector<ObjectFifoDmaEndpointOp> ends;
1448 if (std::optional<ArrayAttr> turns = endpoint.getTurns())
1449 for (
auto name : turns->getAsRange<FlatSymbolRefAttr>())
1451 SymbolTable::lookupNearestSymbolFrom<ObjectFifoDmaEndpointOp>(
1453 end && !llvm::is_contained(ends, end))
1454 ends.push_back(end);
1460 for (
auto [appearances, count] : ends)
1462 passes = std::lcm(passes, count / std::gcd(count, appearances));
1466int64_t ObjectFifoDmaEndpointOp::getNumBDs() {
1467 SmallVector<ObjectFifoDmaEndpointOp> ends =
turnEndpoints(*
this);
1469 return getNumDescriptors() * (repeatsInHardware() ? 1 : getRepeat()) *
1470 getDispatchPasses();
1471 if (ends.front() != *
this)
1473 ArrayRef<Attribute> turns = getTurnsAttr().getValue();
1474 SmallVector<std::pair<int64_t, int64_t>> counts;
1475 for (ObjectFifoDmaEndpointOp end : ends)
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());
1482DMAChannelDir ObjectFifoDmaEndpointOp::getRouteDirection() {
1483 return drains() ? DMAChannelDir::MM2S : DMAChannelDir::S2MM;
1486WireBundle ObjectFifoDmaEndpointOp::getRouteBundle() {
return WireBundle::DMA; }
1488std::optional<int> ObjectFifoDmaEndpointOp::getRouteChannel() {
1489 return getChannelIndex();
1492void ObjectFifoDmaEndpointOp::setRouteChannel(
int channel) {
1493 setChannelIndex(channel);
1496LogicalResult ObjectFifoDmaEndpointOp::verify() {
1498 return emitOpError(
"tile operand is not an aie.tile or aie.logical_tile");
1499 ObjectFifoPoolOp pool = getPoolOp();
1501 return emitOpError(
"references undefined pool '") << getPool() <<
"'";
1504 if (failed(verifyEndpoint(*
this, pool, getSegments()))) {
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");
1520 "push_queue repeat_count exceeds the hardware task limit");
1521 if (getOutOfOrder() && getRepeat() > 1)
1523 "push_queue cannot repeat out-of-order packets: "
1524 "each repetition may need a different destination BD ID");
1527 if (std::optional<ArrayAttr> turns = getDispatch()) {
1529 return emitOpError(
"only a draining endpoint can dispatch");
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)";
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>())
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,
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");
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";
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";
1584 auto padding = getPadDimensions();
1585 if (padding && padding->size() != selectedCount) {
1586 return emitOpError(
"padDimensions has ")
1587 << padding->size() <<
" entries for " << selectedCount
1588 <<
" selected segments";
1590 if (padding && !drains()) {
1591 return emitOpError(
"padDimensions is only valid on a draining endpoint");
1593 if (getPadValue() != 0 &&
1594 (!padding || llvm::none_of(*padding, [](BDPadLayoutArrayAttr entry) {
1595 return !entry.empty();
1597 return emitOpError(
"nonzero padValue requires a non-empty padDimensions "
1604 return getStreamWindow(window);
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";
1616 if (dims && pads && !pads.empty() && dims.size() != pads.size()) {
1617 return emitOpError(
"dimensions and padDimensions entry ")
1618 << position <<
" have different ranks";
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();
1631TileLike RouteEndpointOp::getTileLike() {
1632 return dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
1635DMAChannelDir RouteEndpointOp::getRouteDirection() {
1638 auto device = getOperation()->getParentOfType<DeviceOp>();
1639 StringRef name = getSymName();
1641 for (
auto flow : device.getOps<RouteOp>()) {
1642 if (flow.namesAsSource(name)) {
1643 return DMAChannelDir::MM2S;
1645 named |= flow.namesAsDestination(name);
1647 assert(named &&
"endpoint is named by no flow, so it has no direction to "
1648 "read; --aie-objectfifo-verify rejects this");
1650 return DMAChannelDir::S2MM;
1653WireBundle RouteEndpointOp::getRouteBundle() {
return getBundle(); }
1655std::optional<int> RouteEndpointOp::getRouteChannel() {
1656 return getChannelIndex();
1659void RouteEndpointOp::setRouteChannel(
int channel) { setChannelIndex(channel); }
1666verifyConsumedBy(Operation *op, ArrayAttr proofs,
bool shimInput,
1668 function_ref<
bool(FlatSymbolRefAttr)> namesShimOutput) {
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
1679LogicalResult RouteEndpointOp::verify() {
1680 TileLike tile = getTileLike();
1682 return emitOpError(
"tile operand is not an aie.tile or aie.logical_tile");
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);
1698 if (!sources.empty() && !dests.empty()) {
1699 return emitOpError(
"is named as both a source and a destination, so its "
1700 "direction is ambiguous");
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 "
1707 << sharers.size() <<
" times";
1708 llvm::SmallDenseSet<int> ids;
1709 for (RouteOp flow : sources) {
1710 std::optional<uint16_t>
id = flow.getPacketAttr().getPktId();
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 "
1717 <<
static_cast<int>(*id) <<
"; each needs its own";
1720 if (llvm::any_of(dests, [&](RouteOp flow) {
1721 return flow.getKeepPktHeader() != dests[0].getKeepPktHeader();
1723 return emitOpError(
"receives several packet flows, so they must agree "
1724 "on keep_pkt_header");
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();
1740 switch (getBundle()) {
1741 case WireBundle::DMA:
1745 case WireBundle::PLIO:
1746 if (!tile.isShimTile()) {
1747 return emitOpError(
"a PLIO end is on a shim");
1750 case WireBundle::Core:
1753 return emitOpError(
"bundle must be DMA, PLIO or Core");
1763static ParseResult parseRouteSources(OpAsmParser &parser, ArrayAttr &sources) {
1764 SmallVector<Attribute> names;
1765 auto parseOne = [&]() -> ParseResult {
1766 FlatSymbolRefAttr name;
1767 if (parser.parseAttribute(name))
1769 names.push_back(name);
1772 if (succeeded(parser.parseOptionalLSquare())) {
1773 if (failed(parser.parseOptionalRSquare()) &&
1774 (parser.parseCommaSeparatedList(parseOne) || parser.parseRSquare()))
1776 }
else if (parseOne()) {
1779 sources = parser.getBuilder().getArrayAttr(names);
1783static void printRouteSources(OpAsmPrinter &p, Operation *, ArrayAttr sources) {
1784 if (sources.size() == 1) {
1785 p.printAttribute(sources[0]);
1789 llvm::interleaveComma(sources, p,
1790 [&](Attribute name) { p.printAttribute(name); });
1794LogicalResult RouteOp::verify() {
1795 if (getSources().empty()) {
1796 return emitOpError(
"expects at least one source");
1798 if (getDestinations().empty()) {
1799 return emitOpError(
"expects at least one destination");
1802 if (getKeepPktHeader() && !getPacket()) {
1803 return emitOpError(
"keep_pkt_header is only meaningful on a packet flow");
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)));
1812 llvm::SmallDenseSet<StringRef> seen;
1813 for (StringRef source : getSourceNames()) {
1814 if (!lookup(source)) {
1815 return emitOpError(
"source '") << source <<
"' is not an endpoint";
1817 if (!seen.insert(source).second) {
1818 return emitOpError(
"names '@") << source <<
"' as a source twice";
1821 for (StringRef destination : getDestinationNames()) {
1822 if (!lookup(destination)) {
1823 return emitOpError(
"destination '")
1824 << destination <<
"' is not an endpoint";
1826 if (!seen.insert(destination).second) {
1827 return emitOpError(
"names '@")
1829 <<
"' more than once; an end is a source or a "
1830 "destination, and only one of each";
1836 if (isFanIn() && !getPacket()) {
1837 return emitOpError(
"has several sources, so it needs a `packet` header; "
1838 "a circuit cannot merge streams");
1844ObjectFifoCreateOp::getDimensionsFromStream(Value consumerTile) {
1846 for (
auto cons : getConsumerTiles()) {
1847 if (cons == consumerTile)
1851 return getDimensionsFromStreamPerConsumer()[dimsIndex];
1855 OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
1856 BDDimLayoutArrayAttr &dimensions) {
1857 std::vector<BDDimLayoutAttr> emptyDims = {};
1858 if (parser.parseOperand(operand))
1860 if (succeeded(parser.parseOptionalKeyword(
"dimensionsToStream"))) {
1861 if (parser.parseCustomAttributeWithFallback<BDDimLayoutArrayAttr>(
1867 BDDimLayoutArrayAttr::get(parser.getContext(), ArrayRef(emptyDims));
1873 Operation *op, Value operand,
1874 BDDimLayoutArrayAttr dimensions) {
1876 if (!dimensions.empty()) {
1877 printer <<
" dimensionsToStream ";
1878 printer.printStrippedAttrOrType(dimensions);
1883 Attribute &channel) {
1885 if (succeeded(parser.parseOptionalSymbolName(name))) {
1886 channel = FlatSymbolRefAttr::get(name);
1890 if (parser.parseInteger(index))
1892 channel = parser.getBuilder().getI32IntegerAttr(index);
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";
1906 return success(resolved);
1910 Attribute channel) {
1911 if (
auto index = dyn_cast<IntegerAttr>(channel))
1912 printer << index.getInt();
1914 printer.printAttributeWithoutType(channel);
1919 ObjectFifoPortAttr &port,
1920 SmallVectorImpl<Type> &objects) {
1921 if (parser.parseLParen())
1925 SMLoc portLoc = parser.getCurrentLocation();
1926 if (succeeded(parser.parseOptionalKeyword(&portName))) {
1927 std::optional<ObjectFifoPort> parsed = symbolizeObjectFifoPort(portName);
1929 return parser.emitError(portLoc,
"invalid objectFifo port: ") << portName;
1930 port = ObjectFifoPortAttr::get(parser.getContext(), *parsed);
1931 if (parser.parseComma())
1936 SMLoc countLoc = parser.getCurrentLocation();
1937 if (parser.parseInteger(count) || parser.parseRParen() ||
1938 parser.parseColon() || parser.parseTypeList(objects))
1941 if (count !=
static_cast<int64_t
>(objects.size()))
1942 return parser.emitError(countLoc,
"acquires ")
1943 << count <<
" objects but names " << objects.size() <<
" of them";
1949 ObjectFifoPortAttr port,
1950 TypeRange objects) {
1953 printer << stringifyObjectFifoPort(port.getValue()) <<
", ";
1954 printer << objects.size() <<
") : ";
1955 llvm::interleaveComma(objects, printer);
1959 ObjectFifoPortAttr &port,
1960 IntegerAttr &size) {
1961 if (parser.parseLParen())
1965 SMLoc portLoc = parser.getCurrentLocation();
1966 if (succeeded(parser.parseOptionalKeyword(&portName))) {
1967 std::optional<ObjectFifoPort> parsed = symbolizeObjectFifoPort(portName);
1969 return parser.emitError(portLoc,
"invalid objectFifo port: ") << portName;
1970 port = ObjectFifoPortAttr::get(parser.getContext(), *parsed);
1971 if (parser.parseComma())
1976 if (parser.parseInteger(count) || parser.parseRParen())
1978 size = parser.getBuilder().getI32IntegerAttr(count);
1984 ObjectFifoPortAttr port,
1988 printer << stringifyObjectFifoPort(port.getValue()) <<
", ";
1989 printer << size.getInt() <<
")";
1993 OpAsmParser &parser, SmallVectorImpl<OpAsmParser::UnresolvedOperand> &tiles,
1994 BDDimLayoutArrayArrayAttr &dimensions) {
1997 std::vector<BDDimLayoutArrayAttr> tileDims = {};
1999 auto parseOneOperand = [&]() -> ParseResult {
2000 if (parser.parseOperand(tiles.emplace_back(),
true)) {
2006 BDDimLayoutArrayAttr dimAttr =
2007 BDDimLayoutArrayAttr::get(parser.getContext(), {});
2009 if (succeeded(parser.parseOptionalKeyword(
"dimensionsFromStream"))) {
2011 if (parser.parseCustomAttributeWithFallback<BDDimLayoutArrayAttr>(
2016 tileDims.emplace_back(dimAttr);
2020 if (parser.parseCommaSeparatedList(AsmParser::Delimiter::None,
2021 parseOneOperand,
" in operand list"))
2024 dimensions = BDDimLayoutArrayArrayAttr::get(parser.getContext(), tileDims);
2029 OpAsmPrinter &printer, Operation *op, OperandRange tiles,
2030 BDDimLayoutArrayArrayAttr dimsPerTileAttr) {
2032 for (
auto tile : tiles) {
2034 if (dimsPerTileAttr && tileIdx < dimsPerTileAttr.size() &&
2035 dimsPerTileAttr[tileIdx] && !dimsPerTileAttr[tileIdx].empty()) {
2036 printer <<
" dimensionsFromStream ";
2037 printer.printStrippedAttrOrType(dimsPerTileAttr[tileIdx]);
2039 if (tileIdx < tiles.size() - 1) {
2046static void printObjectFifoConsumerElemType(OpAsmPrinter &p,
2047 ObjectFifoCreateOp op,
2048 TypeAttr consumerElemType) {
2049 if (consumerElemType)
2050 p <<
" -> " << consumerElemType;
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 {
2060 if (parser.parseKeyword(&kw)) {
2063 auto bundle = symbolizeWireBundle(kw);
2065 return parser.emitError(parser.getCurrentLocation(),
2066 "invalid wire bundle '" + kw +
"'");
2068 out.push_back(
static_cast<int32_t
>(*bundle));
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)) {
2082 inChannels.push_back(inChan);
2083 egChannels.push_back(egChan);
2086 if (parser.parseCommaSeparatedList(AsmParser::Delimiter::Paren, parseOne)) {
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);
2102 DenseI32ArrayAttr ingressBundles,
2103 DenseI32ArrayAttr ingressChannels,
2104 DenseI32ArrayAttr egressBundles,
2105 DenseI32ArrayAttr egressChannels) {
2110 for (
size_t i = 0; i < vias.size(); i++) {
2114 printer << vias[i] <<
" : "
2115 << stringifyWireBundle(
static_cast<WireBundle
>(ingressBundles[i]))
2116 <<
" : " << ingressChannels[i] <<
" -> "
2117 << stringifyWireBundle(
static_cast<WireBundle
>(egressBundles[i]))
2118 <<
" : " << egressChannels[i];
2123static ParseResult parseObjectFifoConsumerElemType(OpAsmParser &parser,
2124 TypeAttr &consumerElemType) {
2125 if (failed(parser.parseOptionalArrow()))
2128 if (parser.parseType(type))
2130 consumerElemType = TypeAttr::get(type);
2134static void printObjectFifoInitValues(OpAsmPrinter &p, ObjectFifoCreateOp op,
2135 Attribute numElem, TypeAttr type,
2136 Attribute initValues) {
2137 if (op.getInitValues()) {
2143 if (isa<ArrayAttr>(numElem)) {
2145 llvm::cast<mlir::IntegerAttr>(llvm::cast<mlir::ArrayAttr>(numElem)[0])
2148 depth = llvm::cast<mlir::IntegerAttr>(numElem).getInt();
2150 for (
int i = 0; i < depth; i++) {
2151 p.printStrippedAttrOrType(llvm::cast<mlir::ArrayAttr>(initValues)[i]);
2152 if (i < depth - 1) {
2160static ParseResult parseObjectFifoInitValues(OpAsmParser &parser,
2161 Attribute numElem, TypeAttr type,
2162 Attribute &initValues) {
2164 if (isa<ArrayAttr>(numElem)) {
2166 llvm::cast<mlir::IntegerAttr>(llvm::cast<mlir::ArrayAttr>(numElem)[0])
2169 depth = llvm::cast<mlir::IntegerAttr>(numElem).getInt();
2171 auto objfifoType = llvm::cast<AIEObjectFifoType>(type.getValue());
2172 auto memrefType = llvm::cast<MemRefType>(objfifoType.getElementType());
2174 if (!memrefType.hasStaticShape())
2175 return parser.emitError(parser.getNameLoc())
2176 <<
"type should be static shaped memref, but got " << memrefType;
2178 if (parser.parseOptionalEqual())
2181 Type tensorType = mlir::memref::getTensorTypeFromMemRefType(memrefType);
2182 if (parser.parseAttribute(initValues, tensorType))
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";
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))
2208 return std::nullopt;
2211std::optional<ObjectFifoAllocateOp> ObjectFifoCreateOp::getAllocate() {
2212 for (ObjectFifoAllocateOp alloc :
2213 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoAllocateOp>())
2214 if (alloc.getObjFifoName() == name().getValue())
2216 return std::nullopt;
2219bool ObjectFifoCreateOp::delegateReaches(
const AIETargetModel &target,
2223 return llvm::all_of(std::array{producer, consumer}, [&](
TileID end) {
2225 return s == SharedMemory::First || s == SharedMemory::Either;
2229bool ObjectFifoCreateOp::allocatedHome(
const AIETargetModel &target,
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);
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))
2246 if (link.getOptionalSharedTile() && link.getPoolOwner() == *
this)
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;
2266 ObjectFifoCreateOp owner = link.getPoolOwner();
2269 if (owner.getElemType() != getElemType())
2274std::optional<StringRef> ObjectFifoCreateOp::dmaReason() {
2276 return "it asks for a dma transport";
2277 if (getRepeatCount())
2278 return "it repeats objects (`repeat_count`)";
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())
2289 return "a consumer reshapes the data (`dimensionsFromStream`)";
2292 if (getLink() && !getAllocate())
2293 return "it is linked through a tile's DMAs";
2294 return std::nullopt;
2299 std::optional<TileID> delegate, std::optional<TileID> linkTile) {
2304 allocatedHome(target, producer, consumer, *delegate, linkTile)) {
2306 return own == SharedMemory::None ? SharedMemory::Either : own;
2309 return SharedMemory::None;
2313static std::optional<TileID> placedAt(Value tile) {
2314 auto tileLike = dyn_cast_or_null<TileLike>(tile.getDefiningOp());
2316 return std::nullopt;
2317 std::optional<int> col = tileLike.tryGetCol(), row = tileLike.tryGetRow();
2319 return std::nullopt;
2320 return TileID{*col, *row};
2323std::optional<StringRef>
2325 if (std::optional<StringRef> reason = dmaReason())
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,
2342 return link ?
"it is linked through a tile's DMAs"
2343 :
"its ends share no memory module";
2344 return std::nullopt;
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;
2364 return StringRef(
"push_queue requires producer releases in a local core "
2365 "to submit send tasks");
2366 return std::nullopt;
2369std::optional<StringRef>
2370ObjectFifoCreateOp::sharedReceiveRefusal(
bool shim,
bool outOfOrder) {
2372 return StringRef(
"a shim's receiving channel writes into the runtime's "
2373 "tasks, which no object header picks");
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;
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;
2385 auto byDMA = [](ObjectFifoCreateOp fifo) {
2387 return fifo.placedDmaReason(shared).has_value();
2389 std::optional<int> channel = pinned(*
this);
2390 Value tile = getProducerTile();
2391 if (!channel || cast<TileLike>(tile.getDefiningOp()).isShimTile() ||
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)) &&
2406int ObjectFifoCreateOp::dmaDepth(std::optional<unsigned> consumer) {
2407 if (consumer ? streamsToConsumer(*consumer) : streamsFromProducer())
2409 if (!consumer && getInitValues())
2411 if (consumer && isa<ArrayAttr>(getElemNumber()))
2412 return size(*consumer + 1);
2418 Value tile = consumer ? getConsumerTiles()[*consumer] : getProducerTile();
2419 ObjectFifoPort port =
2420 consumer ? ObjectFifoPort::Consume : ObjectFifoPort::Produce;
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());
2428 if (maxAcquire == 0)
2430 if (maxAcquire == 1 && size() == 1)
2432 return maxAcquire + 1;
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())
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)
2458std::optional<PlannedDmaEnd>
2459ObjectFifoCreateOp::plannedDmaEnd(std::optional<unsigned> consumer) {
2460 return plannedDmaEnd(consumer, placedAt);
2463std::optional<PlannedDmaEnd>
2464ObjectFifoCreateOp::plannedDmaEnd(std::optional<unsigned> consumer,
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);
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();
2488 auto ordered = [](ObjectFifoCreateOp fifo,
bool drains) {
2489 return !fifo.getOutOfOrder() && (!drains || !usesPushQueue(fifo));
2492 int depth = dmaDepth(consumer);
2496 static_cast<int>(*consumer),
2498 walkable(depth) && ordered(*
this,
false),
2499 objectBytes(getConsumerElemTypeOrDefault()),
2502 int64_t repeat = getRepeatCount().value_or(1);
2504 repeat > 1 && (usesPushQueue(*
this) || (depth == 1 && !getIterCount()));
2509 walkable(depth) && ordered(*
this,
true) &&
2510 !getRepeatCount() &&
2511 getDimensionsToStream().empty(),
2512 objectBytes(getElemType()),
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)) {
2525 return std::nullopt;
2529 int64_t depth = link.getPoolDepth(positions);
2530 int64_t segments = link.getPoolSegments().size();
2532 (drains ? link.isDistribute() : link.isJoin()) ? 1 : segments;
2533 int64_t descriptors = depth * selected;
2534 int64_t contiguousObjects = 0;
2535 if (link.walksStream()) {
2537 bool inferred = succeeded(link.getStreamWindow(window));
2538 descriptors = !drains ? 1 : inferred ? window.
outputs : 0;
2540 contiguousObjects = depth + window.
top + window.
bottom;
2542 int64_t repeat = drains ? link.getRepeatCount().value_or(1) : 1;
2543 bool inHardware = repeat > 1 && ((drains && usesPushQueue(*
this)) ||
2544 (descriptors == 1 && !getIterCount()));
2546 if (drains && link.isDispatch()) {
2547 int64_t objects = std::max<int64_t>(depth, 1);
2549 std::lcm(objects,
static_cast<int64_t
>(link.getFifoOuts().size())) /
2553 llvm::any_of(link.getOutputObjectFifos(), [](ObjectFifoCreateOp out) {
2554 return !out.getDimensionsToStream().empty();
2559 link.getOutputObjectFifos(),
2560 [&](ObjectFifoCreateOp out) { return ordered(out, true); }) &&
2562 llvm::all_of(link.getInputObjectFifos(),
2563 [&](ObjectFifoCreateOp in) { return ordered(in, false); }));
2564 return PlannedDmaEnd{descriptors * (inHardware ? 1 : repeat) * passes,
2568 walkable(depth) && segments == 1 &&
2569 !link.getRepeatCount() && !link.walksStream() &&
2570 !link.isDispatch() && !drainLaysOut && linkOrdered,
2571 objectBytes(link.getPoolOwner().getElemType()),
2576bool ObjectFifoCreateOp::canTakeTurns() {
2577 if (getConsumerTiles().size() != 1)
2579 auto pinned = [](ObjectFifoEndPortAttr port) {
2580 return port && (port.isCore() || port.channelIndex());
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));
2591 if (link.isMerge() && llvm::is_contained(link.getInputObjectFifos(), *
this))
2594 return ObjectFifoDmaEndpointOp::canTakeTurns(
2595 usesPushQueue(*
this),
2596 pinned(getProdPortAttr()) || pinned(getConsumerPort(0)), dispatch,
2597 packetHeader() !=
nullptr, getIterCount().has_value(), repeat,
2601bool ObjectFifoDmaEndpointOp::canTakeTurns(
bool pushQueue,
bool pinned,
2602 bool dispatch,
bool packet,
2603 bool iterates, int64_t repeat,
2605 return !pushQueue && !pinned && !dispatch && !packet && !iterates &&
2606 repeat == 1 && !walksStream;
2609int ObjectFifoCreateOp::sharedDepth() {
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));
2621LogicalResult ObjectFifoAllocateOp::verify() {
2622 ObjectFifoCreateOp objFifo = getObjectFifo();
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");
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: ")
2640 ObjectFifoLinkOp link = *linked;
2641 auto producer = dyn_cast<TileOp>(objFifo.getProducerTile().getDefiningOp());
2643 dyn_cast<TileOp>(objFifo.getConsumerTiles()[0].getDefiningOp());
2644 auto delegate = dyn_cast<TileOp>(getDelegateTile().getDefiningOp());
2646 std::optional<Value> linkPoint = link.getOptionalSharedTile();
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();
2656 InFlightDiagnostic diag = emitOpError(
"places @")
2657 << name <<
"'s objects in the link's pool";
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 "
2665 << name <<
"'s is " << objFifo.getElemType().getElementType()
2670 diag <<
", which starts with @" << link.getPoolOwner().name().getValue()
2671 <<
"'s initial objects, "
2672 <<
"but @" << name <<
" has initial objects of its own";
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";
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";
2685 diag <<
", but @" << name
2686 <<
" is one link's output and another link's input, so its "
2687 "objects would be both links' pools";
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";
2703TileOp ObjectFifoAllocateOp::getDelegateTileOp() {
2704 return cast<TileOp>(getDelegateTile().getDefiningOp());
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);
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;
2732 if (isJoin() && isDistribute())
2733 return emitError(
"ObjectFifoLinkOp does not support 'join' and "
2734 "'distribute' at the same time");
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 "
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 "
2752 << fifo.name().getValue() <<
"' carries " << fifo.getElemType()
2753 <<
" and '" << fifos.front().name().getValue() <<
"' carries "
2754 << fifos.front().getElemType();
2757 for (ObjectFifoCreateOp out : outs)
2758 if (out.getConsumerTiles().size() != 1)
2759 return emitOpError(
"each turn of a dispatch reaches one consumer, "
2761 << out.name().getValue() <<
"' has "
2762 << out.getConsumerTiles().size();
2765 PacketInfoAttr pinned;
2766 for (ObjectFifoCreateOp in : getInputObjectFifos()) {
2767 PacketInfoAttr header = in.packetHeader();
2768 if (!header || !header.isAssigned())
2770 if (pinned && pinned != header)
2771 return emitOpError(
"a merge is one route with one header, but its "
2772 "inputs pin different ones");
2778 auto sharedTile = getOptionalSharedTile();
2780 return emitError(
"ObjectFifoLinkOp must have a link point, i.e., a "
2781 "shared tile between objectFifos");
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";
2798 DenseMap<Operation *, size_t> reads;
2800 (*this)->getParentOfType<DeviceOp>().getOps<ObjectFifoLinkOp>()) {
2801 if (other == *
this) {
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)
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");
2820 llvm::dyn_cast_or_null<TileLike>(sharedTile.value().getDefiningOp());
2822 return emitError(
"shared tile must implement TileLike interface");
2826 if (isJoin() || isDistribute()) {
2827 if (tile.isShimTile())
2828 return emitError(
"ObjectFifoLinkOp join and distribute are "
2829 "unavailable on shim tiles");
2832 return emitError(
"ObjectFifoLinkOp join and distribute require "
2833 "semaphore locks, which this device lacks");
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");
2841 auto elementsOf = [](Type objectFifoType) {
2842 return cast<MemRefType>(
2843 cast<AIEObjectFifoType>(objectFifoType).getElementType())
2847 DataLayout dataLayout = DataLayout::closest(getOperation());
2848 auto bytesOf = [&](Type objectFifoType, int64_t elements) {
2850 static_cast<int64_t
>(dataLayout.getTypeSize(
2852 cast<AIEObjectFifoType>(objectFifoType).getElementType())
2853 .getElementType()));
2855 auto checkSlot = [&](StringRef role, ObjectFifoCreateOp participant,
2856 int64_t object, ObjectFifoCreateOp shared,
2857 int64_t slotBytes, ArrayAttr offsets) -> LogicalResult {
2859 return emitOpError() << role <<
" @" << participant.name().getValue()
2860 <<
" has empty objects";
2861 if (slotBytes %
object == 0)
2863 std::string offsetText;
2864 llvm::raw_string_ostream os(offsetText);
2865 llvm::interleaveComma(offsets, os, [&](Attribute offset) {
2866 os << *getConstantIntValue(offset);
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";
2876 if (getFifoIns().size() != getSrcOffsets().size())
2877 return emitOpError(
"number of provided src offsets must be equal "
2878 "to the number of input objectFifos");
2880 if (!getDstOffsets().empty())
2881 return emitOpError(
"dst offsets should be empty for join");
2885 for (
auto [idx, len] : llvm::enumerate(getJoinTransferLengths()))
2887 return emitOpError(
"src offsets must increase: input objectFifo ")
2888 << idx <<
" would transfer " << len <<
" elements";
2890 ObjectFifoCreateOp fifoOut = getOutputObjectFifos()[0];
2891 for (
auto [fifoIn, slot] :
2892 llvm::zip(getInputObjectFifos(), getJoinTransferLengths())) {
2894 fifoIn.getConsumerElemType()
2895 ? bytesOf(fifoIn.getConsumerElemTypeOrDefault(),
2896 elementsOf(fifoIn.getConsumerElemTypeOrDefault()))
2897 : bytesOf(fifoIn.getElemType(),
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),
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;
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) <<
".";
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");
2928 if (!getSrcOffsets().empty())
2929 return emitOpError(
"src offsets should be empty for distribute");
2931 for (
auto [idx, len] : llvm::enumerate(getDistributeTransferLengths()))
2933 return emitOpError(
"dst offsets must increase: output objectFifo ")
2934 << idx <<
" would transfer " << len <<
" elements";
2936 ObjectFifoCreateOp fifoIn = getInputObjectFifos()[0];
2937 for (
auto [fifoOut, slot] :
2938 llvm::zip(getOutputObjectFifos(), getDistributeTransferLengths())) {
2940 if (failed(checkSlot(
2942 bytesOf(fifoOut.getElemType(), elementsOf(fifoOut.getElemType())),
2944 bytesOf(fifoIn.getElemType(),
2946 fifoOut.getPadDimensions().value_or(
2947 ArrayRef<BDPadLayoutAttr>{}),
2954 for (
size_t seen = 0; end < fifoIn.getConsumerTiles().size(); end++)
2955 if (fifoIn.getConsumerTiles()[end] == *sharedTile &&
2956 seen++ == reads.lookup(fifoIn))
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;
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) <<
".";
2976 if (!getSrcOffsets().empty() && !getDstOffsets().empty())
2977 return emitOpError(
"all offsets should be empty if there is no "
2978 "join or distribute");
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();
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 "
2995 <<
"-element object; to send part of each input object, walk "
2996 "the stream (an outer dimension stepping whole input "
3001 if (walksStream()) {
3003 if (failed(getStreamWindow(window)))
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");
3017 return emitOpError() <<
"a walk over a stream of " << window.
objects
3018 <<
" objects needs a lock counting that many, "
3019 "but locks count to "
3023 std::optional<int> col = tile.tryGetCol(), row = tile.tryGetRow();
3024 for (
int r = 0; (!col || !row) && r < target.
rows(); ++r) {
3030 std::optional<int64_t> poolBds;
3033 *col, *row, DMAChannelDir::MM2S);
3034 channel < channels; ++channel)
3036 std::min<int64_t>(poolBds.value_or(INT64_MAX),
3038 DMAChannelDir::MM2S));
3039 int64_t bds = poolBds.value_or(target.
getNumBDs(AIETileType::MemTile) / 2);
3041 return emitOpError() <<
"a walk over a stream lowers to one descriptor "
3043 << window.
outputs <<
", but a MemTile channel has "
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: "
3059 << first.name().getValue() <<
" has " << repeat
3060 << (first.getRepeatCount() ?
"" :
" (default)") <<
", @"
3061 << fifo.name().getValue() <<
" has " << otherRepeat
3062 << (fifo.getRepeatCount() ?
"" :
" (default)");
3069std::optional<Value> ObjectFifoLinkOp::getOptionalSharedTile() {
3070 std::vector<ObjectFifoCreateOp> fifoIn = getInputObjectFifos();
3071 std::vector<ObjectFifoCreateOp> fifoOut = getOutputObjectFifos();
3073 if (fifoIn.size() < getFifoIns().size() ||
3074 fifoOut.size() < getFifoOuts().size() || fifoIn.empty() ||
3081 Value tile = fifoOut[0].getProducerTile();
3082 for (
auto in : fifoIn)
3083 if (!llvm::is_contained(in.getConsumerTiles(), tile))
3088 if (isDistribute()) {
3089 Value tile = fifoOut[0].getProducerTile();
3090 for (
auto out : fifoOut)
3091 if (out.getProducerTile() != tile)
3093 if (!llvm::is_contained(fifoIn[0].getConsumerTiles(), tile))
3098 for (
auto consumerIn : fifoIn[0].getConsumerTiles())
3099 if (consumerIn == fifoOut[0].getProducerTile())
3100 return {fifoOut[0].getProducerTile()};
3104bool ObjectFifoLinkOp::walksStream() {
3105 if (isJoin() || isDistribute())
3107 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
3110 ArrayRef<BDDimLayoutAttr> dims = outs[0].getDimensionsToStream();
3111 if (dims.size() < 2 || dims.front().getSize() < 2)
3114 for (BDDimLayoutAttr dim : dims.drop_front())
3115 inner *= dim.getSize();
3116 int64_t objectSize =
3117 cast<AIEObjectFifoType>(getInputObjectFifos()[0].getElemType())
3121 return getDimsMaxIdx(dims) >= objectSize &&
3122 inner == cast<AIEObjectFifoType>(outs[0].getElemType())
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())
3134 out.getDimensionsToStream(), pads,
3135 cast<AIEObjectFifoType>(in.getElemType())
3138 [&] { return emitOpError(); }, window);
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;
3148 if (owner.getConsumerLink(index) == *
this)
3150 return std::nullopt;
3153int64_t ObjectFifoLinkOp::getPoolDepth() {
return getPoolDepth(placedAt); }
3155int64_t ObjectFifoLinkOp::getPoolDepth(
TilePositions positions) {
3160 LinkPoolPlan plan{getOptionalSharedTile().value_or(Value()), 0, {}};
3162 if (walksStream()) {
3163 plan.
depth = succeeded(getStreamWindow(window)) ? window.
objects : 0;
3166 ObjectFifoCreateOp owner = getPoolOwner();
3167 if (!owner.getAllocate()) {
3168 std::optional<unsigned> index = getOwnerConsumerIndex();
3169 plan.
depth = index ? owner.dmaDepth(index) : owner.size();
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();
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 &&
3187 {fifo.getProducerTile(), fifo.getConsumerTiles()[0],
3188 alloc->getDelegateTile(),
3189 llvm::is_contained(outs, fifo) ? fifo.dmaDepth(0)
3190 : fifo.dmaDepth(std::nullopt)});
3197 int64_t result =
depth;
3198 std::optional<TileID> link =
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,
3207 result = std::max(result, sharer.depth);
3212ObjectFifoCreateOp ObjectFifoLinkOp::getPoolOwner() {
3213 std::vector<ObjectFifoCreateOp> ins = getInputObjectFifos();
3214 std::vector<ObjectFifoCreateOp> outs = getOutputObjectFifos();
3215 if (isJoin() || isMerge())
3217 if (isDistribute() || isDispatch())
3222 auto count = [](ObjectFifoCreateOp fifo) {
3223 return cast<AIEObjectFifoType>(fifo.getElemType())
3228 if (outs[0].getInitValues() ||
3229 (count(outs[0]) > count(ins[0]) && !outs[0].getPadDimensions()))
3234SmallVector<std::pair<int64_t, int64_t>> ObjectFifoLinkOp::getPoolSegments() {
3235 auto count = [](ObjectFifoCreateOp fifo) {
3236 return cast<AIEObjectFifoType>(fifo.getElemType())
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()
3252 int64_t size = next - offset;
3254 size = count(participant);
3255 segments.emplace_back(offset, size);
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);
3269 if (
auto *st = SymbolTable::lookupSymbolIn(parent, name);
3270 isa_and_nonnull<ObjectFifoCreateOp>(st))
3271 inputObjFifos.push_back(cast<ObjectFifoCreateOp>(st));
3275 return inputObjFifos;
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);
3287 if (
auto *st = mlir::SymbolTable::lookupSymbolIn(parent, name);
3288 isa_and_nonnull<ObjectFifoCreateOp>(st))
3289 outputObjFifos.push_back(cast<ObjectFifoCreateOp>(st));
3293 return outputObjFifos;
3296std::vector<int> ObjectFifoLinkOp::getJoinTransferLengths() {
3297 std::vector<int> lengths;
3300 llvm::cast<AIEObjectFifoType>(getOutputObjectFifos()[0].getElemType());
3301 auto elemTypeOut = llvm::cast<MemRefType>(fifoOut.getElementType());
3302 int lenOut = elemTypeOut.getNumElements();
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);
3310 for (
size_t i = 0; i < getFifoIns().size(); i++) {
3312 int offset = srcOffset(i);
3313 if (i == getFifoIns().size() - 1)
3314 len = lenOut - offset;
3316 len = srcOffset(i + 1) - offset;
3317 lengths.push_back(len);
3323std::vector<int> ObjectFifoLinkOp::getDistributeTransferLengths() {
3324 std::vector<int> lengths;
3325 if (isDistribute()) {
3327 llvm::cast<AIEObjectFifoType>(getInputObjectFifos()[0].getElemType());
3328 auto elemTypeIn = llvm::cast<MemRefType>(fifoIn.getElementType());
3329 int lenIn = elemTypeIn.getNumElements();
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);
3337 for (
size_t i = 0; i < getFifoOuts().size(); i++) {
3338 int offset = dstOffset(i);
3340 if (i == getFifoOuts().size() - 1)
3341 len = lenIn - offset;
3343 len = dstOffset(i + 1) - offset;
3344 lengths.push_back(len);
3350std::optional<int> ObjectFifoLinkOp::getRepeatCount() {
3351 for (
auto fifoOut : getOutputObjectFifos())
3352 if (fifoOut.getRepeatCount().has_value())
3353 return {fifoOut.getRepeatCount()};
3361TileOp ObjectFifoRegisterExternalBuffersOp::getTileOp() {
3362 return cast<TileOp>(getTile().getDefiningOp());
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);
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)) {
3399Type accessElementType(Operation *target) {
3400 if (
auto fifo = dyn_cast_or_null<ObjectFifoCreateOp>(target)) {
3401 return llvm::cast<AIEObjectFifoType>(fifo.getElemType()).getElementType();
3403 if (
auto endpoint = dyn_cast_or_null<ObjectFifoCoreEndpointOp>(target)) {
3404 if (endpoint.getPoolOp()) {
3405 return endpoint.getAccessType();
3412LogicalResult verifyAccessPlacement(Operation *op, Operation *target,
3413 std::optional<ObjectFifoPort> port) {
3414 auto core = op->getParentOfType<CoreOp>();
3415 Value coreTile = core.getTile();
3417 if (
auto endpoint = dyn_cast_or_null<ObjectFifoCoreEndpointOp>(target)) {
3419 return op->emitOpError(
"port is implied by the endpoint's role");
3421 if (endpoint.getTile() != coreTile) {
3422 return core.emitOpError(
3423 "objectFifo endpoint accessed by core running on another tile");
3428 auto fifo = dyn_cast_or_null<ObjectFifoCreateOp>(target);
3430 return op->emitError(
"cannot retrieve associated object FIFO");
3433 return op->emitOpError(
"port is required when accessing an objectFifo");
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");
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");
3454LogicalResult ObjectFifoAcquireOp::verify() {
3455 auto parent = getOperation()->getParentOfType<CoreOp>();
3456 if (parent ==
nullptr) {
3457 return emitOpError(
"must be called from inside a CoreOp");
3460 Operation *target = lookupAccessTarget(*
this, getObjFifoName());
3461 if (failed(verifyAccessPlacement(*
this, target, getPort()))) {
3465 if (getObjects().empty()) {
3466 return emitOpError(
"must acquire at least one object");
3469 Type elem = accessElementType(target);
3473 auto fifo = dyn_cast<ObjectFifoCreateOp>(target);
3477 if (getPort() == ObjectFifoPort::Consume) {
3478 for (
auto [position, consumer] :
3479 llvm::enumerate(fifo.getConsumerTiles())) {
3480 if (consumer == parent.getTile()) {
3481 index = position + 1;
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);
3493 auto consType = fifo ? llvm::dyn_cast<AIEObjectFifoType>(
3494 fifo.getConsumerElemTypeOrDefault())
3496 if (fifo && !consType) {
3497 return emitOpError(
"ObjectFifo consumer element type must be an "
3498 "!aie.objectfifo<memref<...>> type");
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;
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);
3527LogicalResult ObjectFifoReleaseOp::verify() {
3528 auto parent = getOperation()->getParentOfType<CoreOp>();
3529 if (parent ==
nullptr)
3530 return emitOpError(
"must be called from inside a CoreOp");
3532 Operation *target = lookupAccessTarget(*
this, getObjFifoName());
3533 return verifyAccessPlacement(*
this, target, getPort());
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);
3552LogicalResult CascadeFlowOp::verify() {
3553 TileLike src = getSourceTileLike();
3554 TileLike dst = getDestTileLike();
3557 return emitOpError(
"source and dest must be tile-like operations");
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");
3567 bool onTarget = (*this)->getParentOfType<AIETarget>() !=
nullptr;
3568 if (onTarget && t.getCascadeSteps().empty())
3569 return emitOpError(
"cascade not supported in ")
3570 << stringifyAIEArch(t.getTargetArch());
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();
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");
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");
3592TileLike CascadeFlowOp::getSourceTileLike() {
3593 return dyn_cast_or_null<TileLike>(getSourceTile().getDefiningOp());
3596TileLike CascadeFlowOp::getDestTileLike() {
3597 return dyn_cast_or_null<TileLike>(getDestTile().getDefiningOp());
3600TileOp CascadeFlowOp::getSourceTileOp() {
3601 if (
auto tileOp = dyn_cast_or_null<TileOp>(getSourceTile().getDefiningOp()))
3603 llvm::report_fatal_error(
"Calling getSourceTileOp requires TileOp.");
3606TileOp CascadeFlowOp::getDestTileOp() {
3607 if (
auto tileOp = dyn_cast_or_null<TileOp>(getDestTile().getDefiningOp()))
3609 llvm::report_fatal_error(
"Calling getDestTileOp requires TileOp.");
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;
3626static CascadeDir oppositeCascadeDir(CascadeDir 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;
3637 llvm_unreachable(
"unhandled CascadeDir");
3640static std::string describeCascadeDirs(ArrayRef<CascadeDir> dirs) {
3642 llvm::raw_string_ostream os(s);
3644 dirs, os, [&](CascadeDir d) { os << stringifyCascadeDir(d); },
" or ");
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);
3654 return emitOpError(
"requires a placed tile (aie.tile), not a logical tile");
3657 CascadeDir inputDir = getInputDir();
3658 CascadeDir outputDir = getOutputDir();
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");
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()));
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());
3681 return emitOpError(
"cascade not supported in ")
3682 << stringifyAIEArch(t.getTargetArch());
3691LogicalResult PutCascadeOp::verify() {
3693 Type type = getCascadeValue().getType();
3694 DataLayout dataLayout = DataLayout::closest(*
this);
3695 auto bits = dataLayout.getTypeSizeInBits(type);
3697 if (bits != archbits)
3698 return emitOpError(
"type must match architecture cascade width (")
3699 << archbits <<
" bits in "
3708LogicalResult GetCascadeOp::verify() {
3710 Type type = getCascadeValue().getType();
3711 DataLayout dataLayout = DataLayout::closest(*
this);
3712 auto bits = dataLayout.getTypeSizeInBits(type);
3714 if (bits != archbits)
3715 return emitOpError(
"must be a ") << archbits <<
"-bit type";
3726LogicalResult GetStreamOp::verify() {
3727 Type type = getStreamValue().getType();
3728 auto vectorType = dyn_cast<VectorType>(type);
3731 return emitOpError(
"vector stream reads are only supported on AIE4");
3735 return emitOpError(
"AIE4 cores read streams in 512-bit or 1024-bit units; "
3736 "use a vector<16xi32> or vector<32xi32> result instead "
3739 <<
" (a 32-bit read has no AIE4 equivalent outside the load-FIFO "
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 ")
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, 10,
false);
3752LogicalResult PutStreamOp::verify() {
3753 Type type = getStreamValue().getType();
3754 auto vectorType = dyn_cast<VectorType>(type);
3757 return emitOpError(
"vector stream writes are only supported on AIE4");
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 ")
3766 if (matchPattern(getChannel(), m_ConstantInt(&channel)) && !channel.isZero())
3767 return emitOpError(
"AIE4 cores have output stream 0 only");
3780using PortKey = std::tuple<int, int, int, int>;
3787std::optional<PortKey> tryGetPortKey(Value tileValue, WireBundle bundle,
3789 auto tile = llvm::dyn_cast_or_null<TileLike>(tileValue.getDefiningOp());
3791 return std::nullopt;
3792 std::optional<int> col = tile.tryGetCol();
3793 std::optional<int> row = tile.tryGetRow();
3795 return std::nullopt;
3796 return PortKey{*col, *row,
static_cast<int>(bundle), channel};
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);
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());
3820 auto [it, inserted] = flowSeen.try_emplace({*src, *dst}, flow);
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";
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();
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)) {
3860 tryGetPortKey(dest.getTile(), dest.getBundle(), dest.getChannel());
3869 endpoints->push_back(*port);
3871 if (!comparable || sources.empty() || dests.empty())
3873 llvm::sort(sources);
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)},
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";
3895static LogicalResult verifyNoSharedProgramChannels(DeviceOp device) {
3896 std::map<std::tuple<Operation *, int, int, DMAChannelDir, int>,
3897 std::pair<DMAStartOp, Operation *>>
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())
3909 starts.try_emplace({key, col.value_or(-1), row.value_or(-1),
3910 start.getChannelDir(), start.getChannelIndex()},
3912 if (added || it->second.second == program)
3914 InFlightDiagnostic diag =
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";
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());
3937 circuitSources.try_emplace(*src, flow);
3940 auto [it, inserted] = circuitDests.try_emplace(*dst, flow);
3943 InFlightDiagnostic diag =
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";
3950 for (PacketFlowOp packetFlow : device.getOps<PacketFlowOp>()) {
3951 Region &body = packetFlow.getPorts();
3954 for (Operation &op : body.front()) {
3955 std::optional<PortKey> port;
3956 std::map<PortKey, FlowOp> *circuits =
nullptr;
3958 if (
auto source = dyn_cast<PacketSourceOp>(op)) {
3959 port = tryGetPortKey(source.getTile(), source.getBundle(),
3960 source.getChannel());
3961 circuits = &circuitSources;
3963 }
else if (
auto dest = dyn_cast<PacketDestOp>(op)) {
3965 tryGetPortKey(dest.getTile(), dest.getBundle(), dest.getChannel());
3966 circuits = &circuitDests;
3971 auto it = circuits->find(*port);
3972 if (it == circuits->end())
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";
3985LogicalResult verifyNoSharedCircuitViaEgresses(DeviceOp device) {
3986 enum class ClaimKind { FlowDest, PacketDest,
Connect, MasterSet, Via };
3990 size_t viaIndex = 0;
3992 std::map<PortKey, Claim> claimedEgresses;
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});
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});
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});
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});
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();
4042 for (
auto [index, via] : llvm::enumerate(flow.getVias())) {
4043 std::optional<PortKey> egress = tryGetPortKey(
4044 via,
static_cast<WireBundle
>(bundles[index]), channels[index]);
4048 Claim viaClaim{flow, ClaimKind::Via, index};
4049 auto [it, inserted] = claimedEgresses.try_emplace(*egress, viaClaim);
4052 if (index + 1 == flow.getVias().size() && it->second.op == flow &&
4053 it->second.kind == ClaimKind::FlowDest) {
4054 it->second = viaClaim;
4057 InFlightDiagnostic diag = flow.emitOpError()
4058 <<
"via " << index <<
" claims circuit egress "
4059 << to_string(*egress)
4060 <<
", which another operation already claims";
4061 Diagnostic ¬e = 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";
4066 case ClaimKind::PacketDest:
4067 note <<
"a packet flow ends at the same port";
4069 case ClaimKind::Connect:
4070 note <<
"a fixed connect drives the same port";
4072 case ClaimKind::MasterSet:
4073 note <<
"a fixed master set drives the same port";
4075 case ClaimKind::Via:
4076 note <<
"via " << it->second.viaIndex
4077 <<
" claims the same circuit egress";
4080 return WalkResult::interrupt();
4082 return WalkResult::advance();
4084 return failure(result.wasInterrupted());
4092LogicalResult verifyNoDuplicateNames(Operation *symbolTableOp) {
4093 if (symbolTableOp->getNumRegions() == 0 ||
4094 symbolTableOp->getRegion(0).empty()) {
4097 DenseMap<StringAttr, Operation *> nameSeen;
4098 for (Operation &op : symbolTableOp->getRegion(0).front()) {
4099 auto name = op.getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
4103 auto [it, inserted] = nameSeen.try_emplace(name, &op);
4109 if (isa<SymbolOpInterface>(op) && isa<SymbolOpInterface>(it->second)) {
4112 InFlightDiagnostic diag = op.emitError() <<
"redefinition of symbol named '"
4113 << name.getValue() <<
"'";
4114 diag.attachNote(it->second->getLoc())
4115 <<
"see existing symbol definition here";
4123LogicalResult DeviceOp::verify() {
4132 DenseMap<TileID, CoreOp> coreAtTile;
4133 for (CoreOp core : getOps<CoreOp>()) {
4135 llvm::dyn_cast_or_null<TileLike>(core.getTile().getDefiningOp());
4138 std::optional<int> col = tile.tryGetCol();
4139 std::optional<int> row = tile.tryGetRow();
4143 auto [it, inserted] = coreAtTile.try_emplace(
id, core);
4145 InFlightDiagnostic diag =
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";
4156 if (failed(verifyNoDuplicateFlows(*
this)))
4158 if (failed(verifyNoDuplicatePacketFlows(*
this)))
4160 if (failed(verifyNoSharedCircuitPorts(*
this)))
4162 if (failed(verifyNoSharedProgramChannels(*
this)))
4164 if (failed(verifyNoSharedCircuitViaEgresses(*
this))) {
4168 if (failed(verifyNoDuplicateNames(*
this))) {
4175LogicalResult DeviceOp::verifyRegions() {
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();
4189 return failure(result.wasInterrupted());
4196xilinx::AIE::DeviceOp DeviceOp::getForSymbolInModule(mlir::ModuleOp module,
4197 llvm::StringRef symbol) {
4199 if (symbol.empty()) {
4203 Operation *maybeDeviceOp = mlir::SymbolTable::lookupSymbolIn(module, symbol);
4204 if (!maybeDeviceOp) {
4207 deviceOp = llvm::dyn_cast<DeviceOp>(maybeDeviceOp);
4211xilinx::AIE::DeviceOp
4212DeviceOp::getForSymbolInModuleOrError(mlir::ModuleOp module,
4213 llvm::StringRef symbol) {
4214 DeviceOp deviceOp = getForSymbolInModule(module, symbol);
4216 if (!symbol.empty()) {
4217 module.emitError("No such device: ") << symbol;
4219 module.emitError("No 'main' device in module");
4229TileOp TileElement::tryGetTileOp() {
4230 auto element = cast<TileElement>(this->getOperation());
4231 return dyn_cast_or_null<TileOp>(element.getTile().getDefiningOp());
4234TileOp TileElement::getTileOp() {
4235 if (
auto tileOp = tryGetTileOp())
4237 llvm::report_fatal_error(
"Calling getTileOp requires TileOp.");
4244LogicalResult LogicalTileOp::verify() {
4246 *
this, (*this)->getAttrOfType<PacketInfoAttr>(
"controller_id"),
4250 int columns = targetModel.
columns();
4251 int rows = targetModel.
rows();
4254 if (
auto col = getCol()) {
4255 if (*col >= columns)
4256 return emitOpError(
"column index (")
4258 <<
") must be less than the number of columns in the device ("
4261 if (
auto row = getRow()) {
4263 return emitOpError(
"row index (")
4264 << *row <<
") must be less than the number of rows in the 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;
4277 if (!tileTypeExists) {
4278 return emitOpError(
"tile type '")
4279 << stringifyAIETileType(tileType)
4280 <<
"' does not exist on the target device";
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 <<
")";
4298TileID LogicalTileOp::getCanonicalTileID() {
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};
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) {
4316 llvm_unreachable(
"No tile of matching tile type found in AIE device");
4319size_t LogicalTileOp::getNumSourceConnections(WireBundle bundle) {
4321 TileID tile = getCanonicalTileID();
4323 if (bundle == WireBundle::Core || bundle == WireBundle::DMA) {
4325 if (targetModel.
hasShimMux(tile.col, tile.row))
4334size_t LogicalTileOp::getNumDestConnections(WireBundle bundle) {
4336 TileID tile = getCanonicalTileID();
4338 if (bundle == WireBundle::Core || bundle == WireBundle::DMA) {
4340 if (targetModel.
hasShimMux(tile.col, tile.row))
4349std::optional<int> LogicalTileOp::tryGetCol() {
4350 if (
auto col = getCol())
4352 return std::nullopt;
4355std::optional<int> LogicalTileOp::tryGetRow() {
4356 if (
auto row = getRow())
4358 return std::nullopt;
4365ParseResult LogicalTileOp::parse(OpAsmParser &parser, OperationState &result) {
4366 AIETileType tileType;
4367 if (parser.parseLess())
4370 StringRef tileTypeStr;
4371 if (parser.parseKeyword(&tileTypeStr))
4374 auto tileTypeOpt = symbolizeAIETileType(tileTypeStr);
4376 return parser.emitError(parser.getCurrentLocation(),
4377 "unknown logical tile type: ")
4379 tileType = *tileTypeOpt;
4381 if (parser.parseGreater())
4384 if (parser.parseLParen())
4387 std::optional<int32_t> col;
4388 if (succeeded(parser.parseOptionalQuestion())) {
4392 if (parser.parseInteger(colVal))
4397 if (parser.parseComma())
4400 std::optional<int32_t> row;
4401 if (succeeded(parser.parseOptionalQuestion())) {
4405 if (parser.parseInteger(rowVal))
4410 if (parser.parseRParen())
4414 if (parser.parseOptionalAttrDict(result.attributes))
4418 result.getOrAddProperties<LogicalTileOp::Properties>().tile_type =
4419 AIETileTypeAttr::get(parser.getContext(), tileType);
4421 result.getOrAddProperties<LogicalTileOp::Properties>().col =
4422 parser.getBuilder().getI32IntegerAttr(*col);
4424 result.getOrAddProperties<LogicalTileOp::Properties>().row =
4425 parser.getBuilder().getI32IntegerAttr(*row);
4428 result.addTypes(parser.getBuilder().getIndexType());
4433void LogicalTileOp::print(OpAsmPrinter &printer) {
4434 printer <<
"<" << stringifyAIETileType(getTileType()) <<
">";
4437 if (
auto col = getCol())
4442 if (
auto row = getRow())
4448 SmallVector<StringRef, 3> elidedAttrs = {
"tile_type",
"col",
"row"};
4449 printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
4456LogicalResult TileOp::verify() {
4458 *
this, (*this)->getAttrOfType<PacketInfoAttr>(
"controller_id"),
4462 int columns = targetModel.
columns();
4463 int rows = targetModel.
rows();
4464 if (colIndex() >= columns)
4465 return emitOpError(
"column index (")
4467 <<
") must be less than the number of columns in the device ("
4469 if (rowIndex() >= rows)
4470 return emitOpError(
"row index (")
4472 <<
") must be less than the number of rows in the device (" << rows
4475 auto users = getResult().getUsers();
4477 for (
auto *user : users) {
4478 if (llvm::isa<SwitchboxOp>(*user)) {
4480 return emitOpError(
"can only have one switchbox");
4488size_t TileOp::getNumSourceConnections(WireBundle bundle) {
4490 if (bundle == WireBundle::Core || bundle == WireBundle::DMA)
4494 if (targetModel.
hasShimMux(getCol(), getRow()))
4503size_t TileOp::getNumDestConnections(WireBundle bundle) {
4505 if (bundle == WireBundle::Core || bundle == WireBundle::DMA)
4509 if (targetModel.
hasShimMux(getCol(), getRow()))
4518std::optional<int> TileOp::tryGetCol() {
return getCol(); }
4519std::optional<int> TileOp::tryGetRow() {
return getRow(); }
4521AIETileType TileOp::getTileType() {
4523 return targetModel.
getTileType(getCol(), getRow());
4526static bool isLegalTileConnection(TileOp tile,
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;
4534 tile.colIndex(), tile.rowIndex(), srcBundle, srcChan, dstBundle, dstChan);
4537static bool isLegalTileConnection(TileOp tile,
4539 ConnectOp connectOp) {
4540 auto srcBundle = connectOp.getSourceBundle();
4541 auto srcChan = connectOp.getSourceChannel();
4542 auto dstBundle = connectOp.getDestBundle();
4543 auto dstChan = connectOp.getDestChannel();
4545 tile.colIndex(), tile.rowIndex(), srcBundle, srcChan, dstBundle, dstChan);
4548TileOp TileOp::getOrCreate(mlir::OpBuilder builder, DeviceOp device,
int col,
4549 int row, std::optional<mlir::Location> loc) {
4550 TileOp tile =
nullptr;
4552 for (
auto t : device.getOps<AIE::TileOp>()) {
4553 if (t.getRow() == row && t.getCol() == col) {
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);
4573LogicalResult ShimMuxOp::verify() {
4578 if (!isa<TileOp>(getTile().getDefiningOp()))
4581 TileOp tile = getTileOp();
4583 return emitOpError(
"tile (")
4584 << tile.getCol() <<
", " << tile.getRow()
4585 <<
") has no shim mux: its DMA connects to the switchbox "
4588 Region &body = getConnections();
4589 DenseSet<Port> destset;
4591 return emitOpError(
"should have non-empty body");
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)) {
4604 return ops.emitOpError(
"cannot be contained in a Switchbox op");
4610size_t ShimMuxOp::getNumSourceConnections(WireBundle bundle) {
4611 auto tile = getTileOp();
4614 tile.getRow(), bundle);
4617size_t ShimMuxOp::getNumDestConnections(WireBundle bundle) {
4618 auto tile = getTileOp();
4628LogicalResult ShimDMAOp::verify() {
4635TileOp ShimDMAOp::getTileOp() {
4636 return cast<TileElement>(this->getOperation()).getTileOp();
4639LogicalResult PacketRulesOp::verify() {
4640 if (Region &body = getRules(); body.empty())
4641 return emitOpError(
"should have non-empty body");
4645LogicalResult MasterSetOp::verify() {
4647 for (
auto val : getAmsels()) {
4648 auto amsel = dyn_cast_if_present<AMSelOp>(val.getDefiningOp());
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();
4658bool MasterSetOp::keepsPktHeader() {
4660 (*this)->getParentOfType<SwitchboxOp>().getTileOp().getTileID(),
4661 destPort(), getKeepPktHeader());
4665 std::optional<bool> keep) {
4668 return master.bundle != WireBundle::DMA &&
4669 (tile.row != 0 || master.bundle != WireBundle::South);
4675static LogicalResult verifyFlowEndpoint(Operation *op, Value tile,
Port port,
4677 if (!isa_and_nonnull<TileLike>(tile.getDefiningOp()))
4678 return op->emitOpError(
4679 "tile operand is not an aie.tile or aie.logical_tile");
4681 port.bundle == WireBundle::NOC || port.bundle == WireBundle::PLIO;
4682 if (port.bundle != WireBundle::Core && port.bundle != WireBundle::DMA &&
4685 auto tileOp = dyn_cast_or_null<TileOp>(tile.getDefiningOp());
4691 int col = tileOp.getCol(), row = tileOp.getRow();
4701 channels = isSource ? tileOp.getNumDestConnections(port.bundle)
4702 : tileOp.getNumSourceConnections(port.bundle);
4704 if (
static_cast<size_t>(port.channel) < channels)
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";
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,
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;
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";
4743 auto verifyBundles = [&](DenseI32ArrayAttr bundles,
4744 StringRef direction) -> LogicalResult {
4745 for (
auto [index, bundle] : llvm::enumerate(bundles.asArrayRef())) {
4747 bundle >
static_cast<int32_t
>(getMaxEnumValForWireBundle())) {
4748 return op->emitOpError(
"has invalid via ")
4749 << direction <<
" bundle " << bundle <<
" at index " << index;
4754 auto verifyChannels = [&](DenseI32ArrayAttr channels,
4755 StringRef direction) -> LogicalResult {
4756 for (
auto [index, channel] : llvm::enumerate(channels.asArrayRef())) {
4758 return op->emitOpError(
"has negative via ")
4759 << direction <<
" channel " << channel <<
" at index " << index;
4764 if (failed(verifyBundles(ingressBundles,
"ingress")) ||
4765 failed(verifyChannels(ingressChannels,
"ingress")) ||
4766 failed(verifyBundles(egressBundles,
"egress")) ||
4767 failed(verifyChannels(egressChannels,
"egress"))) {
4773LogicalResult FlowOp::verify() {
4774 if (failed(verifyFlowEndpoint(*
this, getSource(),
4775 {getSourceBundle(), sourceIndex()},
true)))
4777 if (failed(verifyFlowEndpoint(*
this, getDest(),
4778 {getDestBundle(), destIndex()},
false))) {
4782 return verifyFlowVias(*
this, getVias(), getViaIngressBundlesAttr(),
4783 getViaIngressChannelsAttr(), getViaEgressBundlesAttr(),
4784 getViaEgressChannelsAttr());
4787LogicalResult PacketSourceOp::verify() {
4788 return verifyFlowEndpoint(*
this, getTile(), port(),
true);
4791LogicalResult PacketDestOp::verify() {
4792 return verifyFlowEndpoint(*
this, getTile(), port(),
false);
4795LogicalResult PacketFlowOp::verify() {
4796 Region &body = getPorts();
4798 return emitOpError(
"should have non-empty body");
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))
4806 if (isa<PacketDestOp>(ops))
4811 return emitOpError(
"must have at least one aie.packet_source");
4813 return emitOpError(
"must have at least one aie.packet_dest");
4814 if (!getVias().empty() && numSources != 1) {
4816 "with via waypoints must have exactly one aie.packet_source");
4818 if (!getVias().empty() && numDests != 1) {
4820 "with via waypoints must have exactly one aie.packet_dest");
4823 uint8_t
id = getID();
4824 if (uint32_t maxId =
getTargetModel(getOperation()).getMaxPacketId();
4826 return emitOpError(
"packet id ")
4827 <<
static_cast<int>(id) <<
" exceeds the maximum of " << maxId;
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";
4839 return verifyFlowVias(*
this, getVias(), getViaIngressBundlesAttr(),
4840 getViaIngressChannelsAttr(), getViaEgressBundlesAttr(),
4841 getViaEgressChannelsAttr());
4849static uint32_t channelsOfOwnTile(TileOp tile, DMAChannelDir direction,
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>();
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;
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 <<
"]";
4877LogicalResult DmaPollForQueueSpaceOp::verify() {
4878 auto core = (*this)->getParentOfType<CoreOp>();
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;
4888 if (targetModel.getDmaTaskQueueDepth() == 0)
4889 return emitOpError(
"waits on a task queue, which this device has none of");
4893LogicalResult CoreOp::verify() {
4894 if (getBody().empty())
4895 return emitOpError(
"should have non-empty body");
4902 "When `elf_file` attribute is specified, core body must be empty "
4903 "(consist of exactly one `aie.end` op).");
4906 if (getLinkWith() && getLinkFiles())
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())
4912 "cannot specify both 'link_with' (deprecated) and 'link_merge_files' "
4913 "on the same core; run aie-assign-core-link-files to migrate");
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 '")
4925 <<
"' appears in both 'link_files' and 'link_merge_files'; an "
4926 "artifact must be either merged or linked, not both";
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";
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())
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
4951 if (acquire.getAction() == LockAction::AcquireGreaterEqual &&
4954 "lock_acquires uses AcquireGreaterEqual on a target without "
4958 int64_t localMem = targetModel.getLocalMemorySize();
4959 auto validAlignment = [localMem](int64_t alignment) {
4960 return alignment > 0 && alignment <= localMem &&
4961 llvm::isPowerOf2_64(alignment);
4963 if (
auto alignment = getMeasuredDataAlignment();
4964 alignment && !validAlignment(*alignment))
4965 return emitOpError(
"measured_data_alignment must be a power of two between "
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";
4974 auto tile = dyn_cast_if_present<TileOp>(getTile().getDefiningOp());
4976 tile ? targetModel.getNumBanks(tile.getCol(), tile.getRow()) : 0;
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
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 "
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 "
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) <<
")";
5007 if (stackRun.
size >= localMem)
5008 return emitOpError(getStackSize() ?
"stack_size "
5009 :
"measured stack requirement ")
5011 <<
" leaves no local memory for this tile's buffers (" << localMem
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";
5026bool CoreOp::isEmpty() {
5027 Region &body = getBody();
5029 return (body.hasOneBlock() && body.front().getOperations().size() == 1 &&
5030 llvm::isa<AIE::EndOp>(body.front().front()));
5033TileOp CoreOp::getTileOp() {
5034 return cast<TileElement>(this->getOperation()).getTileOp();
5037uint32_t CoreOp::getEffectiveStackSize() {
5038 if (
auto declared = getStackSize())
5041 uint32_t fallback = targetModel.getDefaultCoreStackSize();
5042 if (
auto measured = getMeasuredStackSize())
5043 return std::max<uint32_t>(
5045 llvm::alignTo(*measured, targetModel.getCoreStackAlignment()));
5050 return {getStackAddress().value_or(0), getEffectiveStackSize()};
5053int64_t CoreOp::getSectionAlignment(std::optional<int32_t> 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);
5063SmallVector<BufferOp> CoreOp::getSectionReservationBuffers(
5064 ArrayRef<CoreSectionReservation> reservations) {
5066 SmallVector<BufferOp> onTile;
5067 (*this)->getParentOp()->walk([&](BufferOp buffer) {
5068 if (buffer.getTile() == getTile())
5069 onTile.push_back(buffer);
5071 SmallVector<BufferOp> holders;
5072 DenseSet<Operation *> claimed;
5074 auto holds = [&](BufferOp buffer) {
5075 if (claimed.contains(buffer) || buffer.getAllocationSize() != held.bytes)
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);
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);
5092SmallVector<CoreSectionReservation> CoreOp::getSectionReservations() {
5094 SmallVector<CoreSectionReservation> held;
5097 int64_t data = getDataSize().value_or(getMeasuredDataSize().value_or(0));
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);
5105 held.push_back({Kind::Bank, size, bank, getSectionAlignment(bank)});
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]});
5118int64_t BufferOp::getSectionAlignment() {
5119 if (!getCoreData() && !getBankReserved())
5121 for (Operation *user : getTile().getUsers())
5122 if (
auto core = dyn_cast<CoreOp>(user)) {
5124 return core.getSectionAlignment(std::nullopt);
5125 std::optional<int32_t> bank = getMemBank();
5126 return bank ? core.getSectionAlignment(bank) : 1;
5131int64_t BufferOp::getAllocationSize() {
5133 DataLayout::closest(getOperation()));
5136LogicalResult BufferOp::verify() {
5137 if (UsesAreAccessible::verifyTrait(*this).failed()) {
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;
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())
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();
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");
5172 if (std::optional<int32_t> memBank = getMemBank()) {
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";
5182 dyn_cast_if_present<TileLike>(getTile().getDefiningOp());
5183 tileLike && (tileLike.isCoreTile() || tileLike.isMemTile())) {
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()) {
5196 static_cast<int32_t
>(targetModel.
getNumBanks(*col, *row))))
5197 return emitOpError(
"mem_bank attribute value is out of range");
5203 auto tile = dyn_cast_if_present<TileOp>(getTile().getDefiningOp());
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";
5224 std::optional<int32_t> address = getAddress();
5225 std::optional<int32_t> memBank = getMemBank();
5226 if (address && memBank && getAllocationSize() > 0) {
5228 int64_t numBanks = targetModel.
getNumBanks(tile.getCol(), tile.getRow());
5229 int64_t memSize = tile.isMemTile() ? targetModel.
getMemTileSize()
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;
5249 auto memref = dyn_cast<MemRefType>(type);
5253 auto space = dyn_cast_or_null<IntegerAttr>(
memref.getMemorySpace());
5257 int64_t value = space.getInt();
5258 if (value >= 5 && value <= 8) {
5259 return {
static_cast<int>(value - 5)};
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");
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");
5294 DenseMap<TileID, Operation *> &tiles) {
5295 for (
auto tile : device.getOps<TileOp>()) {
5296 tiles[tile.getTileID()] = tile;
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);
5309static void printBufferInitialValue(OpAsmPrinter &p, BufferOp op, Type type,
5310 Attribute initialValue) {
5311 if (op.getInitialValue()) {
5313 p.printAttributeWithoutType(initialValue);
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;
5324 if (parser.parseOptionalEqual())
5327 Type tensorType = mlir::memref::getTensorTypeFromMemRefType(memrefType);
5328 if (parser.parseAttribute(initialValue, tensorType))
5330 if (!llvm::isa<ElementsAttr>(initialValue))
5331 return parser.emitError(parser.getNameLoc())
5332 <<
"initial value should be an elements attribute";
5336TileOp BufferOp::getTileOp() {
5337 return cast<TileElement>(this->getOperation()).getTileOp();
5344LogicalResult MemOp::verify() {
5345 Region &body = getBody();
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";
5359TileOp MemOp::getTileOp() {
5360 return cast<TileElement>(this->getOperation()).getTileOp();
5367LogicalResult MemTileDMAOp::verify() {
5368 assert(getOperation()->getNumRegions() == 1 &&
5369 "MemTileDMAOp has zero region!");
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";
5381 if (
auto startOp = dyn_cast<DMAStartOp>(bodyOp)) {
5384 if (!startOp.getEndpoint() && startOp.getChannelIndex() > 3) {
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();
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);
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))
5415 if (
auto bufferOp = dyn_cast<BufferOp>(bufferDef);
5416 !bufferOp || bufferOp.getTile() != getTile()) {
5417 InFlightDiagnostic err =
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";
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";
5448TileOp MemTileDMAOp::getTileOp() {
5449 return cast<TileElement>(this->getOperation()).getTileOp();
5456static bool isBdPacketEnabled(DMABDOp bd) {
5457 if (bd.getPacket().has_value())
5459 if (Block *blk = bd->getBlock())
5460 return !blk->getOps<DMABDPACKETOp>().empty();
5465static LogicalResult verifyDMAChannelInRange(Operation *op, DMAChannelDir dir,
5468 if (channel >= 0 && channel < channels)
5470 return op->emitOpError() << stringifyDMAChannelDir(dir) <<
" channel "
5471 << channel <<
" is out of range: the tile has "
5472 << channels <<
" " << stringifyDMAChannelDir(dir)
5481 int64_t channels = dir == DMAChannelDir::MM2S
5482 ? tile.getNumDestConnections(WireBundle::DMA)
5483 : tile.getNumSourceConnections(WireBundle::DMA);
5484 return verifyDMAChannelInRange(op, dir, channel, channels);
5489static LogicalResult emitShimPLTileHasNoDMA(Operation *op,
5490 std::optional<int> col,
5491 std::optional<int> 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");
5501 if (tile.isShimPLTile())
5502 return emitShimPLTileHasNoDMA(op, tile.tryGetCol(), tile.tryGetRow());
5508 int col,
int row, DMAChannelDir dir,
5511 return emitShimPLTileHasNoDMA(op, col, row);
5515 return verifyDMAChannelInRange(op, dir, channel,
5520 PacketInfoAttr packet,
5522 if (packet && !packet.isAssigned())
5523 return op->emitOpError()
5525 <<
" has no pkt_id; allocation assigns one, so a header at "
5526 "this level must carry it";
5532 std::optional<int32_t> oooId = bd.getOutOfOrderId();
5533 if (!oooId.has_value())
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");
5541 if (*oooId < 0 ||
static_cast<uint32_t
>(*oooId) > maxOooId)
5542 return bd.emitOpError(
"out_of_order_id must be in [0, ") << maxOooId <<
"]";
5552 AIETileType tileType) {
5553 std::optional<BDIterationAttr> iter = bd.getIteration();
5558 return bd.emitOpError(
"BD iteration is not supported on this target");
5559 uint32_t size = iter->getSize(), current = iter->getCurrent();
5561 if (size < 1 || size > maxSize)
5562 return bd.emitOpError(
"BD iteration size must be in [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;
5573 if (stepInWords < 1 || stepInWords > maxStep)
5574 return bd.emitOpError() <<
"BD iteration stride must be in [1, "
5575 << maxStep <<
"] 32-bit words";
5577 if (current >= size)
5578 return bd.emitOpError(
"BD iteration current must be in [0, size)");
5582static LogicalResult verifyDMARepeatCount(Operation *op, int32_t repeatCount) {
5584 if (maxRepeat == 0) {
5585 if (repeatCount != 0)
5586 return op->emitOpError(
"repeat_count is not supported on this target");
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";
5597 Operation *op,
const AIETargetModel &targetModel,
int col,
int row,
5598 DMAChannelDir dir, int64_t channel) {
5602 if (channel >= 0 && channel < channels)
5604 return op->emitOpError() << stringifyDMAChannelDir(dir) <<
" channel "
5605 << channel <<
" is out of range: the tile has "
5606 << channels <<
" " << stringifyDMAChannelDir(dir)
5614 std::optional<int> col = tile.tryGetCol();
5615 std::optional<int> row = tile.tryGetRow();
5624 bool outOfOrder, ArrayRef<DMABDOp> bds,
5625 bool packetEnabledByContext) {
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");
5634 return op->emitOpError(
"out-of-order S2MM channel must have at least one "
5635 "receive buffer descriptor");
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");
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; "
5667 UseLockOp &release) {
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)");
5676 diag <<
", or a use_lock(release) alone when out-of-order";
5679 for (UseLockOp op : block.getOps<UseLockOp>()) {
5680 UseLockOp &slot = op.release() ? release : acquire;
5685 if (!acquire && !release)
5687 if (release && (acquire || outOfOrder))
5689 return reject(acquire ? acquire : release);
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);
5701 getOperation(), cast<TileLike>(program.getTile().getDefiningOp()),
5702 getChannelDir(), getChannelIndex())))
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");
5712 llvm::to_vector_of<UseLockOp>(bdRegion.front().getOps<UseLockOp>());
5713 if (useLocks.size() != 2)
5715 "DMAOp regions/blocks must have exactly two UseLock ops");
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");
5726 if (
auto program = dyn_cast<TileElement>(parentOp))
5728 getOperation(), program.getTileLike(), getChannelDir(),
5729 getChannelIndex())))
5731 if (failed(verifyDMARepeatCount(getOperation(), getRepeatCount())))
5733 SmallVector<DMABDOp> bds;
5734 for (
auto &bdRegion : getBds())
5735 llvm::append_range(bds, bdRegion.front().getOps<DMABDOp>());
5737 getOutOfOrder(), bds);
5744BufferOp DMABDOp::getBufferOp() {
5745 return cast<BufferOp>(getBuffer().getDefiningOp());
5750static ParseResult parseOptionalOperandType(OpAsmParser &parser, Type &type,
5753 if (succeeded(parser.parseOptionalColon()))
5754 return parser.parseType(type);
5758static void printOptionallyTypedOperand(OpAsmPrinter &printer, Value operand,
5761 if (operand.getType() != defaultType)
5762 printer <<
" : " << operand.getType();
5771parseDynamicScalar(OpAsmParser &parser,
5772 std::optional<OpAsmParser::UnresolvedOperand> &operand,
5773 IntegerAttr &staticAttr, Type &type) {
5775 OptionalParseResult intResult = parser.parseOptionalInteger(intValue);
5776 if (intResult.has_value()) {
5777 if (failed(*intResult))
5780 parser.getBuilder().getI32IntegerAttr(
static_cast<int32_t
>(intValue));
5783 OpAsmParser::UnresolvedOperand op;
5784 if (parser.parseOperand(op) ||
5785 parseOptionalOperandType(parser, type, parser.getBuilder().getI32Type()))
5791static void printDynamicScalar(OpAsmPrinter &printer, Operation *,
5792 Value operand, IntegerAttr staticAttr, Type) {
5794 printOptionallyTypedOperand(printer, operand,
5795 IntegerType::get(operand.getContext(), 32));
5797 printer << staticAttr.getInt();
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());
5811 if (failed(*isOperand) ||
5812 parseOptionalOperandType(parser, type,
5813 parser.getBuilder().getI64Type()))
5815 values.push_back(operand);
5816 types.push_back(type);
5817 ints.push_back(ShapedType::kDynamic);
5820 if (parser.parseCommaSeparatedList(AsmParser::Delimiter::Square, parseEntry))
5822 integers = parser.getBuilder().getDenseI64ArrayAttr(ints);
5827 OperandRange values,
5828 ArrayRef<int64_t> integers,
5831 auto value = values.begin();
5832 llvm::interleaveComma(integers, printer, [&](int64_t i) {
5833 if (!ShapedType::isDynamic(i)) {
5838 printOptionallyTypedOperand(printer, v,
5839 IntegerType::get(v.getContext(), 64));
5846static void splitScalarOfr(mlir::OpBuilder &builder, mlir::OpFoldResult ofr,
5847 mlir::Value &operand, mlir::IntegerAttr &attr) {
5852 if (
auto v = llvm::dyn_cast_if_present<mlir::Value>(ofr)) {
5857 llvm::cast<mlir::IntegerAttr>(llvm::cast<mlir::Attribute>(ofr));
5858 attr = builder.getI32IntegerAttr(
static_cast<int32_t
>(intAttr.getInt()));
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) {
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);
5876 DenseI64ArrayAttr staticSizesAttr =
5877 staticSizes.empty() ? DenseI64ArrayAttr{}
5878 : builder.getDenseI64ArrayAttr(staticSizes);
5879 DenseI64ArrayAttr staticStridesAttr =
5880 staticStrides.empty() ? DenseI64ArrayAttr{}
5881 : builder.getDenseI64ArrayAttr(staticStrides);
5885 mlir::Value offsetVal, lenVal;
5886 mlir::IntegerAttr offsetAttr, lenAttr;
5887 splitScalarOfr(builder, offset, offsetVal, offsetAttr);
5888 splitScalarOfr(builder, len, lenVal, lenAttr);
5890 build(builder, state, buffer, offsetVal, lenVal,
5891 offsetAttr, lenAttr,
5892 dynSizes, dynStrides,
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) {
5923 mlir::OpFoldResult offsetOfr = builder.getI32IntegerAttr(offset);
5924 mlir::OpFoldResult lenOfr = builder.getI32IntegerAttr(len);
5928 llvm::SmallVector<mlir::OpFoldResult> sizes, strides;
5930 for (BDDimLayoutAttr d : dims) {
5931 sizes.push_back(builder.getI64IntegerAttr(d.getSize()));
5932 strides.push_back(builder.getI64IntegerAttr(d.getStride()));
5935 buildMixed(builder, state, buffer, offsetOfr, lenOfr, sizes, strides, padDims,
5939llvm::SmallVector<mlir::OpFoldResult> DMABDOp::getMixedSizes() {
5940 return ::mlir::getMixedValues(
5941 getStaticSizes().value_or(llvm::ArrayRef<int64_t>{}), getSizes(),
5945llvm::SmallVector<mlir::OpFoldResult> DMABDOp::getMixedStrides() {
5946 return ::mlir::getMixedValues(
5947 getStaticStrides().value_or(llvm::ArrayRef<int64_t>{}), getStrides(),
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())))
5959 if (failed(mlir::verifyListOfOperandsOrIntegers(
5960 *
this,
"strides", staticStrides.size(), staticStrides, getStrides())))
5962 if (staticSizes.size() != staticStrides.size())
5963 return emitOpError(
"expected the same number of sizes (")
5964 << staticSizes.size() <<
") and strides (" << staticStrides.size()
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;
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++])
5989 std::optional<int64_t> tc =
5990 ShapedType::isDynamic(t)
5991 ? mlir::getConstantIntValue(dynStrides[nextStride++])
5994 emitError() <<
"buffer descriptor size/stride is a runtime value; a "
5995 "compile-time constant is required on this path";
5996 return std::nullopt;
5998 dims.push_back(BDDimLayoutAttr::get(
5999 getContext(),
static_cast<uint32_t
>(*sc),
static_cast<uint32_t
>(*tc)));
6004std::optional<llvm::SmallVector<BDDimLayoutAttr>>
6005DMABDOp::getConstantDimensions() {
6006 return getFoldedDimensions([&]() {
return emitOpError(); });
6012LogicalResult DMABDOp::verifyTransferInBounds() {
6013 auto buffer = llvm::dyn_cast<MemRefType>(getBuffer().getType());
6014 if (!buffer || !buffer.hasStaticShape() ||
6015 llvm::isa<BlockArgument>(getBuffer()))
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)
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)
6032 InFlightDiagnostic err = emitOpError(
"transfer of ")
6033 << *len <<
" elements at offset " << *offset
6034 <<
" runs past the end of the " << numElements
6035 <<
"-element buffer";
6037 err.attachNote() <<
"an omitted `len` is the whole buffer; give the "
6038 "length to transfer from this offset";
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);
6047 maxIdx += *t * (*s - 1);
6049 if (maxIdx < numElements)
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
6061 llvm::ArrayRef<BDPadLayoutAttr> pads,
6063 if (dims.empty() || pads.empty())
6066 for (
auto [dim, pad] : llvm::zip(dims, pads))
6067 size *= dim.getSize() + pad.getConstPadBefore() + pad.getConstPadAfter();
6075 if (dims.back().getStride() != 1)
6079 uint64_t product = 1;
6080 for (
int i =
static_cast<int>(dims.size()) - 1; i >= 1; --i) {
6081 product *= dims[i].getSize();
6083 if (dims[i - 1].getSize() > 1 && dims[i - 1].getStride() != product)
6089std::optional<SmallVector<BDDimLayoutAttr>>
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);
6098 if (kept.size() == dims.size() || len != product)
6099 return std::nullopt;
6101 return SmallVector<BDDimLayoutAttr>{};
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 "
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 (")
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";
6129 Operation *op, std::optional<int64_t> lengthUnit, BaseMemRefType buffer,
6130 std::optional<int64_t> lenElems,
bool contiguous,
6131 llvm::ArrayRef<int64_t> innerSizes) {
6133 return op->emitOpError(
"length_parameter requires length_unit");
6136 int64_t elemBytes = buffer.getElementTypeBitWidth() / 8;
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";
6145 llvm::SmallVector<int64_t, 3> sizes(innerSizes);
6146 llvm::SmallVector<int64_t, 3> strides(3, 0);
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 "
6162 llvm::MutableArrayRef<int64_t> sizes,
6163 llvm::MutableArrayRef<int64_t> strides) {
6164 if (sizes[2] > 1 || sizes[1] <= 1)
6166 sizes[2] = sizes[1];
6167 strides[2] = strides[1];
6173 Operation *op,
const AIETargetModel &targetModel,
int col,
int row) {
6175 if (arch != AIEArch::AIE2 && arch != AIEArch::AIE2p)
6176 return op->emitOpError(
"length_parameter is only supported on AIE2 and "
6179 return op->emitOpError(
"length_parameter is only supported on shim NOC "
6180 "tiles, got tile (")
6181 << col <<
", " << row <<
")";
6185 return op->emitOpError(
"length_parameter requires a BD whose buffer "
6186 "length fills a 32-bit register");
6191 llvm::SmallVector<uint32_t> ids;
6192 program.getDmaBody().walk([&](DMABDOp bd) {
6193 if (
auto id = bd.getBdId())
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");
6207 if (getLengthParameterAttr() || getLengthStateTableIdxAttr()) {
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: ");
6221 if (dims->size() > 4)
6222 return emitOpError(
"length_parameter requires at most 4 dimensions, got ")
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())
6236 else if (!hasLen() && buffer.hasStaticShape())
6237 lenElems = buffer.getNumElements();
6247 Operation *p = (*this)->getParentOp();
6248 if (!llvm::isa<MemOp, MemTileDMAOp, ShimDMAOp, DMAOp>(*p)) {
6253 bool isUnrankedMemRef = llvm::isa<UnrankedMemRefType>(getBuffer().getType());
6257 if (!isUnrankedMemRef) {
6258 if (!isa_and_nonnull<BufferOp, ExternalBufferOp>(
6259 getBuffer().getDefiningOp()))
6261 "BDs only support BufferOp or ExternalBufferOp operands.");
6264 if (getLenInBytes() % 4)
6265 return emitOpError(
"transfer length must be multiple of 4 (i.e., represent "
6266 "4 byte aligned address)");
6268 TileElement parentTileElement = getParentTileElement(getOperation());
6269 TileLike parentTile = parentTileElement.getTileLike();
6271 return emitOpError(
"parent tile must implement TileLike interface");
6273 if (!isUnrankedMemRef && getOperation()->getParentOfType<MemOp>() &&
6274 (!isa<BufferOp>(getBuffer().getDefiningOp()) ||
6275 getBufferOp().getTile() != parentTileElement.getTile()))
6277 "Core tile DMAs can only access a buffer in the same tile.");
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;
6289 if (getBdIdVal() && getBdId().has_value())
6290 return emitOpError(
"bd_id and bd_id_val are mutually exclusive");
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();
6309 if (lenStaticallyKnown) {
6310 if (
auto constLen = getConstantLen();
6311 constLen.has_value() && *constLen <= 0) {
6314 uint64_t lenInBytes = getLenInBytes();
6316 if (granularity != 0) {
6317 uint64_t lenInWords = lenInBytes * 8 / granularity;
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";
6330 if (failed(verifyMixedSizesAndStrides()) || failed(verifyTransferInBounds()))
6335 std::optional<llvm::SmallVector<BDDimLayoutAttr>> dims;
6336 if (!getMixedSizes().empty()) {
6337 dims = getConstantDimensions();
6338 if (!dims.has_value())
6341 if (dims.has_value()) {
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 "
6351 << std::to_string(dims->size()) <<
" dimensions).";
6353 auto buffer = llvm::dyn_cast<MemRefType>(getBuffer().getType());
6355 return emitOpError() <<
"dimensions attribute cannot be used with "
6356 "unranked memref buffer type.";
6367 bool skipSizeCheck =
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 =
6385 ? (1ULL << stepBits) - 1 +
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 <<
".";
6406 if (getBufferElementTypeWidthInBytes() < 4 && dims->back().getStride() != 1)
6408 "For <32b width datatypes, inner-most dim stride must be 1");
6410 if (getBufferElementTypeWidthInBytes() > 4 && dims->back().getStride() != 1)
6412 "For >32b width datatypes, inner-most dim stride must be 1");
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.");
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)
6453 if (i == *effectiveInnermost) {
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).";
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).";
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).";
6487 llvm::SmallVector<std::pair<DmaBdField, DmaBdField>, 3> 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";
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() +
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.";
6516 if ((paddims->back().getConstPadBefore() *
6517 getBufferElementTypeWidthInBytes()) %
6519 return emitOpError() <<
"Inner-most padding-before count must result in"
6520 <<
" padding in 32-bit words.";
6521 if ((paddims->back().getConstPadAfter() *
6522 getBufferElementTypeWidthInBytes()) %
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))) {
6529 int64_t before = pad.getConstPadBefore();
6530 int64_t after = pad.getConstPadAfter();
6532 before = before * getBufferElementTypeWidthInBytes() / 4;
6533 after = after * getBufferElementTypeWidthInBytes() / 4;
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." :
".");
6544 if (!isUnrankedMemRef &&
6545 (parentTile.isMemTile() || parentTile.isCoreTile())) {
6547 auto bufferOp = getBuffer().getDefiningOp<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 "
6556 << offsetInBytes <<
" (bytes)";
6559 if (
auto packetInfo = getPacket()) {
6562 if (packetInfo->getPktType() > 7)
6563 return emitOpError(
"Packet type field can only hold 3 bits.");
6564 if (packetInfo->assignedId() >
6566 return emitOpError(
"Packet ID field can only hold 5 bits.");
6574 if (!hasLen() && !getBuffer().getType().hasStaticShape())
6575 return emitOpError() <<
"buffer with dynamic shape requires static length.";
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.");
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.");
6586 if (axcache > 0xF) {
6587 return emitOpError(
"AxCache value out of 4-bit range.");
6594LogicalResult DMABDPACKETOp::verify() {
6597 if (getPacketType() < 0 || getPacketType() > 7)
6598 return emitOpError(
"Packet type field can only hold 3 bits.");
6599 if (getPacketID() < 0 ||
6601 static_cast<int32_t
>(
getTargetModel(getOperation()).getMaxPacketId()))
6602 return emitOpError(
"Packet ID field can only hold 5 bits.");
6606std::optional<int64_t> DMABDOp::getStaticLenInBytes() {
6608 if (std::optional<int32_t> len = getConstantLen()) {
6609 elems =
static_cast<uint32_t
>(*len);
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();
6620 return llvm::checkedMul(
6621 elems,
static_cast<int64_t
>(getBufferElementTypeWidthInBytes()));
6624uint32_t DMABDOp::getAxcacheOrDefault() {
6625 return getAxcache().value_or(
6633static LogicalResult FoldDMAStartOp(DMAStartOp op, PatternRewriter &rewriter) {
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();
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);
6655 if (isa<EndOp>((reachable.back())->getTerminator()))
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))
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);
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);
6681 uniquePattern.push_back(*patternIt);
6686 if (patternIt == reachable.end())
6690 while (patternIt != reachable.end()) {
6692 if (!areEquivalentBDs(*patternIt, uniquePattern[idx]))
6695 idx = (idx + 1) % uniquePattern.size();
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());
6712struct LinearizeContiguousBDTransfer :
public mlir::OpRewritePattern<DMABDOp> {
6713 using OpRewritePattern::OpRewritePattern;
6716 matchAndRewrite(DMABDOp op, mlir::PatternRewriter &rewriter)
const override {
6717 if (op.getStaticSizes().value_or(llvm::ArrayRef<int64_t>{}).empty())
6718 return mlir::failure();
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();
6736 auto isConstant = [](mlir::Value v) {
6737 return mlir::getConstantIntValue(v).has_value();
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();
6749 if (dims->size() == 1 && dims->front().getStride() == 1)
6750 return mlir::failure();
6752 int64_t product = 1;
6753 for (BDDimLayoutAttr dim : *dims)
6754 product *= dim.getSize();
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);
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);
6777 return mlir::success();
6785struct FoldConstantBDDimList :
public mlir::OpRewritePattern<DMABDOp> {
6786 using OpRewritePattern::OpRewritePattern;
6789 matchAndRewrite(DMABDOp op, mlir::PatternRewriter &rewriter)
const override {
6790 if (op.getSizes().empty() && op.getStrides().empty() && !op.getOffset() &&
6792 return mlir::failure();
6793 llvm::SmallVector<mlir::OpFoldResult> sizes = op.getMixedSizes();
6794 llvm::SmallVector<mlir::OpFoldResult> strides = op.getMixedStrides();
6800 bool changed = succeeded(mlir::foldDynamicIndexList(sizes)) |
6801 succeeded(mlir::foldDynamicIndexList(strides));
6804 std::optional<int32_t> foldOffset, foldLen;
6806 if (
auto c = mlir::getConstantIntValue(op.getOffset()))
6807 foldOffset =
static_cast<int32_t
>(*c);
6809 if (
auto c = mlir::getConstantIntValue(op.getLen()))
6810 foldLen =
static_cast<int32_t
>(*c);
6811 changed |= foldOffset.has_value() || foldLen.has_value();
6814 return mlir::failure();
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);
6824 bool wasDynamic = !op.getSizes().empty() || !op.getStrides().empty();
6825 if (!op.hasLen() && wasDynamic && dynSizes.empty() && dynStrides.empty() &&
6826 !staticSizes.empty()) {
6828 for (int64_t s : llvm::ArrayRef(staticSizes).take_back(3))
6830 foldLen =
static_cast<int32_t
>(extent);
6833 rewriter.modifyOpInPlace(op, [&]() {
6834 op.getSizesMutable().assign(dynSizes);
6835 op.getStridesMutable().assign(dynStrides);
6837 if (staticSizes.empty())
6838 op.removeStaticSizesAttr();
6840 op.setStaticSizes(staticSizes);
6841 if (staticStrides.empty())
6842 op.removeStaticStridesAttr();
6844 op.setStaticStrides(staticStrides);
6846 op.getOffsetMutable().clear();
6847 op.setStaticOffset(foldOffset);
6850 op.getLenMutable().clear();
6851 op.setStaticLen(foldLen);
6854 return mlir::success();
6859void DMABDOp::getCanonicalizationPatterns(RewritePatternSet &results,
6860 MLIRContext *context) {
6861 results.add<FoldConstantBDDimList, LinearizeContiguousBDTransfer>(context);
6864void DMAStartOp::getCanonicalizationPatterns(RewritePatternSet &results,
6865 MLIRContext *context) {
6866 results.add(FoldDMAStartOp);
6869RouteEndpointOp DMAStartOp::getEndpointOp() {
6870 FlatSymbolRefAttr name = getEndpoint();
6873 return SymbolTable::lookupNearestSymbolFrom<RouteEndpointOp>(*
this, name);
6876LogicalResult DMAStartOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
6877 FlatSymbolRefAttr name = getEndpoint();
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 "
6885 auto endpoint = symbolTable.lookupSymbolIn<RouteEndpointOp>(device, name);
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());
6899 return emitOpError() << name
6900 <<
" is on a different tile than this DMA program";
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");
6914 if (
auto program = dyn_cast<TileElement>((*this)->getParentOp());
6915 program && !getEndpoint())
6917 getOperation(), program.getTileLike(), getChannelDir(),
6918 getChannelIndex())))
6920 if (failed(verifyDMARepeatCount(getOperation(), getRepeatCount())))
6922 if (
auto program = dyn_cast<DmaBody>((*this)->getParentOp());
6923 program && !getEndpoint() &&
6925 getOperation(), cast<TileLike>(program.getTile().getDefiningOp()),
6926 getChannelDir(), getChannelIndex())))
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>());
6936 getOutOfOrder(), bds);
6943LogicalResult SwitchboxOp::verify() {
6949 if (!isa<TileOp>(getTile().getDefiningOp()))
6952 Region &body = getConnections();
6953 DenseSet<Port> sourceset;
6954 DenseSet<Port> destset;
6955 auto tile = getTileOp();
6958 return emitOpError(
"should have non-empty body");
6960 for (
auto connectOp : body.front().getOps<ConnectOp>())
6961 sourceset.insert({connectOp.getSourceBundle(), connectOp.sourceIndex()});
6962 for (
auto &ops : body.front()) {
6964 auto checkBound = [&ops](StringRef dir, WireBundle bundle,
int index,
6965 int bound) -> LogicalResult {
6966 if (index >= bound) {
6968 return ops.emitOpError(
"index ")
6969 << index <<
" for " << dir <<
" bundle "
6970 << stringifyWireBundle(bundle) <<
" must be less than "
6972 return ops.emitOpError()
6973 << dir <<
" bundle " << stringifyWireBundle(bundle)
6974 <<
" not supported; index: " << index <<
", bound: " << bound;
6979 if (
auto connectOp = dyn_cast<ConnectOp>(ops)) {
6980 Port source = {connectOp.getSourceBundle(), connectOp.sourceIndex()};
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 "
6990 << llvm::join(llvm::map_range(
6991 destset, [](
auto &p) {
return to_string(p); }),
6994 destset.insert(dest);
6996 if (connectOp.sourceIndex() < 0)
6997 return connectOp.emitOpError(
"source index cannot be less than zero");
6999 if (checkBound(
"source", connectOp.getSourceBundle(),
7000 connectOp.sourceIndex(),
7001 getNumSourceConnections(connectOp.getSourceBundle()))
7005 if (connectOp.destIndex() < 0)
7006 return connectOp.emitOpError(
"dest index cannot be less than zero");
7008 if (checkBound(
"dest", connectOp.getDestBundle(), connectOp.destIndex(),
7009 getNumDestConnections(connectOp.getDestBundle()))
7014 if (!isLegalTileConnection(tile, targetModel, connectOp))
7015 return connectOp.emitOpError(
"illegal stream switch connection");
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);
7025 if (connectOp.destIndex() < 0)
7026 return connectOp.emitOpError(
"dest index cannot be less than zero");
7028 if (checkBound(
"dest", connectOp.getDestBundle(), connectOp.destIndex(),
7029 getNumDestConnections(connectOp.getDestBundle()))
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);
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))
7052 for (
auto m : mstrs) {
7053 for (
auto s : slvs) {
7055 if (!isLegalTileConnection(tile, targetModel, m, s)) {
7056 return amselOp->emitOpError(
"illegal stream switch connection");
7060 }
else if (isa<EndOp>(ops)) {
7063 return ops.emitOpError(
"cannot be contained in a Switchbox op");
7070template <
typename... ParentOpTypes>
7073 Operation *operation = op->getParentOp();
7075 if (llvm::isa_and_nonnull<ParentOpTypes...>(operation))
7077 operation = operation->getParentOp();
7083TileOp LockOp::getTileOp() {
7084 return cast<TileElement>(this->getOperation()).getTileOp();
7087LogicalResult LockOp::verify() {
7088 if (
auto result = UsesAreAccessible::verifyTrait(*
this); result.failed())
7091 if (
auto lockID = getLockID()) {
7092 TileLike tileLike = getTileLike();
7094 return emitOpError(
"tile operand must implement TileLike interface");
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 <<
")";
7102 if (std::optional<int32_t> init = getInit()) {
7104 if (*init < 0 || *init > max)
7105 return emitOpError(
"init value ")
7106 << *init <<
" is outside the lock's range [0, " << max <<
"]";
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;
7123 auto *block = op->getBlock();
7125 for (
auto op : block->getOps<UseLockOp>()) {
7128 if (
auto lock = op.getLock().getDefiningOp<LockOp>();
7129 lock && lock.getLockID().has_value()) {
7130 if (lockID != -1 && lockID != lock.getLockIDValue())
7132 lockID = lock.getLockIDValue();
7141 auto *block = op->getBlock();
7142 int acqValue = -1, relValue = -1;
7143 for (
auto op : block->getOps<UseLockOp>()) {
7146 auto value = getConstantLockValue(op);
7149 if (op.acquire() || op.acquireGE()) {
7150 if (acqValue != -1 && acqValue != *value) {
7154 }
else if (op.release()) {
7155 if (relValue != -1 && relValue != *value) {
7167 if (
auto memOp = op->getParentOfType<MemOp>()) {
7168 auto useLock = cast<UseLockOp>(op);
7169 if (
auto lock = useLock.getLockOp(); lock.getTile() != memOp.getTile())
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")
7189LogicalResult UseLockOp::verify() {
7191 if (llvm::isa_and_nonnull<DeviceOp, ModuleOp>((*this)->getParentOp()))
7192 return (*this)->emitOpError(
"must be used in a core or memory operation.");
7200 if ((inDmaBlock || isInRuntimeDmaTask(*
this)) &&
7201 !getLock().getDefiningOp<LockOp>())
7202 return (*this)->emitOpError(
"lock operand is not an aie.lock");
7205 if (targetModel.
getTargetArch() == AIEArch::AIE1 && acquireGE())
7206 return (*this)->emitOpError(
7207 "AcquireGreaterEqual is not supported in AIE1.");
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).");
7219 if (!(*this)->getBlock())
7220 return (*this)->emitOpError(
"is not in a block.");
7224 return (*this)->emitOpError(
7225 "used in a DMA block that have multiple locks.");
7228 return (*this)->emitOpError(
"acquires/releases the lock in a DMA block "
7229 "from/to multiple states.");
7233 return (*this)->emitOpError(
"can only access a lock in the same tile");
7243 if (isInRuntimeDmaTask(*
this))
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";
7251#include "aie/Dialect/AIE/IR/AIEEnums.cpp.inc"
7252#include "aie/Dialect/AIE/IR/AIEInterfaces.cpp.inc"
7259static ParseResult parseTraceEventValue(AsmParser &parser, Attribute &value) {
7264static void printTraceEventValue(AsmPrinter &printer, Attribute value) {
7269static ParseResult parseTraceRegValue(OpAsmParser &parser, Attribute &value) {
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);
7283static void printTraceRegValue(OpAsmPrinter &printer, Operation *op,
7286 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(value)) {
7287 printer << intAttr.getInt();
7294#define GET_OP_CLASSES
7295#include "aie/Dialect/AIE/IR/AIEOps.cpp.inc"
7297FailureOr<int32_t> UseLockOp::getConstantValue() {
7298 if (
auto value = getConstantLockValue(*
this))
7300 return emitOpError(
"expected the lock value to be a compile-time constant "
7301 "(defined by an arith.constant).");
7304LogicalResult UseLockOp::canonicalize(UseLockOp op, PatternRewriter &rewriter) {
7308 if (op.acquireGE() && op->getBlock()->getOps<DMABDOp>().empty()) {
7309 if (
auto value = getConstantLockValue(op); value && *value == 0) {
7310 rewriter.eraseOp(op);
7317TileOp SwitchboxOp::getTileOp() {
7318 return cast<TileElement>(this->getOperation()).getTileOp();
7321size_t SwitchboxOp::getNumSourceConnections(WireBundle bundle) {
7322 auto tile = getTileOp();
7325 tile.getRow(), bundle);
7328size_t SwitchboxOp::getNumDestConnections(WireBundle bundle) {
7329 auto tile = getTileOp();
7332 tile.getRow(), bundle);
7335TileOp ShimMuxOp::getTileOp() {
7336 return cast<TileElement>(this->getOperation()).getTileOp();
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;
7366std::optional<std::pair<TileID, Port>>
7368 switch (output.bundle) {
7369 case WireBundle::North:
7372 case WireBundle::South:
7375 case WireBundle::East:
7378 case WireBundle::West:
7382 return std::nullopt;
7384 return std::pair(tile,
7388std::optional<std::pair<TileID, Port>>
7392 if (!endpoint || !targetModel.
isValidTile(endpoint->first))
7393 return std::nullopt;
7401ParseResult BDChainOp::parse(OpAsmParser &parser, OperationState &result) {
7402 SmallVector<OpAsmParser::Argument> entryArgs;
7405 StringAttr symNameAttr;
7406 if (parser.parseSymbolName(symNameAttr, SymbolTable::getSymbolAttrName(),
7407 result.attributes)) {
7412 ParseResult argParseResult = parser.parseCommaSeparatedList(
7413 OpAsmParser::Delimiter::Paren, [&]() -> ParseResult {
7414 OpAsmParser::Argument argument;
7415 if (parser.parseArgument(argument,
true,
true)) {
7418 entryArgs.push_back(argument);
7421 if (argParseResult) {
7422 return argParseResult;
7426 auto *body = result.addRegion();
7427 ParseResult bodyParseResult = parser.parseRegion(*body, entryArgs,
false);
7428 if (bodyParseResult) {
7429 return bodyParseResult;
7435void BDChainOp::print(OpAsmPrinter &printer) {
7438 ->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
7441 printer.printSymbolName(taskName);
7443 Region &body = getRegion();
7444 auto argsIter = body.getArguments();
7446 for (
auto *it = argsIter.begin(); it != argsIter.end(); ++it) {
7447 if (it != argsIter.begin()) {
7450 printer.printRegionArgument(*it);
7455 printer.printRegion(body,
false,
true);
7462LogicalResult ShimDMAAllocationOp::verify() {
7465 llvm::dyn_cast_or_null<TileLike>(getTile().getDefiningOp());
7467 return emitOpError(
"tile operand must implement TileLike interface");
7470 if (!tileLike.isShimNOCorPLTile()) {
7472 auto col = tileLike.tryGetCol();
7473 auto row = tileLike.tryGetRow();
7475 return emitOpError(
"tile must be a shim tile, but got tile(")
7476 << *col <<
", " << *row <<
")";
7478 return emitOpError(
"tile must be a shim tile");
7484 getChannelIndex())))
7487 return emitOpError(
"a PLIO allocation must be MM2S or S2MM");
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;
7505 std::optional<int> col = tileLike.tryGetCol();
7506 std::optional<int> row = tileLike.tryGetRow();
7511 bool mm2s = getChannelDir() == DMAChannelDir::MM2S;
7512 uint32_t ports = targetModel.
hasShimMux(*col, *row)
7514 *col, *row, WireBundle::PLIO)
7516 *col, *row, WireBundle::PLIO))
7518 *col, *row, WireBundle::PLIO)
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";
7529TileOp ShimDMAAllocationOp::getTileOp() {
7530 return dyn_cast_or_null<TileOp>(getTile().getDefiningOp());
7533ShimDMAAllocationOp ShimDMAAllocationOp::getForSymbol(DeviceOp device,
7534 llvm::StringRef symbol) {
7535 Operation *maybeOp = device.lookupSymbol(symbol);
7537 if (ShimDMAAllocationOp op = dyn_cast<ShimDMAAllocationOp>(maybeOp)) {
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()
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()
7565 if (getHeadBdIds().has_value() != getRepeatCounts().has_value())
7566 return emitOpError(
"head_bd_ids and repeat_counts must both be set or both "
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()
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()
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), "
7587 for (Value tile : getChannelTiles()) {
7588 auto tileOp = tile.getDefiningOp<TileOp>();
7590 return emitOpError(
"channel_tiles operands must be aie.tile values");
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");
7599 for (Value lock : getLocks())
7600 if (!lock.getDefiningOp<LockOp>())
7601 return emitOpError(
"locks operands must be aie.lock values");
7604 if (std::optional<ArrayRef<int32_t>> headBdIds = getHeadBdIds()) {
7606 for (
auto [tile, channel, bdId] :
7607 llvm::zip(getChannelTiles(), getChannelIndices(), *headBdIds)) {
7608 auto tileOp = tile.getDefiningOp<TileOp>();
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()
7624ParseResult RuntimeSequenceOp::parse(OpAsmParser &parser,
7625 OperationState &result) {
7628 StringAttr nameAttr;
7629 (void)parser.parseOptionalSymbolName(
7630 nameAttr, mlir::SymbolTable::getSymbolAttrName(), result.attributes);
7632 SmallVector<OpAsmParser::Argument> entryArgs;
7635 ParseResult argParseResult = parser.parseCommaSeparatedList(
7636 OpAsmParser::Delimiter::Paren, [&]() -> ParseResult {
7637 OpAsmParser::Argument argument;
7638 if (parser.parseArgument(argument,
true,
true)) {
7641 entryArgs.push_back(argument);
7644 if (argParseResult) {
7645 return argParseResult;
7650 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
7654 auto *body = result.addRegion();
7655 ParseResult bodyParseResult = parser.parseRegion(*body, entryArgs,
false);
7656 if (bodyParseResult) {
7657 return bodyParseResult;
7663void RuntimeSequenceOp::print(OpAsmPrinter &printer) {
7664 Region &body = getRegion();
7666 auto nameAttr = (*this)->getAttrOfType<StringAttr>(
7667 mlir::SymbolTable::getSymbolAttrName());
7669 nameAttr != ::mlir::OpBuilder((*this)->getContext())
7670 .getStringAttr(getDefaultRuntimeSequenceName())) {
7672 printer.printSymbolName(nameAttr);
7676 for (
unsigned i = 0, n = body.getNumArguments(); i < n; i++) {
7680 printer.printRegionArgument(body.getArgument(i));
7684 printer.printOptionalAttrDictWithKeyword(
7685 (*this)->getAttrs(),
7686 {mlir::SymbolTable::getSymbolAttrName()});
7689 printer.printRegion(body,
false,
true);
7692LogicalResult RuntimeSequenceOp::verify() {
7693 DeviceOp device = (*this)->getParentOfType<DeviceOp>();
7696 (*this)->emitOpError() <<
"must be inside AIE device operation.";
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()) {
7713 runtimeSequenceOp = *range.begin();
7715 Operation *maybeRuntimeSequenceOp =
7716 mlir::SymbolTable::lookupSymbolIn(deviceOp, symbol);
7717 if (!maybeRuntimeSequenceOp) {
7721 llvm::dyn_cast<RuntimeSequenceOp>(maybeRuntimeSequenceOp);
7723 return runtimeSequenceOp;
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;
7734 deviceOp.emitError(
"No runtime sequence in device");
7737 return runtimeSequenceOp;
7740LogicalResult RuntimeSequenceOp::verifyBeforeMaterialization() {
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);
7751 if (
auto flat = dyn_cast<FlatSymbolRefAttr>(symbolRef)) {
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)) {
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();
7771 if (BufferOp bufferOp = llvm::dyn_cast<BufferOp>(symbolDefOp)) {
7772 if (!bufferOp.getAddress()) {
7774 <<
"Unallocated buffer; fixed addresses are required before "
7775 "runtime sequence materialization.";
7776 return WalkResult::interrupt();
7780 return WalkResult::advance();
7782 if (walkResult.wasInterrupted()) {
7783 return WalkResult::interrupt();
7786 return WalkResult::advance();
7789 if (result.wasInterrupted()) {
7797#define GET_ATTRDEF_CLASSES
7798#include "aie/Dialect/AIE/IR/AIEAttrs.cpp.inc"
7801 ObjectFifoCreateOp objFifo,
7802 ObjectFifoPort port) {
7803 for (
auto coreOp : device.getOps<CoreOp>()) {
7804 if (coreOp.getTile() != tile) {
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;
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
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
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
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
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.
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
llvm::SmallVector< BDDimLayoutAttr > inner