25#include "mlir/Conversion/ArithCommon/CeilFloorDivExpansion.h"
26#include "mlir/Conversion/ArithToEmitC/ArithToEmitC.h"
27#include "mlir/Conversion/SCFToEmitC/SCFToEmitC.h"
28#include "mlir/Dialect/Arith/IR/Arith.h"
29#include "mlir/Dialect/Arith/Transforms/Passes.h"
30#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
31#include "mlir/Dialect/EmitC/IR/EmitC.h"
32#include "mlir/Dialect/EmitC/Transforms/TypeConversions.h"
33#include "mlir/Dialect/MemRef/IR/MemRef.h"
34#include "mlir/Dialect/SCF/IR/SCF.h"
35#include "mlir/IR/Builders.h"
36#include "mlir/IR/BuiltinOps.h"
37#include "mlir/Interfaces/SideEffectInterfaces.h"
38#include "mlir/Pass/Pass.h"
39#include "mlir/Transforms/DialectConversion.h"
40#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
41#include "mlir/Transforms/RegionUtils.h"
43#include "llvm/ADT/StringSet.h"
44#include "llvm/ADT/TypeSwitch.h"
45#include "llvm/Support/Format.h"
50#define GEN_PASS_DECL_CONVERTAIEXTOEMITC
51#define GEN_PASS_DEF_CONVERTAIEXTOEMITC
52#include "aie/Conversion/Passes.h.inc"
62static std::string refuse(StringRef why,
bool inFormat) {
65 if (ch ==
'\n' || ch ==
'\r')
67 else if (ch ==
'"' || ch ==
'\\')
69 else if (ch ==
'{' && inFormat)
74 return "return aie_runtime::txn_refused(\"" + lit +
"\");";
82constexpr llvm::StringLiteral kTxnVecType =
"std::vector<uint32_t>";
84emitc::OpaqueType getU32Type(MLIRContext *ctx) {
85 return emitc::OpaqueType::get(ctx,
"uint32_t");
91template <
typename PoolOp>
92std::string bdPoolName(PoolOp op) {
93 return "bd_pool_" + std::to_string(op.getColumn()) +
"_" +
94 std::to_string(op.getRow()) +
"_" + std::to_string(op.getBdBegin()) +
95 "_" + std::to_string(op.getBdEnd());
100Value u32Literal(OpBuilder &b, Location loc, uint32_t val) {
101 return emitc::ConstantOp::create(
102 b, loc, getU32Type(b.getContext()),
103 emitc::OpaqueAttr::get(b.getContext(), std::to_string(val) +
"u"));
109void emitTxnCall(OpBuilder &b, Location loc, StringRef fn, Value txnVec,
111 SmallVector<Value> callArgs;
112 callArgs.push_back(txnVec);
113 callArgs.append(
args.begin(),
args.end());
114 emitc::CallOpaqueOp::create(b, loc, TypeRange{}, (
"aie_runtime::" + fn).str(),
120struct DeviceResolved {
121 llvm::DenseMap<Operation *, uint32_t> absoluteAddr;
122 llvm::DenseMap<Operation *, DenseIntElementsAttr> blockWriteData;
125class AIEXToEmitCConverter {
127 AIEXToEmitCConverter(emitc::FuncOp funcOp, Value txnVec,
128 const DeviceResolved &resolved, Value opCountVar,
129 bool foldDDRAddrOffset)
130 : funcOp(funcOp), txnVec(txnVec), resolved(resolved),
131 opCountVar(opCountVar), foldDDRAddrOffset(foldDDRAddrOffset) {}
137 std::optional<uint32_t> run() {
144 funcOp.walk([&](Operation *op) {
145 if (isa<memref::MemRefDialect>(op->getDialect()) &&
146 isOpTriviallyDead(op)) {
153 SmallVector<Operation *> consumed;
154 convertBlockRecursive(funcOp.getBlocks().front(), count, consumed);
163 for (Operation *op : llvm::reverse(consumed))
165 IRRewriter rewriter(funcOp.getContext());
166 (void)runRegionDCE(rewriter, funcOp.getFunctionBody());
174 void convertBlockRecursive(Block &block, uint32_t &count,
175 SmallVector<Operation *> &consumed) {
176 SmallVector<Operation *> work;
177 for (Operation &op : block)
179 for (Operation *op : work) {
186 if (isa<emitc::EmitCDialect, arith::ArithDialect>(op->getDialect()))
188 if (isa<scf::SCFDialect>(op->getDialect())) {
189 for (Region &r : op->getRegions())
191 convertBlockRecursive(b, count, consumed);
194 convertOne(op, count);
195 if (!isa<memref::GetGlobalOp>(op))
196 consumed.push_back(op);
205 void countOp(OpBuilder &b, Location loc, uint32_t &count) {
208 emitc::VerbatimOp::create(b, loc,
"++{};", ValueRange{opCountVar});
215 void convertOne(Operation *op, uint32_t &count) {
217 Location loc = op->getLoc();
219 llvm::TypeSwitch<Operation *, void>(op)
220 .Case<AIEX::NpuWrite32Op>([&](
auto w) {
224 Value addrV = runtimeOrResolvedAddr(b, loc, w, w.getAddress());
226 return fail(w,
"cannot convert a symbolic/unresolved write32 "
227 "address to the C++ TXN target");
228 emitTxnCall(b, loc,
"txn_append_write32", txnVec,
229 {addrV, w.getValue()});
230 countOp(b, loc, count);
232 .Case<AIEX::NpuMaskWrite32Op>([&](
auto mw) {
233 Value addrV = runtimeOrResolvedAddr(b, loc, mw, mw.getAddress());
235 return fail(mw,
"cannot convert a symbolic/unresolved maskwrite32 "
236 "address to the C++ TXN target");
237 emitTxnCall(b, loc,
"txn_append_maskwrite32", txnVec,
238 {addrV, mw.getValue(), mw.getMask()});
239 countOp(b, loc, count);
241 .Case<AIEX::NpuMaskPollOp>([&](
auto mp) {
242 Value addrV = runtimeOrResolvedAddr(b, loc, mp, mp.getAddress());
244 return fail(mp,
"cannot convert a symbolic/unresolved maskpoll "
245 "address to the C++ TXN target");
246 emitTxnCall(b, loc,
"txn_append_maskpoll32", txnVec,
247 {addrV, mp.getValue(), mp.getMask()});
248 countOp(b, loc, count);
250 .Case<AIEX::NpuSyncOp>([&](
auto s) {
251 emitTxnCall(b, loc,
"txn_append_sync", txnVec,
252 {s.getColumn(), s.getRow(), s.getDirection(),
253 s.getChannel(), s.getColumnNum(), s.getRowNum()});
254 countOp(b, loc, count);
256 .Case<AIEX::NpuLoadPdiOp>([&](
auto pdi) {
257 Value address = emitc::ConstantOp::create(
258 b, loc, emitc::OpaqueType::get(b.getContext(),
"uint64_t"),
259 emitc::OpaqueAttr::get(b.getContext(),
260 std::to_string(pdi.getAddress()) +
"ULL"));
261 emitTxnCall(b, loc,
"txn_append_loadpdi", txnVec,
262 {u32Literal(b, loc, pdi.getId()),
263 u32Literal(b, loc, pdi.getSize()), address});
264 countOp(b, loc, count);
266 .Case<AIEX::NpuPreemptOp>([&](
auto preempt) {
267 emitTxnCall(b, loc,
"txn_append_preempt", txnVec,
268 {u32Literal(b, loc, preempt.getLevel())});
269 countOp(b, loc, count);
271 .Case<AIEX::NpuAddressPatchOp>([&](
auto ap) {
274 Value addrV = ap.getAddrVal() ? ap.getAddrVal()
275 : u32Literal(b, loc, ap.getAddr());
276 std::optional<uint32_t> argIdx = ap.getArgIdx();
278 return fail(ap,
"address_patch still names its host buffer by SSA "
279 "value; run -aie-resolve-address-patch-buffers");
280 Value idxV = emitc::ConstantOp::create(
281 b, loc, emitc::OpaqueType::get(b.getContext(),
"int32_t"),
282 emitc::OpaqueAttr::get(b.getContext(), std::to_string(*argIdx)));
286 Value foldV = emitc::ConstantOp::create(
287 b, loc, emitc::OpaqueType::get(b.getContext(),
"bool"),
288 emitc::OpaqueAttr::get(b.getContext(),
289 foldDDRAddrOffset ?
"true" :
"false"));
290 Value argPlus = ap.getArgPlus();
293 if (argPlus.getType().isInteger(32))
294 argPlus = emitc::CastOp::create(b, loc, getU32Type(b.getContext()),
296 emitTxnCall(b, loc,
"txn_append_arg_patch", txnVec,
297 {addrV, idxV, argPlus, foldV});
298 countOp(b, loc, count);
300 .Case<AIEX::NpuBlockWriteOp>([&](
auto bw) {
301 convertBlockWrite(b, loc, bw);
302 countOp(b, loc, count);
304 .Case<AIEX::NpuBlockWriteValuesOp>([&](
auto bw) {
305 convertBlockWriteValues(b, loc, bw);
306 countOp(b, loc, count);
308 .Case<cf::AssertOp>([&](
auto a) {
312 emitc::VerbatimOp::create(
313 b, loc,
"if (!({})) " + refuse(a.getMsg(),
true),
314 ValueRange{a.getArg()});
316 .Case<AIEX::DMABdPoolPopOp>([&](AIEX::DMABdPoolPopOp pop) {
317 if (std::optional<uint32_t>
id = pop.getId()) {
318 emitc::VerbatimOp::create(b, loc,
319 "aie_runtime::bd_pool_reserve(" +
320 bdPoolName(pop) +
", " +
321 std::to_string(*
id) +
");");
322 pop.getBdId().replaceAllUsesWith(emitc::LiteralOp::create(
323 b, loc, pop.getBdId().getType(), std::to_string(*
id)));
330 std::string var =
"bd_" + std::to_string(nextPoolVar++);
331 emitc::VerbatimOp::create(
333 "uint32_t " + var +
"; if (!aie_runtime::bd_pool_pop(" +
334 bdPoolName(pop) +
", " + var +
")) " +
335 refuse(
"no free buffer descriptor on tile (" +
336 std::to_string(pop.getColumn()) +
", " +
337 std::to_string(pop.getRow()) +
338 "): the sequence keeps more transfers in flight "
339 "than the tile has descriptors",
342 emitc::LiteralOp::create(b, loc, pop.getBdId().getType(), var);
343 pop.getBdId().replaceAllUsesWith(ref);
345 .Case<AIEX::DMABdPoolPushOp>([&](AIEX::DMABdPoolPushOp push) {
347 emitc::CallOpaqueOp::create(
348 b, loc, TypeRange{},
"aie_runtime::bd_pool_push",
349 ValueRange{poolRef(b, loc, bdPoolName(push)), push.getBdId()});
353 .Case<AIEX::NpuCreateScratchpadOp, AIEX::NpuUpdateFromScratchpadOp>(
355 fail(sp,
"needs the scratchpad of a full-ELF context, which the "
356 "C++ TXN target's per-call streams run without; use a "
357 "runtime sequence argument instead of a scratchpad "
362 .Case<memref::GetGlobalOp>([&](
auto) {})
363 .Default([&](Operation *unsupported) {
364 if (isa<scf::SCFDialect>(unsupported->getDialect()))
366 "control flow in runtime sequences is not yet supported by "
367 "the C++ TXN target");
369 fail(unsupported,
"is not supported by the C++ TXN target");
377 Value resolvedAddr(OpBuilder &b, Location loc, Operation *clone) {
378 auto it = resolved.absoluteAddr.find(clone);
379 if (it == resolved.absoluteAddr.end())
381 return u32Literal(b, loc, it->second);
388 Value runtimeOrResolvedAddr(OpBuilder &b, Location loc, Operation *clone,
390 if (Value lit = resolvedAddr(b, loc, clone))
392 Operation *def = addrOperand ? addrOperand.getDefiningOp() :
nullptr;
393 if (def && !isa<arith::ConstantOp>(def))
399 void fail(Operation *op,
const llvm::Twine &msg) {
400 op->emitOpError(msg);
406 Value poolRef(OpBuilder &b, Location loc, StringRef name) {
407 return emitc::LiteralOp::create(
408 b, loc, emitc::OpaqueType::get(b.getContext(),
"aie_runtime::BdPool"),
412 void convertBlockWrite(OpBuilder &b, Location loc, AIEX::NpuBlockWriteOp bw) {
413 auto addrIt = resolved.absoluteAddr.find(bw);
414 auto dataIt = resolved.blockWriteData.find(bw);
415 if (addrIt == resolved.absoluteAddr.end() ||
416 dataIt == resolved.blockWriteData.end() || !dataIt->second) {
417 bw.emitOpError(
"cannot convert blockwrite without a constant address and "
418 "data to the C++ TXN target");
422 uint32_t addr = addrIt->second;
423 DenseIntElementsAttr data = dataIt->second;
427 MLIRContext *ctx = b.getContext();
428 int64_t n = data.size();
430 emitc::ArrayType::get(ctx, SmallVector<int64_t>{n}, getU32Type(ctx));
431 std::string init =
"{";
432 llvm::raw_string_ostream ss(init);
434 for (APInt word : data.getValues<APInt>()) {
437 ss << llvm::format(
"0x%08xu",
static_cast<unsigned>(word.getZExtValue()));
441 auto arrVar = emitc::VariableOp::create(b, loc, arrTy,
442 emitc::OpaqueAttr::get(ctx, init));
444 uint32_t colVal = 0, rowVal = 0;
445 if (
auto col = bw.getColumn(), row = bw.getRow(); col && row) {
449 emitTxnCall(b, loc,
"txn_append_blockwrite", txnVec,
450 {u32Literal(b, loc, addr), arrVar.getResult(),
451 u32Literal(b, loc,
static_cast<uint32_t
>(n)),
452 u32Literal(b, loc, colVal), u32Literal(b, loc, rowVal)});
460 void convertBlockWriteValues(OpBuilder &b, Location loc,
461 AIEX::NpuBlockWriteValuesOp bw) {
462 MLIRContext *ctx = b.getContext();
463 Value addrV = runtimeOrResolvedAddr(b, loc, bw, bw.getAddress());
465 fail(bw,
"cannot convert a symbolic/unresolved blockwrite_values address "
466 "to the C++ TXN target");
469 ValueRange words = bw.getValues();
470 int64_t n =
static_cast<int64_t
>(words.size());
475 emitc::ArrayType::get(ctx, SmallVector<int64_t>{n}, getU32Type(ctx));
476 auto arrVar = emitc::VariableOp::create(b, loc, arrTy,
477 emitc::OpaqueAttr::get(ctx,
"{}"));
483 for (int64_t i = 0; i < n; i++)
484 emitc::VerbatimOp::create(b, loc,
"{}[" + std::to_string(i) +
"] = {};",
485 ValueRange{arrVar.getResult(), words[i]});
488 emitTxnCall(b, loc,
"txn_append_blockwrite", txnVec,
489 {addrV, arrVar.getResult(),
490 u32Literal(b, loc,
static_cast<uint32_t
>(n)),
491 u32Literal(b, loc, 0), u32Literal(b, loc, 0)});
494 emitc::FuncOp funcOp;
496 const DeviceResolved &resolved;
502 unsigned nextPoolVar = 0;
503 bool foldDDRAddrOffset;
506struct ConvertAIEXToEmitCPass
507 : xilinx::impl::ConvertAIEXToEmitCBase<ConvertAIEXToEmitCPass> {
508 ConvertAIEXToEmitCPass() =
default;
511 explicit ConvertAIEXToEmitCPass(
const ConvertAIEXToEmitCOptions &options)
512 : ConvertAIEXToEmitCBase(options) {}
514 void runOnOperation()
override {
515 ModuleOp moduleOp = getOperation();
516 MLIRContext *ctx = &getContext();
518 return signalPassFailure();
521 AIE::RuntimeSequenceOp seq;
522 AIE::DeviceOp device;
524 SmallVector<SeqInfo> sequences;
525 moduleOp.walk([&](AIE::RuntimeSequenceOp seq) {
526 sequences.push_back({seq, seq->getParentOfType<AIE::DeviceOp>()});
528 if (emitDispatchShim && sequences.size() != 1) {
529 moduleOp.emitOpError()
530 <<
"emit-dispatch-shim needs exactly one aie.runtime_sequence to "
533 return signalPassFailure();
535 if (sequences.empty())
538 OpBuilder builder(ctx);
539 for (
auto &[seqOp, deviceOp] : sequences) {
541 seqOp.emitOpError(
"must be nested inside an aie.device");
542 return signalPassFailure();
544 std::optional<emitc::FuncOp> gen =
545 emitFunction(builder, moduleOp, seqOp, deviceOp);
547 return signalPassFailure();
548 if (emitDispatchShim) {
549 emitc::FuncOp generated = *gen;
550 if (failed(emitDispatchShimFuncs(builder, moduleOp, generated)))
551 return signalPassFailure();
556 SmallVector<Operation *> toErase;
557 for (Operation &op : *moduleOp.getBody())
558 if (!isa<emitc::FuncOp, emitc::IncludeOp>(op))
559 toErase.push_back(&op);
560 for (Operation *op : llvm::reverse(toErase))
566 if (failed(lowerArithAndScfToEmitC(moduleOp)))
567 return signalPassFailure();
569 builder.setInsertionPointToStart(moduleOp.getBody());
570 emitc::IncludeOp::create(builder, moduleOp.getLoc(),
571 "aie/Runtime/TxnEncoding.h",
573 emitc::IncludeOp::create(builder, moduleOp.getLoc(),
"cstdint",
575 emitc::IncludeOp::create(builder, moduleOp.getLoc(),
"vector",
579 emitc::IncludeOp::create(builder, moduleOp.getLoc(),
"optional",
586 LogicalResult lowerArithAndScfToEmitC(ModuleOp moduleOp) {
591 RewritePatternSet expand(moduleOp.getContext());
592 arith::populateCeilFloorDivExpandOpsPatterns(expand);
593 arith::populateExpandMinMaxIPatterns(expand);
596 GreedyRewriteConfig config;
597 config.enableFolding(
false).enableConstantCSE(
false);
598 if (failed(applyPatternsGreedily(moduleOp, std::move(expand), config)))
602 TypeConverter typeConverter;
603 typeConverter.addConversion([](Type t) {
return t; });
604 populateEmitCSizeTTypeConversions(typeConverter);
606 RewritePatternSet patterns(moduleOp.getContext());
607 populateArithToEmitCPatterns(typeConverter, patterns);
608 populateSCFToEmitCConversionPatterns(patterns, typeConverter);
610 ConversionTarget target(*moduleOp.getContext());
611 target.addLegalDialect<emitc::EmitCDialect>();
612 target.addIllegalDialect<arith::ArithDialect>();
613 target.addIllegalDialect<scf::SCFDialect>();
614 return applyPartialConversion(moduleOp, target, std::move(patterns));
621 static std::optional<std::string> cTypeName(Type t) {
622 if (isa<emitc::SizeTType>(t))
623 return std::string(
"size_t");
624 auto intTy = dyn_cast<IntegerType>(t);
625 if (!intTy || !emitc::isSupportedIntegerType(intTy))
627 if (intTy.getWidth() == 1)
628 return std::string(
"bool");
629 return (intTy.isUnsigned() ?
"uint" :
"int") +
630 std::to_string(intTy.getWidth()) +
"_t";
636 LogicalResult emitDispatchShimFuncs(OpBuilder &builder, ModuleOp moduleOp,
638 MLIRContext *ctx = moduleOp.getContext();
639 Location loc = gen.getLoc();
640 TypeRange genParams = gen.getFunctionType().getInputs();
642 SmallVector<std::string> abiTypes;
643 for (Type t : genParams) {
644 std::optional<std::string> name = cTypeName(t);
646 return gen.emitOpError()
647 <<
"runtime-sequence parameter type " << t
648 <<
" has no dispatch ABI spelling; it cannot be passed from the "
649 "host at dispatch time";
650 abiTypes.push_back(*name);
653 builder.setInsertionPointToEnd(moduleOp.getBody());
661 builder.getStrArrayAttr({
"extern \"C\"",
"AIE_DISPATCH_EXPORT"});
666 emitc::PointerType::get(emitc::OpaqueType::get(ctx,
"const char"));
667 auto abiFn = emitc::FuncOp::create(builder, loc,
"dispatch_abi",
668 FunctionType::get(ctx, {}, {charPtrTy}));
669 abiFn.setSpecifiersAttr(externC);
670 OpBuilder ab = OpBuilder::atBlockBegin(abiFn.addEntryBlock());
671 Value abiStr = emitc::LiteralOp::create(
672 ab, loc, charPtrTy,
"\"" + llvm::join(abiTypes,
",") +
"\"");
673 emitc::ReturnOp::create(ab, loc, abiStr);
675 SmallVector<Type> shimParams(genParams);
676 shimParams.push_back(
677 emitc::PointerType::get(emitc::PointerType::get(getU32Type(ctx))));
678 auto i64Ty = emitc::OpaqueType::get(ctx,
"int64_t");
680 emitc::FuncOp::create(builder, loc,
"dispatch_generate",
681 FunctionType::get(ctx, shimParams, {i64Ty}));
682 shimFn.setSpecifiersAttr(externC);
683 Block *shimBlock = shimFn.addEntryBlock();
684 OpBuilder sb = OpBuilder::atBlockBegin(shimBlock);
686 SmallVector<Value> genArgs(shimBlock->getArguments().drop_back());
687 SmallVector<StringRef> holes(genArgs.size(),
"{}");
688 std::string call =
"auto __result = " + gen.getSymName().str() +
"(" +
689 llvm::join(holes,
", ") +
");";
690 emitc::VerbatimOp::create(
691 sb, loc,
"static thread_local " + kTxnVecType.str() +
" __txn;");
692 emitc::VerbatimOp::create(sb, loc,
"aie_runtime::txn_refusal = nullptr;");
693 emitc::VerbatimOp::create(sb, loc, call, genArgs);
694 emitc::VerbatimOp::create(sb, loc,
"if (!__result) return -2;");
695 emitc::VerbatimOp::create(sb, loc,
"__txn = std::move(*__result);");
696 emitc::VerbatimOp::create(sb, loc,
"*{} = __txn.data();",
697 ValueRange{shimBlock->getArguments().back()});
698 emitc::ReturnOp::create(
700 emitc::LiteralOp::create(sb, loc, i64Ty,
701 "static_cast<int64_t>(__txn.size())"));
705 auto whyFn = emitc::FuncOp::create(builder, loc,
"dispatch_last_refusal",
706 FunctionType::get(ctx, {}, {charPtrTy}));
707 whyFn.setSpecifiersAttr(externC);
708 OpBuilder wb = OpBuilder::atBlockBegin(whyFn.addEntryBlock());
709 emitc::ReturnOp::create(
711 emitc::LiteralOp::create(wb, loc, charPtrTy,
712 "aie_runtime::txn_refusal"));
718 static void recordDeviceResolved(Operation *orig, Operation *clone,
719 DeviceResolved &resolved) {
720 if (
auto w = dyn_cast<AIEX::NpuWrite32Op>(orig)) {
721 if (
auto a = w.getAbsoluteAddress())
722 resolved.absoluteAddr[clone] = *a;
723 }
else if (
auto mw = dyn_cast<AIEX::NpuMaskWrite32Op>(orig)) {
724 if (
auto a = mw.getAbsoluteAddress())
725 resolved.absoluteAddr[clone] = *a;
726 }
else if (
auto mp = dyn_cast<AIEX::NpuMaskPollOp>(orig)) {
727 if (
auto a = mp.getAbsoluteAddress())
728 resolved.absoluteAddr[clone] = *a;
729 }
else if (
auto bw = dyn_cast<AIEX::NpuBlockWriteOp>(orig)) {
730 if (
auto a = bw.getAbsoluteAddress())
731 resolved.absoluteAddr[clone] = *a;
732 if (
auto d = bw.getDataWords())
733 resolved.blockWriteData[clone] = d;
734 }
else if (
auto bwv = dyn_cast<AIEX::NpuBlockWriteValuesOp>(orig)) {
737 resolved.absoluteAddr[clone] = *a;
741 FailureOr<emitc::FuncOp> emitFunction(OpBuilder &builder, ModuleOp moduleOp,
742 AIE::RuntimeSequenceOp seqOp,
743 AIE::DeviceOp deviceOp) {
744 Location loc = seqOp.getLoc();
745 Block &entry = seqOp.getBody().front();
750 SmallVector<Type> paramTypes;
752 emitc::OpaqueType::get(moduleOp.getContext(), kTxnVecType);
756 auto txnRetType = emitc::OpaqueType::get(
757 moduleOp.getContext(),
758 (llvm::Twine(
"std::optional<") + kTxnVecType +
">").str());
763 auto sizeT = emitc::SizeTType::get(moduleOp.getContext());
764 auto paramTypeFor = [&](Type t) -> Type {
765 return isa<IndexType>(t) ? Type(sizeT) : t;
767 for (BlockArgument arg : entry.getArguments())
768 if (!isa<BaseMemRefType>(arg.getType()))
769 paramTypes.push_back(paramTypeFor(arg.getType()));
771 builder.setInsertionPointToEnd(moduleOp.getBody());
772 std::string funcName =
"generate_txn_" + deviceOp.getSymName().str() +
"_" +
773 seqOp.getSymName().str();
774 auto funcOp = emitc::FuncOp::create(
775 builder, loc, funcName,
776 FunctionType::get(moduleOp.getContext(), paramTypes,
777 TypeRange{txnRetType}));
778 funcOp.setSpecifiersAttr(builder.getStrArrayAttr({
"inline"}));
779 Block *funcBlock = funcOp.addEntryBlock();
780 OpBuilder fb = OpBuilder::atBlockBegin(funcBlock);
786 emitc::VerbatimOp::create(fb, loc,
"std::vector<uint32_t> txn;");
787 Value txnVec = emitc::LiteralOp::create(fb, loc, txnVecType,
"txn");
788 emitTxnCall(fb, loc,
"txn_init", txnVec, {});
792 llvm::StringSet<> declaredPools;
793 auto declarePool = [&](
auto poolOp) {
794 std::string name = bdPoolName(poolOp);
795 if (!declaredPools.insert(name).second)
797 uint32_t lo = poolOp.getBdBegin(), hi = poolOp.getBdEnd();
798 emitc::VerbatimOp::create(fb, loc,
799 "aie_runtime::BdPool " + name +
800 " = aie_runtime::bd_pool_init_range(" +
801 std::to_string(lo) +
", " +
802 std::to_string(hi) +
");");
804 seqOp.walk([&](Operation *op) {
805 if (
auto pop = dyn_cast<AIEX::DMABdPoolPopOp>(op))
807 else if (
auto push = dyn_cast<AIEX::DMABdPoolPushOp>(op))
814 bool hasControlFlow =
false;
815 seqOp.walk([&](Operation *op) {
816 if (isa<scf::SCFDialect>(op->getDialect()))
817 hasControlFlow =
true;
820 if (hasControlFlow) {
821 emitc::VerbatimOp::create(fb, loc,
"uint32_t __opcount = 0;");
822 opCountVar = emitc::LiteralOp::create(
823 fb, loc, getU32Type(moduleOp.getContext()),
"__opcount");
832 for (BlockArgument arg : entry.getArguments())
833 if (!isa<BaseMemRefType>(arg.getType()))
834 mapping.map(arg, funcBlock->getArgument(p++));
835 DeviceResolved resolved;
836 for (Operation &op : entry.without_terminator()) {
837 fb.clone(op, mapping);
840 op.walk([&](Operation *orig) {
841 Operation *c = mapping.lookupOrNull(orig);
843 recordDeviceResolved(orig, c, resolved);
847 AIEXToEmitCConverter conv(funcOp, txnVec, resolved, opCountVar,
849 std::optional<uint32_t> count = conv.run();
856 const AIE::AIETargetModel &tm = deviceOp.getTargetModel();
857 OpBuilder eb(funcBlock, funcBlock->end());
858 std::string countStr =
859 hasControlFlow ?
"__opcount" : (std::to_string(*count) +
"u");
862 std::string header =
"aie_runtime::txn_prepend_header(txn, " + countStr +
863 ", aie_runtime::txn_device_info(" +
865 std::to_string(tm.
rows()) +
", " +
866 std::to_string(tm.
columns()) +
", " +
868 emitc::VerbatimOp::create(eb, loc, header);
873 Value ret = emitc::LiteralOp::create(eb, loc, txnRetType,
"std::move(txn)");
874 emitc::ReturnOp::create(eb, loc, ret);
881std::unique_ptr<OperationPass<ModuleOp>>
883 return std::make_unique<ConvertAIEXToEmitCPass>();
886std::unique_ptr<OperationPass<ModuleOp>>
888 bool emitDispatchShim) {
889 ConvertAIEXToEmitCOptions options;
890 options.foldDDRAddrOffset = foldDDRAddrOffset;
891 options.emitDispatchShim = emitDispatchShim;
892 return std::make_unique<ConvertAIEXToEmitCPass>(options);
virtual int rows() const =0
Return the number of rows in the device.
virtual int columns() const =0
Return the number of columns in the device.
virtual uint32_t getNumMemTileRows() const =0
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
uint8_t txnDeviceGen(const AIETargetModel &tm)
Device generation ID written into the TXN header (aie_runtime::TxnDeviceInfo::devGen).
mlir::LogicalResult inlineWriteConfigs(mlir::ModuleOp module)
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createConvertAIEXToEmitCPass()