555 bool warnUnsafeBdReuse, EffectFn effectOf) {
558 static_cast<AIE::DMAChannelDir
>(k[2]));
564 bool operator==(
const PathState &other)
const {
565 return queue == other.queue && completion == other.completion;
568 using States = llvm::SmallVector<PathState, 8>;
569 llvm::DenseMap<mlir::Value, unsigned> taskIndices;
570 auto track = [&](mlir::Value value) {
571 if (value && value.getType().isIndex())
572 taskIndices.try_emplace(value, taskIndices.size());
574 std::set<DmaQueueModel::ChannelKey> keys;
575 for (
const auto &[key, channel] : queue.
state())
576 if (depthOf(key) != 0)
578 llvm::DenseMap<mlir::Operation *, QueueEffect> effects;
579 body.walk([&](mlir::Operation *op) {
580 if (warnUnsafeBdReuse) {
581 for (mlir::Value value : op->getOperands())
583 for (mlir::Value value : op->getResults())
585 for (mlir::Region ®ion : op->getRegions())
586 for (mlir::Block &block : region)
587 for (mlir::Value arg : block.getArguments())
591 if (!warnUnsafeBdReuse) {
605 std::map<uint32_t, DmaQueueModel::ChannelKey> keyByStatus;
606 for (
const auto &key : keys)
608 key[0], key[1], key[3],
static_cast<AIE::DMAChannelDir
>(key[2])))
609 keyByStatus[*status] = key;
610 std::map<DmaQueueModel::ChannelKey, ChannelVisits> visits;
614 body.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
615 if (warnUnsafeBdReuse && mlir::isa<mlir::scf::ForOp, mlir::scf::IfOp>(op))
616 for (
const auto &key : keys)
618 if (
auto it = effects.find(op); it != effects.end()) {
619 visit(op, it->second.key);
620 }
else if (
auto poll = mlir::dyn_cast<NpuMaskPollOp>(op)) {
621 if (
auto address = poll.getAbsoluteAddress())
622 if (
auto it = keyByStatus.find(*address); it != keyByStatus.end())
623 visit(op, it->second);
629 for (
const auto &key : keys) {
630 uint32_t depth = depthOf(key);
632 auto channelEffectOf = [&](mlir::Operation *op) {
633 auto it = effects.find(op);
634 return it != effects.end() && it->second.key == key ? it->second
637 llvm::SetVector<mlir::Operation *> overflowing;
638 llvm::SetVector<mlir::Operation *> unsafeFrees;
639 std::map<mlir::Operation *, DmaQueueModel::ChannelState> witnesses;
640 bool trackCompletion = warnUnsafeBdReuse;
641 auto warnUnsafeFree = [&](mlir::Operation *op) {
642 if (warnUnsafeBdReuse && unsafeFrees.insert(op)) {
644 op, key[0], key[1],
static_cast<AIE::DMAChannelDir
>(key[2]),
646 if (!trackCompletion)
647 diag.attachNote() <<
"task ownership analysis budget exhausted; "
648 "completion is conservatively unproven";
651 size_t completionWork = 0;
652 auto equivalent = [&](
const PathState &a,
const PathState &b) {
653 return a.queue == b.queue &&
654 (!trackCompletion || a.completion == b.completion);
656 auto contains = [&](
const States &states,
const PathState &state) {
657 return llvm::any_of(states, [&](
const PathState &other) {
658 return equivalent(state, other);
661 auto compact = [&](States &states) {
663 for (
const auto &state : states)
664 if (!contains(unique, state))
665 unique.push_back(state);
666 states = std::move(unique);
670 auto append = [&](States &to,
const States &from) {
671 if (warnUnsafeBdReuse && !trackCompletion)
673 for (
const auto &state : from)
674 if (!contains(to, state)) {
675 if (trackCompletion && to.size() >= 256) {
676 trackCompletion =
false;
678 if (contains(to, state))
684 auto dedupe = [&](States &states) {
686 for (
auto &state : states)
687 state.completion.normalize();
688 if (states.size() < 2)
691 append(unique, states);
692 states = std::move(unique);
694 auto transfer = [&](States &states, mlir::ValueRange from,
695 mlir::ValueRange to) {
696 if (!trackCompletion)
698 for (
auto &state : states) {
699 auto previous = state.completion.tasks;
700 for (
auto [source, dest] : llvm::zip_equal(from, to)) {
701 auto src = taskIndices.find(source), dst = taskIndices.find(dest);
702 if (src != taskIndices.end() && dst != taskIndices.end())
703 state.completion.tasks[dst->second] = previous[src->second];
708 auto forgetScope = [&](States &states, mlir::Region ®ion,
709 bool keepArguments =
false) {
710 if (!trackCompletion)
712 for (
auto [value, index] : taskIndices) {
713 mlir::Region *parent = value.getParentRegion();
714 if (parent != ®ion && !region.isAncestor(parent))
717 if (
auto arg = mlir::dyn_cast<mlir::BlockArgument>(value))
718 if (arg.getOwner() == ®ion.front())
720 for (
auto &state : states)
721 state.completion.tasks[index] = 0;
728 static_cast<AIE::DMAChannelDir
>(key[2]), depth)
733 enum class PollEffect { Ignore, Space, Idle };
734 auto pollEffectOf = [&](NpuMaskPollOp poll) {
735 auto address = poll.getAbsoluteAddress();
738 if (!address || !mask || !value)
739 return PollEffect::Ignore;
741 key[0], key[1], key[3],
static_cast<AIE::DMAChannelDir
>(key[2]));
742 if (status != address)
743 return PollEffect::Ignore;
745 if (idleMask && (*mask & idleMask) == idleMask &&
746 (*value & idleMask) == 0)
747 return PollEffect::Idle;
749 if (!fieldMask || (depth & (depth - 1)) != 0)
750 return PollEffect::Ignore;
751 uint32_t depthBit = depth << llvm::countr_zero(fieldMask);
752 return depthBit && (depthBit & fieldMask) == depthBit &&
753 (*mask & depthBit) == depthBit && (*value & depthBit) == 0
755 : PollEffect::Ignore;
760 auto unknownRegion = [&](mlir::Region ®ion, States states) {
761 region.walk([&](mlir::Operation *op) {
767 for (
auto &state : states) {
768 state.queue.pushes.assign(depth,
false);
769 state.queue.unknownTokens =
true;
770 if (trackCompletion) {
771 state.completion.unknownTokens =
true;
772 state.completion.mayHaveDroppedPushes |= !canPoll;
773 for (
unsigned owner : state.completion.tasks)
775 state.completion.forgottenOwners.insert(owner);
777 state.completion.pushes.push_back(
779 state.completion.bound(depth + 1,
false);
781 if (overflowing.insert(op))
782 witnesses[op] = state.queue;
789 std::function<States(mlir::Region &, States)> analyze;
790 analyze = [&](mlir::Region ®ion, States states) -> States {
791 if (!region.hasOneBlock())
792 return unknownRegion(region, std::move(states));
793 auto blockVisits = channelVisits.find(®ion.front());
794 if (blockVisits == channelVisits.end())
796 for (mlir::Operation *visited : blockVisits->second) {
797 if (trackCompletion) {
798 completionWork += states.size();
799 if (completionWork > 16384) {
800 trackCompletion =
false;
804 mlir::Operation &op = *visited;
805 if (
auto loop = mlir::dyn_cast<mlir::scf::ForOp>(&op)) {
806 auto lb = mlir::getConstantIntValue(loop.getLowerBound());
807 auto ub = mlir::getConstantIntValue(loop.getUpperBound());
808 if (lb && ub && *lb >= *ub &&
809 (!loop->hasAttr(
"unsignedCmp") || (*lb >= 0 && *ub >= 0))) {
810 transfer(states, loop.getInitArgs(), loop.getResults());
816 transfer(states, loop.getInitArgs(), loop.getRegionIterArgs());
817 States reachable = states;
818 for (
size_t i = 0; i < reachable.size();) {
819 bool wasTrackingCompletion = trackCompletion;
820 States next = analyze(loop.getRegion(), States{reachable[i]});
821 transfer(next, loop.getYieldedValues(), loop.getRegionIterArgs());
822 forgetScope(next, loop.getRegion(),
true);
823 append(reachable, next);
824 if (wasTrackingCompletion && !trackCompletion) {
832 transfer(reachable, loop.getRegionIterArgs(), loop.getResults());
833 forgetScope(reachable, loop.getRegion());
834 states = std::move(reachable);
837 if (
auto branch = mlir::dyn_cast<mlir::scf::IfOp>(&op)) {
838 States alternatives = analyze(branch.getThenRegion(), states);
839 States otherwise = analyze(branch.getElseRegion(), states);
840 if (branch.getNumResults()) {
841 transfer(alternatives, branch.thenYield().getResults(),
842 branch.getResults());
843 transfer(otherwise, branch.elseYield().getResults(),
844 branch.getResults());
846 forgetScope(alternatives, branch.getThenRegion());
847 forgetScope(otherwise, branch.getElseRegion());
848 append(alternatives, otherwise);
849 states = std::move(alternatives);
852 for (mlir::Region &nested : op.getRegions())
853 states = unknownRegion(nested, std::move(states));
855 if (
auto poll = mlir::dyn_cast<NpuMaskPollOp>(&op))
856 if (
auto effect = pollEffectOf(poll); effect != PollEffect::Ignore) {
857 for (
auto &state : states) {
859 if (trackCompletion) {
860 if (effect == PollEffect::Idle)
861 state.completion.noteIdle();
863 state.completion.bound(depth,
true);
873 if (warnUnsafeBdReuse)
874 for (
const auto &state : states)
875 if (!trackCompletion ||
876 !state.completion.isProvenComplete(
877 state.completion.tasks[taskIndices.lookup(e.
task)]))
881 for (
auto &state : states) {
884 state.completion.tasks[taskIndices.lookup(e.
task)] =
885 taskIndices.size() + 1;
891 state.completion.awaitToken();
895 if (overflowing.insert(&op))
896 witnesses[&op] = state.queue;
898 if (trackCompletion && canPoll)
899 state.completion.bound(depth,
true);
900 else if (trackCompletion)
901 state.completion.mayHaveDroppedPushes =
true;
904 if (trackCompletion) {
906 e.
task ? state.completion.tasks[taskIndices.lookup(e.
task)] : 0;
907 state.completion.pushes.push_back({e.
issuesToken, owner});
908 state.completion.bound(depth + 1,
false);
917 if (
auto it = entry.find(key); it != entry.end())
918 channelEntry = it->second;
919 PathState initial{channelEntry, {}};
920 initial.completion.tasks.resize(taskIndices.size());
921 States exits = analyze(body, States{initial});
922 for (mlir::Operation *push : overflowing) {
923 queue.
setState({{key, witnesses[push]}});
931 for (
const auto &state : exits)
932 if (!(channelExit == state.queue)) {
933 channelExit.
pushes.assign(
934 std::max(channelExit.
pushes.size(), state.queue.pushes.size()),
938 merged[key] = channelExit;
958 const std::set<DmaQueueModel::ChannelKey> &awaited,
959 llvm::ArrayRef<SyncCover> mayAwait, EffectFn effectOf) {
960 mlir::Region &body = sequence.getBody();
961 auto covered = [](llvm::ArrayRef<SyncCover> covers,
963 return llvm::any_of(covers,
966 llvm::SmallVector<SyncCover> ownInexact;
967 body.walk([&](NpuSyncOp sync) {
973 llvm::DenseMap<mlir::Operation *, QueueEffect> effects;
974 std::map<DmaQueueModel::ChannelKey, ChannelVisits> visits;
975 body.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
979 (!awaited.count(e.
key) && !covered(mayAwait, e.
key)) ||
980 covered(ownInexact, e.
key))
986 auto describe = [](mlir::InFlightDiagnostic &diag,
988 diag <<
" on tile (" << key[0] <<
"," << key[1] <<
") "
989 << AIE::stringifyDMAChannelDir(
static_cast<AIE::DMAChannelDir
>(key[2]))
990 <<
" channel " << key[3];
993 constexpr int64_t maxFollowedTrips = 64;
994 bool consumed =
true;
995 for (
const auto &channel : visits) {
998 using Counts = std::set<int64_t>;
999 bool unknown =
false;
1000 std::function<Counts(mlir::Region &, Counts)> analyze;
1001 analyze = [&](mlir::Region ®ion, Counts counts) -> Counts {
1004 if (!region.hasOneBlock()) {
1008 auto visited = blocks.find(®ion.front());
1009 if (visited == blocks.end())
1011 for (mlir::Operation *at : visited->second) {
1012 mlir::Operation &op = *at;
1015 if (
auto it = effects.find(&op); it != effects.end()) {
1017 for (int64_t count : counts)
1019 ? count + it->second.issuesToken
1020 : std::max<int64_t>(count - 1, 0));
1021 counts = std::move(next);
1024 if (
auto loop = mlir::dyn_cast<mlir::scf::ForOp>(&op)) {
1025 auto lb = mlir::getConstantIntValue(loop.getLowerBound());
1026 auto ub = mlir::getConstantIntValue(loop.getUpperBound());
1027 auto step = mlir::getConstantIntValue(loop.getStep());
1028 if (lb && ub && step && *step > 0 && !loop->hasAttr(
"unsignedCmp")) {
1029 int64_t trips = *ub > *lb ? llvm::divideCeil(*ub - *lb, *step) : 0;
1030 if (trips <= maxFollowedTrips) {
1031 for (int64_t i = 0; i < trips && !unknown; i++)
1032 counts = analyze(loop.getRegion(), counts);
1036 for (int64_t count : counts) {
1037 Counts after = analyze(loop.getRegion(), Counts{count});
1040 if (after == Counts{count})
1042 auto diag = loop.emitOpError(
"changes how many task-completion "
1043 "tokens are outstanding");
1044 describe(diag, key);
1045 diag <<
" in each pass, so how many it leaves depends on its trip "
1046 "count; await as many tokens in each pass as it issues";
1053 if (
auto branch = mlir::dyn_cast<mlir::scf::IfOp>(&op)) {
1054 Counts taken = analyze(branch.getThenRegion(), counts);
1055 Counts otherwise = analyze(branch.getElseRegion(), counts);
1056 taken.insert(otherwise.begin(), otherwise.end());
1057 counts = std::move(taken);
1065 Counts exits = analyze(body, Counts{0});
1066 if (unknown || *exits.rbegin() == 0)
1068 int64_t left = *exits.rbegin();
1070 auto diag = mlir::emitError(sequence.getLoc())
1071 <<
"ends with " << left <<
" task-completion token"
1072 << (left > 1 ?
"s" :
"") <<
" no await consumes";
1073 describe(diag, key);
1074 diag <<
"; the next command's await on that channel would return for "
1075 "this sequence's transfer instead of its own. Await every "
1076 "token-issuing transfer before the sequence ends, or start it "
1077 "without issue_token";
1080 return mlir::success(consumed);