MLIR-AIE 1.4.6.dev
BdLowering.h
Go to the documentation of this file.
1//===- BdLowering.h ---------------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// Shared BD (buffer-descriptor) size/stride encoding used by both the static
9// (constant-folded) and dynamic (runtime SSA) DMA lowering paths.
10//
11// The hardware size/stride computation lives here ONCE as a policy-templated
12// algorithm (encodeHardwareStridesWraps) so the constant path and the dynamic
13// arith-emitting path cannot drift -- a divergence would silently miscompile a
14// descriptor. The constant path instantiates it with ConstStridePolicy (plain
15// integer math); the dynamic path uses SsaStridePolicy (emits arith ops).
16//
17// The same reasoning extends across TILE TYPES: the register bit layout, which
18// genuinely differs between shim NOC, mem tile and core tile BDs, comes from
19// AIETargetModel::getDmaBdLayout, and both this packer and AIEDmaToNpu.cpp's
20// WriteBdToBlockWritePattern place fields through it.
21//
22//===----------------------------------------------------------------------===//
23
24#ifndef AIE_DIALECT_AIEX_UTILS_BDLOWERING_H
25#define AIE_DIALECT_AIEX_UTILS_BDLOWERING_H
26
28
29#include "mlir/Dialect/Utils/StaticValueUtils.h"
30#include "mlir/IR/Builders.h"
31#include "mlir/IR/BuiltinTypes.h"
32#include "mlir/IR/Operation.h"
33#include "mlir/IR/Value.h"
34#include "mlir/Support/LLVM.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/Twine.h"
37
38#include <cstdint>
39#include <numeric>
40#include <tuple>
41
42namespace xilinx::AIE {
43class AIETargetModel;
44} // namespace xilinx::AIE
45
46namespace xilinx::AIEX {
47
48// The address generator transfers whole granules only, so a size or stride is
49// realizable iff its byte extent (value * elemWidth) is a granule multiple.
50// Dividing through by gcd(elemWidth, gran), that is `value % divisor == 0` with
51// divisor = gran / gcd(elemWidth, gran) -- the element-count multiple a size or
52// stride must land on (e.g. int8 against a 32-bit granule => divisor 4). Shared
53// so the static verifier, the dynamic verifier, and the runtime guard apply one
54// definition.
55//
56// These realizability predicates are header-inline (no AIEX-op dependencies) so
57// the AIEX dialect verifier can call them without the AIEX IR library depending
58// on AIEXUtils -- which would close a link cycle (AIEXUtils already uses AIEX
59// ops).
60inline int64_t bdGranuleDivisor(uint64_t elemWidth,
61 uint32_t addressGranularity) {
62 return addressGranularity / std::gcd(elemWidth, (uint64_t)addressGranularity);
63}
64
65// Whether a constant element count is realizable: value * elemWidth is a whole
66// number of granules. Equivalent to value % bdGranuleDivisor(...) == 0.
67inline bool isConstMultipleOfGranule(int64_t value, uint64_t elemWidth,
68 uint32_t addressGranularity) {
69 return value * (int64_t)elemWidth % (int64_t)addressGranularity == 0;
70}
71
72// Check the constant size/stride operands (innermost-first) of a shim-NOC BD
73// for realizability: d0 size and every non-unit stride must be a whole number
74// of granules (a unit innermost stride is the exempt contiguous case), and a
75// stride must be positive where its size > 1. Runtime operands are skipped
76// (buildBdWords guards them on the host). Shared by both dynamic paths;
77// emits a diagnostic on `op` and fails on the first violation.
78inline mlir::LogicalResult
79verifyConstBdRealizability(mlir::Operation *op,
80 llvm::ArrayRef<mlir::OpFoldResult> sizes,
81 llvm::ArrayRef<mlir::OpFoldResult> strides,
82 uint64_t elemWidth, uint32_t gran) {
83 std::optional<int64_t> d0Size =
84 sizes.empty() ? std::nullopt : mlir::getConstantIntValue(sizes[0]);
85 if (d0Size && !isConstMultipleOfGranule(*d0Size, elemWidth, gran))
86 return op->emitOpError("d0 size ")
87 << *d0Size << " elements at " << (elemWidth / 8)
88 << " bytes each is not a multiple of the " << (gran / 8)
89 << "-byte address-gen granule.";
90 for (int i = 0; i < (int)strides.size(); i++) {
91 auto s = mlir::getConstantIntValue(strides[i]);
92 if (!s)
93 continue;
94 // A unit innermost stride is the contiguous case: successive elements are
95 // packed with no gap, so the transfer is dense and the stride need not land
96 // on a granule boundary. Every other stride addresses a strided access and
97 // must be granule-aligned. A non-word element's innermost stride must be
98 // 1 (see verifyStridesWraps).
99 if (i == 0 && *s == 1)
100 continue;
101 if (!isConstMultipleOfGranule(*s, elemWidth, gran))
102 return op->emitOpError("stride ")
103 << i << " is " << *s << " elements at " << (elemWidth / 8)
104 << " bytes each, not a multiple of the " << (gran / 8)
105 << "-byte address-gen granule.";
106 if (i == 0 && elemWidth != gran && !(d0Size && *d0Size <= 1))
107 return op->emitOpError("stride 0 is ")
108 << *s << " elements, but must be 1 for " << (elemWidth / 8)
109 << "-byte elements: the DMA moves whole " << (gran / 8)
110 << "-byte granules.";
111 }
112 // A stride must be positive where its size > 1 (it is never applied when
113 // size == 1). The d3 iteration dimension is the exception: a zero stride
114 // there is the pure-repeat case (the BD wraps every iteration, repeat carried
115 // by the queue push), matching verifyStridesWraps' dim-3 `< 0` rule. Lists
116 // are innermost-first, so d3 is index 3 (present only for a full 4D
117 // descriptor).
118 //
119 // A RUNTIME size does not excuse the stride: the encoder would scale a zero
120 // stride to -1, an all-ones step field, so such a stride is only legal when
121 // the size is a compile-time 1, the one case where it is never applied. It
122 // is rejected here rather than by a host-side check at every dispatch.
123 constexpr int kIterDim = 3;
124 for (int i = 0; i < (int)sizes.size() && i < (int)strides.size(); i++) {
125 auto sz = mlir::getConstantIntValue(sizes[i]);
126 auto st = mlir::getConstantIntValue(strides[i]);
127 if (!st || (sz && *sz <= 1))
128 continue;
129 if (i == kIterDim ? *st < 0 : *st < 1)
130 return op->emitOpError("stride ")
131 << i
132 << (i == kIterDim
133 ? " must be non-negative unless its size is statically 1."
134 : " must be positive unless its size is statically 1.");
135 }
136 return mlir::success();
137}
138
139// Shared hardware size/stride encoder. The BD encodes each dimension's wrap
140// ("size") scaled to address-gen granules and step ("stride") in granules less
141// DmaBdLayout::stepBias. One algorithm drives both lowerings via a
142// Policy: ConstStridePolicy (int64 math) for the static path, SsaStridePolicy
143// (arith ops) for runtime operands -- keeping them bit-identical. The Policy
144// supplies cst/mul/div/sub and selectGT1/selectGT0/selectLt. Inputs/outputs are
145// 4-element arrays in innermost-first order [d0, d1, d2, d3/iter].
146template <typename Policy>
147void encodeHardwareStridesWraps(Policy &p, uint64_t elemWidth,
148 uint32_t addressGranularity, int64_t stepBias,
149 typename Policy::V inputSizes[4],
150 typename Policy::V inputStrides[4],
151 typename Policy::V sizes[4],
152 typename Policy::V strides[4]) {
153 using V = typename Policy::V;
154 // Scale an element-count stride into hardware granules and apply the bias:
155 // stride * elemWidth / addressGranularity - stepBias
156 auto biasedStride = [&](V inStride) -> V {
157 V granules = p.div(p.mul(inStride, elemWidth), addressGranularity);
158 return stepBias ? p.sub(granules, stepBias) : granules;
159 };
160
161 // d0_size, d0_stride
162 sizes[0] = p.div(p.mul(inputSizes[0], elemWidth), addressGranularity);
163 // d0_stride collapses to hardware 0 for a sub-granule stride (byte extent <
164 // one granule, i.e. the contiguous unit-stride case) or a wide element; else
165 // it is the biased stride. The wide-element test is compile-time; the
166 // sub-granule test is a policy select, so the stride may be runtime. A
167 // non-unit stride over elements narrower or wider than a granule is
168 // unrealizable and rejected/guarded elsewhere.
169 if (elemWidth > addressGranularity) {
170 strides[0] = p.cst(0);
171 } else {
172 strides[0] = p.selectLt(p.mul(inputStrides[0], elemWidth),
173 p.cst((int64_t)addressGranularity), p.cst(0),
174 biasedStride(inputStrides[0]));
175 }
176
177 // d1_size, d1_stride / d2_size, d2_stride: stride only matters when size > 1.
178 sizes[1] = inputSizes[1];
179 strides[1] =
180 p.selectGT1(inputSizes[1], biasedStride(inputStrides[1]), p.cst(0));
181 sizes[2] = inputSizes[2];
182 strides[2] =
183 p.selectGT1(inputSizes[2], biasedStride(inputStrides[2]), p.cst(0));
184
185 // iteration_size, iteration_stride. Size is stored biased by -1. The stride
186 // must be positive like the others, but a zero-stride "repeat" is encoded by
187 // leaving size at 1 (via a positive repeat_count on the queue push) so the BD
188 // wraps every iteration and never adds the stride. Hence stride is gated on
189 // BOTH size > 1 and inStride > 0.
190 sizes[3] = p.selectGT1(inputSizes[3], p.sub(inputSizes[3], 1), p.cst(0));
191 strides[3] = p.selectGT1(
192 inputSizes[3],
193 p.selectGT0(inputStrides[3], biasedStride(inputStrides[3]), p.cst(0)),
194 p.cst(0));
195}
196
197// Constant (compile-time int64) policy: plain integer arithmetic.
199 using V = int64_t;
200 static V cst(int64_t c) { return c; }
201 static V mul(V v, int64_t c) { return v * c; }
202 static V div(V v, int64_t c) { return v / c; }
203 static V sub(V v, int64_t c) { return v - c; }
204 static V selectGT1(V cond, V t, V e) { return cond > 1 ? t : e; }
205 static V selectGT0(V cond, V t, V e) { return cond > 0 ? t : e; }
206 static V selectLt(V a, V b, V t, V e) { return a < b ? t : e; }
207};
208
209// SSA (runtime arith) policy: emits i64 arith ops mirroring ConstStridePolicy.
210// Every primitive builds an arith op at the policy's insertion point, so the
211// innermost stride may be a runtime value like any other dimension.
213 using V = mlir::Value;
214 mlir::OpBuilder &builder;
215 mlir::Location loc;
216
217 SsaStridePolicy(mlir::OpBuilder &b, mlir::Location l) : builder(b), loc(l) {}
218
219 V cst(int64_t c) const;
220 V mul(V v, int64_t c) const;
221 V div(V v, int64_t c) const;
222 V sub(V v, int64_t c) const;
223 V selectGT1(V cond, V t, V e) const;
224 V selectGT0(V cond, V t, V e) const;
225 V selectLt(V a, V b, V t, V e) const;
226};
227
228// Require `cond` to hold when the runtime sequence runs. A condition that
229// folds to true emits nothing and one that folds to false is a compile-time
230// error at `loc`; otherwise a cf.assert carries `message` to the TXN builder,
231// which refuses the dispatch when it fails.
232mlir::LogicalResult emitRuntimeCheck(mlir::OpBuilder &builder,
233 mlir::Location loc, mlir::Value cond,
234 const llvm::Twine &message);
235
236// Erase the arith ops under `root` left unused once the runtime BD words and
237// guards built with these helpers have folded.
238void eraseDeadArith(mlir::Operation *root);
239
240// Coerce an OpFoldResult (constant attr or SSA value) to an SSA Value of the
241// given integer type, materializing an arith.constant / trunc / extui as
242// needed.
243mlir::Value getAsValue(mlir::OpBuilder &builder, mlir::Location loc,
244 mlir::OpFoldResult ofr, mlir::Type intType);
245
246// An integer or index OpFoldResult as an i64 Value, zero-extended (a negative
247// value reads as a huge one the guards reject). An operand wider than 64 bits
248// gets a host-side check that it fits; null if that check folds to false.
249mlir::Value getAsI64(mlir::OpBuilder &builder, mlir::Location loc,
250 mlir::OpFoldResult ofr);
251
252// Build the address-patch `arg_plus` (buffer BYTE offset):
253// sum(elementOffsets[i] * strides[i]) * elemWidthBytes + baseByteOffset, where
254// any entry may be runtime. A fully-constant set folds to one i32 constant (i64
255// when it does not fit), byte-identical to the static path; a runtime one is
256// i64 arith with a host-side check that it is `granuleBytes`-aligned. Null if
257// a check folds to false.
258mlir::Value buildArgPlusValue(mlir::OpBuilder &builder, mlir::Location loc,
259 llvm::ArrayRef<mlir::OpFoldResult> elementOffsets,
260 llvm::ArrayRef<mlir::OpFoldResult> strides,
261 int64_t elemWidthBytes, int64_t baseByteOffset,
262 uint32_t granuleBytes);
263
264// Require a runtime BD walk to stay inside its host buffer: the furthest
265// element it touches, sum(offsets[k] * offsetStrides[k]) +
266// sum((sizes[i] - 1) * strides[i]), must lie within `hostBufferType` past
267// `baseByteOffset`. An unknown (dynamic) shape bounds the walk at 2^32
268// elements, which still rejects a negative offset.
269mlir::LogicalResult
270guardWithinHostBuffer(mlir::OpBuilder &builder, mlir::Location loc,
271 mlir::BaseMemRefType hostBufferType,
272 int64_t baseByteOffset, int64_t elemWidthBytes,
273 llvm::ArrayRef<mlir::OpFoldResult> offsets,
274 llvm::ArrayRef<mlir::OpFoldResult> offsetStrides,
275 llvm::ArrayRef<mlir::OpFoldResult> sizes,
276 llvm::ArrayRef<mlir::OpFoldResult> strides);
277
278// Pack a set of (value, mask, shift) fields into a single i32 BD word via
279// arith and/shl/or. mask == 0xFFFFFFFF skips the AND; shift == 0 skips the SHL.
280mlir::Value
281buildBdWord(mlir::OpBuilder &builder, mlir::Location loc,
282 llvm::ArrayRef<std::tuple<mlir::Value, uint32_t, uint32_t>> fields);
283
284// The base register address of a BD block, `getDmaBdAddress(col,row,bd_id)`, as
285// an i32 Value. The address is linear in bd_id over the BD pool of `channel` in
286// `direction` (base + bd_id*bdStride), so a constant bdId folds to the exact
287// literal the static path uses, while a runtime bdId (dynamic free-list pool)
288// is emitted as arith. Without a channel the pool is taken to start at id 0.
289// Shared by the BD-word encoder and the descriptor / address-patch lowering so
290// every register touched for one BD is computed from the same base.
292 mlir::OpBuilder &builder, mlir::Location loc,
293 const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow,
294 mlir::OpFoldResult bdId, int channel = -1,
295 xilinx::AIE::DMAChannelDir direction = xilinx::AIE::DMAChannelDir::MM2S);
296
297// Fails with a diagnostic for BDs runtime lowerings cannot write yet
298// (tiles without a DmaBdLayout, ControlMM2S/TraceS2MM channels).
299mlir::LogicalResult verifyRuntimeBdTarget(
300 mlir::Operation *op, const xilinx::AIE::AIETargetModel &targetModel,
301 int tileCol, int tileRow,
302 xilinx::AIE::DMAChannelDir direction = xilinx::AIE::DMAChannelDir::MM2S);
303
304// Fails with a diagnostic for a nonzero packet type on a BD without that
305// field (the packet type is then a channel setting).
306mlir::LogicalResult
307verifyBdPacketType(mlir::Operation *op,
308 const xilinx::AIE::AIETargetModel &targetModel, int tileCol,
309 int tileRow, uint32_t packetType);
310
311// Lock, packet and next_bd fields, gathered by the caller from the DMA
312// structure and baked into the template words. Only next_bd and the lock values
313// may be runtime: `next_bd_id_val`, when set, replaces `next_bd_id` (a chain
314// whose successor draws its id from the dynamic pool), and `lock_*_val_val`
315// replaces `lock_*_val` already in field encoding (an AcquireGE negated).
317 uint32_t use_next_bd = 0, next_bd_id = 0;
318 mlir::Value next_bd_id_val;
319 int32_t enable_packet = 0, packet_id = 0, packet_type = 0;
320 int32_t out_of_order_id = 0;
321 int32_t iteration_current = 0;
322 int32_t lock_rel_val = 0, lock_rel_id = 0;
325};
326
327// Build a BD's full register block as i32 SSA values, for the dynamic lowering
328// shared by dma_memcpy_nd and dma_task. The block is DmaBdLayout::numWords
329// words. Every word is written (unset slots are zero),
330// so a BD slot reused from the runtime pool cannot inherit a stale field.
331//
332// `mixedSizes`/`mixedStrides` are outermost-first (d3..d0), matching
333// NpuDmaMemcpyNdOp::getMixedSizes and AIE::DMABDOp::getMixedSizes.
334// buffer_length is the d0*d1*d2 extent in granules. `lenElems`, if set, is a
335// dma_task's explicit transfer length, which must agree with it.
336// `burstLength`/`axcache` are shim-NOC-only fields and are ignored on the
337// other tile types (their verifiers already require the defaults there). Every
338// size and stride gets a host-side check (emitRuntimeCheck) that it fits its BD
339// field and is granule-realizable, so a value the field would truncate refuses
340// the dispatch instead. `repeatCountOut` receives the outer-dim hardware repeat
341// for the caller's queue push.
342//
343// The words do not depend on the BD id -- only the register ADDRESS does, and
344// that is the caller's `getBdRegisterBase` + `npu.blockwrite_values` -- so one
345// routine serves both a pinned bd_id and one drawn from the runtime pool.
346//
347// The tile at (`tileCol`, `tileRow`) must have a target-model DmaBdLayout; the
348// caller is responsible for rejecting anything else with a user-facing
349// diagnostic before calling.
350mlir::LogicalResult
351buildBdWords(mlir::OpBuilder &builder, mlir::Location loc,
352 const xilinx::AIE::AIETargetModel &targetModel, int tileCol,
353 int tileRow, const BdTemplateFields &fields,
354 llvm::ArrayRef<mlir::OpFoldResult> mixedSizes,
355 llvm::ArrayRef<mlir::OpFoldResult> mixedStrides,
356 uint64_t elemWidth, uint32_t burstLength, uint32_t axcache,
357 mlir::OpFoldResult lenElems, mlir::Value &repeatCountOut,
358 llvm::SmallVectorImpl<mlir::Value> &wordsOut);
359
360} // namespace xilinx::AIEX
361
362#endif // AIE_DIALECT_AIEX_UTILS_BDLOWERING_H
mlir::LogicalResult verifyRuntimeBdTarget(mlir::Operation *op, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, xilinx::AIE::DMAChannelDir direction=xilinx::AIE::DMAChannelDir::MM2S)
int64_t bdGranuleDivisor(uint64_t elemWidth, uint32_t addressGranularity)
Definition BdLowering.h:60
mlir::Value buildBdWord(mlir::OpBuilder &builder, mlir::Location loc, llvm::ArrayRef< std::tuple< mlir::Value, uint32_t, uint32_t > > fields)
mlir::Value buildArgPlusValue(mlir::OpBuilder &builder, mlir::Location loc, llvm::ArrayRef< mlir::OpFoldResult > elementOffsets, llvm::ArrayRef< mlir::OpFoldResult > strides, int64_t elemWidthBytes, int64_t baseByteOffset, uint32_t granuleBytes)
mlir::Value getAsValue(mlir::OpBuilder &builder, mlir::Location loc, mlir::OpFoldResult ofr, mlir::Type intType)
mlir::Value getBdRegisterBase(mlir::OpBuilder &builder, mlir::Location loc, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, mlir::OpFoldResult bdId, int channel=-1, xilinx::AIE::DMAChannelDir direction=xilinx::AIE::DMAChannelDir::MM2S)
void encodeHardwareStridesWraps(Policy &p, uint64_t elemWidth, uint32_t addressGranularity, int64_t stepBias, typename Policy::V inputSizes[4], typename Policy::V inputStrides[4], typename Policy::V sizes[4], typename Policy::V strides[4])
Definition BdLowering.h:147
mlir::LogicalResult guardWithinHostBuffer(mlir::OpBuilder &builder, mlir::Location loc, mlir::BaseMemRefType hostBufferType, int64_t baseByteOffset, int64_t elemWidthBytes, llvm::ArrayRef< mlir::OpFoldResult > offsets, llvm::ArrayRef< mlir::OpFoldResult > offsetStrides, llvm::ArrayRef< mlir::OpFoldResult > sizes, llvm::ArrayRef< mlir::OpFoldResult > strides)
mlir::LogicalResult buildBdWords(mlir::OpBuilder &builder, mlir::Location loc, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, const BdTemplateFields &fields, llvm::ArrayRef< mlir::OpFoldResult > mixedSizes, llvm::ArrayRef< mlir::OpFoldResult > mixedStrides, uint64_t elemWidth, uint32_t burstLength, uint32_t axcache, mlir::OpFoldResult lenElems, mlir::Value &repeatCountOut, llvm::SmallVectorImpl< mlir::Value > &wordsOut)
mlir::Value getAsI64(mlir::OpBuilder &builder, mlir::Location loc, mlir::OpFoldResult ofr)
void eraseDeadArith(mlir::Operation *root)
bool isConstMultipleOfGranule(int64_t value, uint64_t elemWidth, uint32_t addressGranularity)
Definition BdLowering.h:67
mlir::LogicalResult emitRuntimeCheck(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value cond, const llvm::Twine &message)
mlir::LogicalResult verifyConstBdRealizability(mlir::Operation *op, llvm::ArrayRef< mlir::OpFoldResult > sizes, llvm::ArrayRef< mlir::OpFoldResult > strides, uint64_t elemWidth, uint32_t gran)
Definition BdLowering.h:79
mlir::LogicalResult verifyBdPacketType(mlir::Operation *op, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, uint32_t packetType)
static V div(V v, int64_t c)
Definition BdLowering.h:202
static V selectLt(V a, V b, V t, V e)
Definition BdLowering.h:206
static V sub(V v, int64_t c)
Definition BdLowering.h:203
static V selectGT0(V cond, V t, V e)
Definition BdLowering.h:205
static V mul(V v, int64_t c)
Definition BdLowering.h:201
static V selectGT1(V cond, V t, V e)
Definition BdLowering.h:204
V selectGT1(V cond, V t, V e) const
V div(V v, int64_t c) const
V sub(V v, int64_t c) const
SsaStridePolicy(mlir::OpBuilder &b, mlir::Location l)
Definition BdLowering.h:217
mlir::OpBuilder & builder
Definition BdLowering.h:214
V selectGT0(V cond, V t, V e) const
V mul(V v, int64_t c) const
V selectLt(V a, V b, V t, V e) const