MLIR-AIE 1.4.6.dev
AIECoreToStandard.cpp
Go to the documentation of this file.
1//===- AIECoreToStandard.cpp ------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2019-2022 Xilinx, Inc.
4// Copyright (C) 2022-2026 Advanced Micro Devices, Inc.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
13
14#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
15#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h"
16#include "mlir/Dialect/Arith/IR/Arith.h"
17#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h"
18#include "mlir/Dialect/DLTI/DLTI.h"
19#include "mlir/Dialect/Index/IR/IndexDialect.h"
20#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
21#include "mlir/Dialect/Math/IR/Math.h"
22#include "mlir/Dialect/Ptr/IR/PtrOps.h"
23#include "mlir/Dialect/UB/IR/UBOps.h"
24#include "mlir/Dialect/Vector/IR/VectorOps.h"
25#include "mlir/IR/Attributes.h"
26#include "mlir/IR/IRMapping.h"
27#include "mlir/IR/PatternMatch.h"
28#include "mlir/Pass/Pass.h"
29#include "mlir/Tools/mlir-translate/MlirTranslateMain.h"
30#include "mlir/Transforms/DialectConversion.h"
31
32namespace xilinx::AIE {
33#define GEN_PASS_DEF_AIECORETOSTANDARD
34#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
35} // namespace xilinx::AIE
36
37using namespace mlir;
38using namespace mlir::vector;
39using namespace xilinx;
40using namespace xilinx::AIE;
41
42static StringRef getArchTargetTriple(AIEArch arch) {
43 switch (arch) {
44 case AIEArch::AIE1:
45 return "aie";
46 case AIEArch::AIE2:
47 return "aie2";
48 case AIEArch::AIE2p:
49 return "aie2p";
50 case AIEArch::AIE2ps:
51 return "aie2ps";
52 case AIEArch::AIE4:
53 return "aie4";
54 }
55 llvm::report_fatal_error("unsupported arch");
56}
57
58// AIE2PS and AIE4 have no core intrinsic set (see declareAIEIntrinsics).
59static bool hasCoreIntrinsics(const AIETargetModel &targetModel) {
60 return !isa<AIE2PSTargetModel, AIE4TargetModel>(targetModel);
61}
62
63static LogicalResult checkCoreIntrinsics(Operation *op) {
64 const auto &targetModel = op->getParentOfType<DeviceOp>().getTargetModel();
65 if (hasCoreIntrinsics(targetModel))
66 return success();
67 return op->emitOpError("has no core lowering for ")
68 << stringifyAIEArch(targetModel.getTargetArch());
69}
70
72 std::tuple<const char *, std::vector<Type>, std::vector<Type>>;
73using IntrinsicDecls = std::vector<IntrinsicDecl>;
74
75static auto getAIE1Intrinsics(OpBuilder &builder) {
76 Type int32Type = IntegerType::get(builder.getContext(), 32);
77 Type int128Type = IntegerType::get(builder.getContext(), 128);
78 Type int384Type = IntegerType::get(builder.getContext(), 384);
79 Type floatType = Float32Type::get(builder.getContext());
80
81 // Note that not all of these are valid for a particular design, or needed.
82 // For right now, we will just accept the noise.
83 IntrinsicDecls functions = {
84 {"debug_i32", {int32Type}, {}},
85 {"llvm.aie.event0", {}, {}},
86 {"llvm.aie.event1", {}, {}},
87 {"llvm.aie.put.ms",
88 {int32Type, int32Type},
89 {}}, //(%channel, %value) -> ()
90 {"llvm.aie.put.wms",
91 {int32Type, int128Type},
92 {}}, //(%channel, %value) -> ()
93 {"llvm.aie.put.fms",
94 {int32Type, floatType},
95 {}}, //(%channel, %value) -> ()
96 {"llvm.aie.get.ss", {int32Type}, {int32Type}}, //(%channel, %value) -> ()
97 {"llvm.aie.get.wss",
98 {int32Type},
99 {int128Type}}, //(%channel, %value) -> ()
100 {"llvm.aie.get.fss", {int32Type}, {floatType}}, //(%channel, %value) -> ()
101 {"llvm.aie.put.mcd", {int384Type}, {}},
102 {"llvm.aie.get.scd", {}, {int384Type}},
103 {"llvm.aie.lock.acquire.reg",
104 {int32Type, int32Type},
105 {}}, //(%lock_id, %lock_val) -> ()
106 {"llvm.aie.lock.release.reg",
107 {int32Type, int32Type},
108 {}}, //(%lock_id, %lock_val) -> ()
109 };
110 return functions;
111}
112
113static auto getAIE2Intrinsics(OpBuilder &builder) {
114 Type int32Type = IntegerType::get(builder.getContext(), 32);
115 Type accType = VectorType::get({16}, int32Type);
116 IntrinsicDecls functions = {
117 {"debug_i32", {int32Type}, {}},
118 {"llvm.aie2.event", {int32Type}, {}},
119 {"llvm.aie2.put.ms", {int32Type, int32Type}, {}}, //(%value, %tlast) -> ()
120 {"llvm.aie2.get.ss", {}, {int32Type, int32Type}}, //() -> (%value, %tlast)
121 {"llvm.aie2.mcd.write.vec",
122 {accType, int32Type},
123 {}}, // (%value, %enable) -> ()
124 {"llvm.aie2.scd.read.vec",
125 {int32Type},
126 {accType}}, // (%enable) -> (%value)
127 {"llvm.aie2.acquire",
128 {int32Type, int32Type},
129 {}}, //(%lock_id, %lock_val) -> ()
130 {"llvm.aie2.release",
131 {int32Type, int32Type},
132 {}}, //(%lock_id, %lock_val) -> ()
133 {"llvm.aie2.set.ctrl.reg",
134 {int32Type, int32Type},
135 {}}, //(%reg_id, %value) -> ()
136 };
137 return functions;
138}
139
140static auto getAIE2pIntrinsics(OpBuilder &builder) {
141 Type int32Type = IntegerType::get(builder.getContext(), 32);
142 Type accType = VectorType::get({16}, int32Type);
143 IntrinsicDecls functions = {
144 {"debug_i32", {int32Type}, {}},
145 {"llvm.aie2p.event", {int32Type}, {}},
146 {"llvm.aie2p.put.ms",
147 {int32Type, int32Type},
148 {}}, //(%value, %tlast) -> ()
149 {"llvm.aie2p.get.ss",
150 {},
151 {int32Type, int32Type}}, //() -> (%value, %tlast)
152 {"llvm.aie2p.mcd.write.vec",
153 {accType, int32Type},
154 {}}, // (%value, %enable) -> ()
155 {"llvm.aie2p.scd.read.vec",
156 {int32Type},
157 {accType}}, // (%enable) -> (%value)
158 {"llvm.aie2p.acquire",
159 {int32Type, int32Type},
160 {}}, //(%lock_id, %lock_val) -> ()
161 {"llvm.aie2p.release",
162 {int32Type, int32Type},
163 {}}, //(%lock_id, %lock_val) -> ()
164 {"llvm.aie2p.set.ctrl.reg",
165 {int32Type, int32Type},
166 {}}, //(%reg_id, %value) -> ()
167 };
168 return functions;
169}
170
171static void declareAIEIntrinsics(AIEArch arch, OpBuilder &builder) {
172 auto registerIntrinsics = [&builder](const IntrinsicDecls &functions) {
173 for (auto &i : functions) {
174 auto [name, argTypes, retTypes] = i;
175 func::FuncOp::create(
176 builder, builder.getUnknownLoc(), name,
177 FunctionType::get(builder.getContext(), argTypes, retTypes))
178 .setPrivate();
179 }
180 };
181 switch (arch) {
182 case AIEArch::AIE1:
183 registerIntrinsics(getAIE1Intrinsics(builder));
184 return;
185 case AIEArch::AIE2:
186 registerIntrinsics(getAIE2Intrinsics(builder));
187 return;
188 case AIEArch::AIE2p:
189 registerIntrinsics(getAIE2pIntrinsics(builder));
190 return;
191 case AIEArch::AIE2ps:
192 case AIEArch::AIE4:
193 // No intrinsic set: checkCoreIntrinsics rejects ops that need one.
194 return;
195 }
196 llvm::report_fatal_error("unsupported arch");
197}
198
199// Move all the ops with OpTy inside device, to just before the device.
200template <typename OpTy>
201static void outlineOps(DeviceOp device) {
202 SmallVector<OpTy, 16> ops;
203 for (const auto &op : device.getOps<OpTy>())
204 ops.push_back(op);
205
206 for (const auto &op : ops)
207 op->moveBefore(device);
208}
209
210// The outlined core function must not use values of the device, which is
211// erased. Give the core its own copy of each outside constant it uses and
212// diagnose any other outside value.
213static LogicalResult sinkOutsideValuesIntoCore(CoreOp core) {
214 Region &body = core.getBody();
215 OpBuilder builder = OpBuilder::atBlockBegin(&body.front());
216 DenseMap<Value, Value> copies;
217 WalkResult result = body.walk([&](Operation *op) {
218 for (OpOperand &operand : op->getOpOperands()) {
219 Value value = operand.get();
220 if (body.isAncestor(value.getParentRegion()))
221 continue;
222 Operation *def = value.getDefiningOp();
223 if (!def || !def->hasTrait<OpTrait::ConstantLike>()) {
224 InFlightDiagnostic diag =
225 op->emitOpError("uses a value defined outside its aie.core, "
226 "which cannot be outlined");
227 diag.attachNote(value.getLoc()) << "value defined here";
228 return WalkResult::interrupt();
229 }
230 Value &copy = copies[value];
231 if (!copy) {
232 Operation *clone = builder.clone(*def);
233 builder.setInsertionPointAfter(clone);
234 copy = clone->getResult(cast<OpResult>(value).getResultNumber());
235 }
236 operand.set(copy);
237 }
238 return WalkResult::advance();
239 });
240 return failure(result.wasInterrupted());
241}
242
243namespace {
244template <typename MyAIEOp>
245struct AIEOpRemoval : OpConversionPattern<MyAIEOp> {
246 using OpConversionPattern<MyAIEOp>::OpConversionPattern;
247 using OpAdaptor = typename MyAIEOp::Adaptor;
248 ModuleOp &module;
249
250 AIEOpRemoval(MLIRContext *context, ModuleOp &m, PatternBenefit benefit = 1)
251 : OpConversionPattern<MyAIEOp>(context, benefit), module(m) {}
252
253 LogicalResult
254 matchAndRewrite(MyAIEOp op, OpAdaptor adaptor,
255 ConversionPatternRewriter &rewriter) const override {
256 rewriter.eraseOp(op);
257 return success();
258 }
259};
260
261struct AIEDebugOpToStdLowering : OpConversionPattern<DebugOp> {
262 using OpConversionPattern::OpConversionPattern;
263 ModuleOp &module;
264
265 AIEDebugOpToStdLowering(MLIRContext *context, ModuleOp &m,
266 PatternBenefit benefit = 1)
267 : OpConversionPattern(context, benefit), module(m) {}
268
269 LogicalResult
270 matchAndRewrite(DebugOp op, OpAdaptor adaptor,
271 ConversionPatternRewriter &rewriter) const override {
272 if (failed(checkCoreIntrinsics(op)))
273 return failure();
274 std::string funcName = "debug_i32";
275 auto func = module.lookupSymbol<func::FuncOp>(funcName);
276 if (!func)
277 return op.emitOpError("Could not find the intrinsic function ")
278 << funcName;
279 SmallVector<Value, 1> args;
280 args.push_back(op.getArg());
281 func::CallOp::create(rewriter, op.getLoc(), func, args);
282 rewriter.eraseOp(op);
283 return success();
284 }
285};
286
287struct AIEPutStreamToStdLowering : OpConversionPattern<PutStreamOp> {
288 using OpConversionPattern::OpConversionPattern;
289 ModuleOp &module;
290
291 AIEPutStreamToStdLowering(MLIRContext *context, ModuleOp &m,
292 PatternBenefit benefit = 1)
293 : OpConversionPattern(context, benefit), module(m) {}
294
295 LogicalResult
296 matchAndRewrite(PutStreamOp op, OpAdaptor adaptor,
297 ConversionPatternRewriter &rewriter) const override {
298 if (failed(checkCoreIntrinsics(op)))
299 return failure();
300 auto device = op->getParentOfType<DeviceOp>();
301 const auto &targetModel = device.getTargetModel();
302 std::string funcName;
303 if (targetModel.getTargetArch() == AIEArch::AIE1)
304 funcName = "llvm.aie.put.";
305 else if (targetModel.getTargetArch() == AIEArch::AIE2)
306 funcName = "llvm.aie2.put.";
307 else
308 funcName = "llvm.aie2p.put.";
309
310 if (op.isWideStream())
311 funcName += "wms";
312 else if (op.isFloatStream())
313 funcName += "fms";
314 else
315 funcName += "ms";
316
317 auto putMSFunc = module.lookupSymbol<func::FuncOp>(funcName);
318 if (!putMSFunc)
319 return op.emitOpError("Could not find the intrinsic function ")
320 << funcName;
321 SmallVector<Value, 2> args;
322 if (targetModel.getTargetArch() == AIEArch::AIE1) {
323 args.push_back(op.getChannel());
324 args.push_back(op.getStreamValue());
325 } else {
326 args.push_back(op.getStreamValue());
327 args.push_back(arith::ConstantOp::create(
328 rewriter, op.getLoc(), IntegerType::get(rewriter.getContext(), 32),
329 rewriter.getI32IntegerAttr(0))); // tlast
330 }
331 func::CallOp::create(rewriter, op.getLoc(), putMSFunc, args);
332 rewriter.eraseOp(op);
333 return success();
334 }
335};
336
337struct AIEGetStreamToStdLowering : OpConversionPattern<GetStreamOp> {
338 using OpConversionPattern::OpConversionPattern;
339 ModuleOp &module;
340
341 AIEGetStreamToStdLowering(MLIRContext *context, ModuleOp &m,
342 PatternBenefit benefit = 1)
343 : OpConversionPattern(context, benefit), module(m) {}
344
345 LogicalResult
346 matchAndRewrite(GetStreamOp op, OpAdaptor adaptor,
347 ConversionPatternRewriter &rewriter) const override {
348 if (failed(checkCoreIntrinsics(op)))
349 return failure();
350 auto device = op->getParentOfType<DeviceOp>();
351 const auto &targetModel = device.getTargetModel();
352 std::string funcName;
353 if (targetModel.getTargetArch() == AIEArch::AIE1)
354 funcName = "llvm.aie.get.";
355 else if (targetModel.getTargetArch() == AIEArch::AIE2)
356 funcName = "llvm.aie2.get.";
357 else
358 funcName = "llvm.aie2p.get.";
359
360 if (op.isWideStream())
361 funcName += "wss";
362 else if (op.isFloatStream())
363 funcName += "fss";
364 else
365 funcName += "ss";
366
367 auto getSSFunc = module.lookupSymbol<func::FuncOp>(funcName);
368 if (!getSSFunc)
369 return op.emitOpError("Could not find the intrinsic function ")
370 << funcName;
371 SmallVector<Value, 2> args;
372 if (targetModel.getTargetArch() == AIEArch::AIE1)
373 args.push_back(op.getChannel());
374 auto getSSCall =
375 func::CallOp::create(rewriter, op.getLoc(), getSSFunc, args);
376 rewriter.replaceOp(op, getSSCall.getResult(0));
377 // Capture TLAST in AIEv2?
378 return success();
379 }
380};
381
382struct AIEPutCascadeToStdLowering : OpConversionPattern<PutCascadeOp> {
383 using OpConversionPattern::OpConversionPattern;
384 ModuleOp &module;
385
386 AIEPutCascadeToStdLowering(MLIRContext *context, ModuleOp &m,
387 PatternBenefit benefit = 1)
388 : OpConversionPattern(context, benefit), module(m) {}
389
390 LogicalResult
391 matchAndRewrite(PutCascadeOp op, OpAdaptor adaptor,
392 ConversionPatternRewriter &rewriter) const override {
393 if (failed(checkCoreIntrinsics(op)))
394 return failure();
395 auto device = op->getParentOfType<DeviceOp>();
396 const auto &targetModel = device.getTargetModel();
397 std::string funcName;
398 if (targetModel.getTargetArch() == AIEArch::AIE1)
399 funcName = "llvm.aie.put.mcd";
400 else if (targetModel.getTargetArch() == AIEArch::AIE2)
401 funcName = "llvm.aie2.mcd.write.vec";
402 else
403 funcName = "llvm.aie2p.mcd.write.vec";
404 auto putMCDFunc = module.lookupSymbol<func::FuncOp>(funcName);
405 if (!putMCDFunc)
406 return op.emitOpError("Could not find the intrinsic function ")
407 << funcName;
408 SmallVector<Value, 2> args;
409 Value cascadeValue = op.getCascadeValue();
410
411 // Check if we need a bitcast for the input value
412 Type expectedInputType = putMCDFunc.getFunctionType().getInput(0);
413 Type actualInputType = cascadeValue.getType();
414
415 if (expectedInputType != actualInputType) {
416 // Create a bitcast operation to convert from actual input type to
417 // expected type
418 cascadeValue = vector::BitCastOp::create(rewriter, op.getLoc(),
419 expectedInputType, cascadeValue);
420 }
421
422 args.push_back(cascadeValue);
423 if (isa<AIE2TargetModel>(targetModel))
424 args.push_back(arith::ConstantOp::create(
425 rewriter, op.getLoc(), IntegerType::get(rewriter.getContext(), 32),
426 rewriter.getI32IntegerAttr(1))); // enable
427
428 func::CallOp::create(rewriter, op.getLoc(), putMCDFunc, args);
429 rewriter.eraseOp(op);
430 return success();
431 }
432};
433
434struct AIEGetCascadeToStdLowering : OpConversionPattern<GetCascadeOp> {
435 using OpConversionPattern::OpConversionPattern;
436 ModuleOp &module;
437
438 AIEGetCascadeToStdLowering(MLIRContext *context, ModuleOp &m,
439 PatternBenefit benefit = 1)
440 : OpConversionPattern(context, benefit), module(m) {}
441
442 LogicalResult
443 matchAndRewrite(GetCascadeOp op, OpAdaptor adaptor,
444 ConversionPatternRewriter &rewriter) const override {
445 if (failed(checkCoreIntrinsics(op)))
446 return failure();
447 auto device = op->getParentOfType<DeviceOp>();
448 const auto &targetModel = device.getTargetModel();
449 std::string funcName;
450 if (targetModel.getTargetArch() == AIEArch::AIE1)
451 funcName = "llvm.aie.get.scd";
452 else if (targetModel.getTargetArch() == AIEArch::AIE2)
453 funcName = "llvm.aie2.scd.read.vec";
454 else
455 funcName = "llvm.aie2p.scd.read.vec";
456 auto getSCDFunc = module.lookupSymbol<func::FuncOp>(funcName);
457 if (!getSCDFunc)
458 return op.emitOpError("Could not find the intrinsic function ")
459 << funcName;
460 SmallVector<Value, 2> args;
461 if (isa<AIE2TargetModel>(targetModel))
462 args.push_back(arith::ConstantOp::create(
463 rewriter, op.getLoc(), IntegerType::get(rewriter.getContext(), 32),
464 rewriter.getI32IntegerAttr(1))); // enable
465
466 auto getSCDCall =
467 func::CallOp::create(rewriter, op.getLoc(), getSCDFunc, args);
468 Value result = getSCDCall.getResult(0);
469
470 // Check if we need a bitcast
471 Type expectedType = op.getResult().getType();
472 Type intrinsicReturnType = result.getType();
473
474 if (expectedType != intrinsicReturnType) {
475 // Create a bitcast operation to convert from intrinsic return type to
476 // expected type
477 result = vector::BitCastOp::create(rewriter, op.getLoc(), expectedType,
478 result);
479 }
480
481 rewriter.replaceOp(op, result);
482 return success();
483 }
484};
485
486struct AIEUseLockToStdLowering : OpConversionPattern<UseLockOp> {
487 using OpConversionPattern::OpConversionPattern;
488 ModuleOp &module;
489
490 AIEUseLockToStdLowering(MLIRContext *context, ModuleOp &m,
491 PatternBenefit benefit = 1)
492 : OpConversionPattern(context, benefit), module(m) {}
493 LogicalResult
494 matchAndRewrite(UseLockOp useLock, OpAdaptor adaptor,
495 ConversionPatternRewriter &rewriter) const override {
496 if (!isa<DeviceOp>(useLock->getParentOp())) {
497 auto device = useLock->getParentOfType<DeviceOp>();
498 if (!device) {
499 return module.emitOpError("Device Not found!");
500 }
501 const auto &targetModel = device.getTargetModel();
502 // A lock in a core or in any function needs an intrinsic, whether or
503 // not an exported core calls the function. Any other lock (DMA
504 // regions, runtime sequences) is erased with its parent.
505 if (!hasCoreIntrinsics(targetModel)) {
506 if (useLock->getParentOfType<CoreOp>() ||
507 useLock->getParentOfType<func::FuncOp>())
508 return checkCoreIntrinsics(useLock);
509 rewriter.eraseOp(useLock);
510 return success();
511 }
512
513 // Generate the intrinsic name
514 std::string funcName;
515 if (targetModel.getTargetArch() == AIEArch::AIE1)
516 funcName = "llvm.aie.lock.";
517 else if (targetModel.getTargetArch() == AIEArch::AIE2)
518 funcName = "llvm.aie2.";
519 else
520 funcName = "llvm.aie2p.";
521 if (useLock.acquire() || useLock.acquireGE())
522 funcName += "acquire";
523 else if (useLock.release())
524 funcName += "release";
525 if (targetModel.getTargetArch() == AIEArch::AIE1)
526 funcName += ".reg";
527
528 auto useLockFunc = module.lookupSymbol<func::FuncOp>(funcName);
529 if (!useLockFunc)
530 return useLock.emitOpError("Could not find the intrinsic function!");
531
532 SmallVector<Value, 2> args;
533 auto i32Ty = IntegerType::get(rewriter.getContext(), 32);
534 args.push_back(arith::IndexCastOp::create(rewriter, useLock.getLoc(),
535 i32Ty, useLock.getLock()));
536
537 Value value = adaptor.getValue();
538 // AIE2 acquire-greater-equal is encoded as a negative value, so negate
539 // it at runtime.
540 if (useLock.acquireGE()) {
541 Value zero = arith::ConstantOp::create(
542 rewriter, useLock.getLoc(), i32Ty, rewriter.getI32IntegerAttr(0));
543 value = arith::SubIOp::create(rewriter, useLock.getLoc(), zero, value);
544 }
545 args.push_back(value);
546
547 func::CallOp::create(rewriter, useLock.getLoc(), useLockFunc, args);
548 }
549 rewriter.eraseOp(useLock);
550 return success();
551 }
552};
553
554struct AIEBufferToStandard : OpConversionPattern<BufferOp> {
555 using OpConversionPattern::OpConversionPattern;
556 ModuleOp &module;
557 AIEBufferToStandard(MLIRContext *context, ModuleOp &m,
558 PatternBenefit benefit = 1)
559 : OpConversionPattern(context, benefit), module(m) {}
560 LogicalResult
561 matchAndRewrite(BufferOp buffer, OpAdaptor adaptor,
562 ConversionPatternRewriter &rewriter) const override {
563 // The core's own sections fill this extent; nothing refers to it by name.
564 if (buffer.getCoreData()) {
565 rewriter.eraseOp(buffer);
566 return success();
567 }
568 rewriter.setInsertionPointToStart(module.getBody());
569 auto t = llvm::cast<MemRefType>(buffer.getType());
570 auto symName = buffer.name().getValue();
571 // A declaration, never a definition: a buffer lives at the address the
572 // allocator chose, and the linker supplies that address from the generated
573 // script or BCF. `initial_value` is device state, written by whoever
574 // configures the device -- the CDO writer, or mlir_aie_initialize_buffers
575 // on the simulator path. A definition here would place the bytes wherever
576 // `*(.data*)` lands, which costs the core's data region a copy it never
577 // reads.
578 memref::GlobalOp::create(rewriter, buffer.getLoc(), symName,
579 rewriter.getStringAttr("public"), buffer.getType(),
580 /*initial_value=*/nullptr, /*constant*/ false,
581 /*alignment*/ nullptr);
582
583 for (auto &use : make_early_inc_range(buffer.getResult().getUses())) {
584 Operation *user = use.getOwner();
585 rewriter.setInsertionPoint(user);
586 auto allocated =
587 memref::GetGlobalOp::create(rewriter, buffer.getLoc(), t, symName);
588 // Assume that buffers are aligned so they can be vectorized.
589 memref::AssumeAlignmentOp::create(rewriter, buffer.getLoc(), allocated,
590 32);
591
592 use.set(allocated.getResult());
593 }
594
595 rewriter.eraseOp(buffer);
596 return success();
597 }
598};
599
600struct AIECoreToStandardFunc : OpConversionPattern<CoreOp> {
601 using OpConversionPattern::OpConversionPattern;
602 ModuleOp &module;
603 IRMapping &mapper;
604 DenseMap<Operation *, SmallVector<BufferOp, 4>> &tileToBuffers;
605 int tileCol = 0;
606 int tileRow = 0;
607
608 AIECoreToStandardFunc(
609 MLIRContext *context, ModuleOp &m, IRMapping &mapper,
610 DenseMap<Operation *, SmallVector<BufferOp, 4>> &tileToBuffers,
611 PatternBenefit benefit = 1, int tileCol = 1, int tileRow = 1)
612 : OpConversionPattern(context, benefit), module(m), mapper(mapper),
613 tileToBuffers(tileToBuffers), tileCol(tileCol), tileRow(tileRow) {}
614
615 LogicalResult
616 matchAndRewrite(CoreOp op, OpAdaptor adaptor,
617 ConversionPatternRewriter &rewriter) const override {
618
619 int col = op.colIndex();
620 int row = op.rowIndex();
621
622 // Only pull code for the indicated function
623 if ((tileRow != row && tileRow != -1) ||
624 (tileCol != col && tileCol != -1)) {
625 rewriter.eraseOp(op);
626 return success();
627 }
628
629 // The parent should be an AIE.device op.
630 rewriter.setInsertionPointAfter(op->getParentOp());
631
632 std::string coreName = coreFrameSymbolName(col, row);
633 auto coreFunc =
634 func::FuncOp::create(rewriter, op.getLoc(), coreName,
635 FunctionType::get(rewriter.getContext(), {}, {}));
636
637 rewriter.cloneRegionBefore(op.getBody(), coreFunc.getBody(),
638 coreFunc.getBody().begin(), mapper);
639
640 // Set saturation and rounding modes at core entry for AIE2/AIE2p, but
641 // only if the core body contains aievec.srs or bf16 aievec.matmul ops.
642 // Skip for cores with only lock/stream ops to avoid breaking existing
643 // test SSA naming.
644 bool hasSRS = false;
645 bool hasIntegerSRS = false;
646 bool hasBF16Matmul = false;
647 auto scan = [&](Operation *childOp) {
648 StringRef opName = childOp->getName().getStringRef();
649 if (opName == "aievec.srs") {
650 hasSRS = true;
651 // Check if this is an integer SRS (e.g., i32→i8) vs float SRS
652 // (e.g., f32→bf16). Integer SRS needs positive_inf rounding to
653 // match C++ kernel behavior; float SRS works better with floor.
654 if (childOp->getNumResults() > 0) {
655 auto resultType = childOp->getResult(0).getType();
656 if (auto vecType = dyn_cast<VectorType>(resultType)) {
657 if (vecType.getElementType().isInteger())
658 hasIntegerSRS = true;
659 }
660 }
661 }
662 // Detect bf16 matmul ops — these need conv_even rounding to avoid
663 // systematic negative bias from floor rounding in BFP16 arithmetic.
664 // On AIE2P a bf16 matmul is a bfp16 one: aievec.to_bfp16 converts its
665 // bf16 operands, and aievec.matmul_aie2p_bfp16 may take them loaded.
666 if (opName == "aievec.to_bfp16" || opName == "aievec.matmul_aie2p_bfp16")
667 hasBF16Matmul = true;
668 if (opName == "aievec.matmul" || opName == "aievec.matmul_aie2p") {
669 if (childOp->getNumOperands() > 0) {
670 auto lhsType = childOp->getOperand(0).getType();
671 if (auto vecType = dyn_cast<VectorType>(lhsType))
672 if (vecType.getElementType().isBF16())
673 hasBF16Matmul = true;
674 }
675 }
676 };
677 coreFunc.walk(scan);
678 auto device = op->getParentOfType<DeviceOp>();
679 // These targets cannot set the modes at all, so check callees too.
680 if (device && !hasCoreIntrinsics(device.getTargetModel())) {
681 SmallVector<func::FuncOp> worklist;
682 DenseSet<Operation *> visited;
683 auto addCallees = [&](Operation *root) {
684 root->walk([&](func::CallOp call) {
685 auto callee = SymbolTable::lookupNearestSymbolFrom<func::FuncOp>(
686 device, call.getCalleeAttr());
687 if (callee && visited.insert(callee).second)
688 worklist.push_back(callee);
689 });
690 };
691 addCallees(coreFunc);
692 while (!worklist.empty()) {
693 func::FuncOp callee = worklist.pop_back_val();
694 callee.walk(scan);
695 addCallees(callee);
696 }
697 }
698 if (hasSRS || hasBF16Matmul) {
699 if (device) {
700 if (!hasCoreIntrinsics(device.getTargetModel()))
701 return op.emitOpError("needs the rounding and saturation modes set "
702 "for aievec.srs or bf16 matmul, which has no "
703 "lowering for ")
704 << stringifyAIEArch(device.getTargetModel().getTargetArch());
705 AIEArch arch = device.getTargetModel().getTargetArch();
706 if (arch == AIEArch::AIE2 || arch == AIEArch::AIE2p) {
707 std::string ctrlRegFuncName = (arch == AIEArch::AIE2p)
708 ? "llvm.aie2p.set.ctrl.reg"
709 : "llvm.aie2.set.ctrl.reg";
710 auto ctrlRegFunc = module.lookupSymbol<func::FuncOp>(ctrlRegFuncName);
711 if (ctrlRegFunc) {
712 Block &entryBlock = coreFunc.getBody().front();
713 rewriter.setInsertionPointToStart(&entryBlock);
714 Location loc = op.getLoc();
715 // Rounding register index differs between AIE2 and AIE2P:
716 // AIE2: crRnd=6
717 // AIE2P: crRnd=1
718 // Saturation register uses AIE2 index (9) for both architectures.
719 // On AIE2P, index 9 maps to crPackSize (no-op for saturation),
720 // preserving the pre-existing behavior. The AIE2P crSat fix
721 // (index 0) requires updating downstream tests and is tracked
722 // separately.
723 int satRegIdx = 9;
724 int rndRegIdx = (arch == AIEArch::AIE2p) ? 1 : 6;
725 // saturation_mode::saturate = 1
726 auto cSatIdx = arith::ConstantOp::create(
727 rewriter, loc, rewriter.getI32IntegerAttr(satRegIdx));
728 auto c1 = arith::ConstantOp::create(rewriter, loc,
729 rewriter.getI32IntegerAttr(1));
730 func::CallOp::create(rewriter, loc, ctrlRegFunc,
731 ValueRange{cSatIdx, c1});
732 // Rounding mode:
733 // - conv_even (12) for bf16 matmul: eliminates systematic
734 // negative bias from floor rounding in BFP16 arithmetic,
735 // matching ::aie::set_rounding(aie::rounding_mode::conv_even)
736 // used in external C++ matmul kernels.
737 // - positive_inf (9) for integer SRS (shift-round-saturate on
738 // integer data, e.g., i32→i8), unless the core has a bf16
739 // matmul.
740 // - conv_even (12) for float-only SRS (f32→bf16), matching the
741 // round-to-nearest-even semantics of arith.truncf.
742 int roundingMode = hasIntegerSRS && !hasBF16Matmul ? 9 : 12;
743 auto cRndIdx = arith::ConstantOp::create(
744 rewriter, loc, rewriter.getI32IntegerAttr(rndRegIdx));
745 auto cRoundingMode = arith::ConstantOp::create(
746 rewriter, loc, rewriter.getI32IntegerAttr(roundingMode));
747 func::CallOp::create(rewriter, loc, ctrlRegFunc,
748 ValueRange{cRndIdx, cRoundingMode});
749 }
750 }
751 }
752 }
753
754 // Rewrite the AIE.end() op
755 coreFunc.getBody().walk([&](Operation *childOp) {
756 rewriter.setInsertionPointAfter(childOp);
757
758 if (isa<EndOp>(childOp)) {
759 func::ReturnOp::create(rewriter, childOp->getLoc(), ValueRange({}));
760 rewriter.eraseOp(childOp);
761 }
762 });
763
764 rewriter.eraseOp(op);
765 return success();
766 }
767};
768
769// Lower AIE.event to llvm.aie.event intrinsic
770struct AIEEventOpToStdLowering : OpConversionPattern<EventOp> {
771 using OpConversionPattern::OpConversionPattern;
772 ModuleOp &module;
773
774 AIEEventOpToStdLowering(MLIRContext *context, ModuleOp &m,
775 PatternBenefit benefit = 1)
776 : OpConversionPattern(context, benefit), module(m) {}
777
778 LogicalResult
779 matchAndRewrite(EventOp op, OpAdaptor adaptor,
780 ConversionPatternRewriter &rewriter) const override {
781 auto device = op->getParentOfType<DeviceOp>();
782 std::string funcName;
783 SmallVector<Value, 1> args;
784 switch (device.getTargetModel().getTargetArch()) {
785 case AIEArch::AIE1:
786 funcName = "llvm.aie.event" + std::to_string(op.getVal());
787 break;
788 case AIEArch::AIE2:
789 funcName = "llvm.aie2.event";
790 args.push_back(arith::ConstantOp::create(
791 rewriter, op.getLoc(), rewriter.getI32Type(),
792 rewriter.getI32IntegerAttr(op.getVal())));
793 break;
794 case AIEArch::AIE2p:
795 funcName = "llvm.aie2p.event";
796 args.push_back(arith::ConstantOp::create(
797 rewriter, op.getLoc(), rewriter.getI32Type(),
798 rewriter.getI32IntegerAttr(op.getVal())));
799 break;
800 case AIEArch::AIE2ps:
801 case AIEArch::AIE4:
802 return op.emitOpError("has no core lowering for ")
803 << stringifyAIEArch(device.getTargetModel().getTargetArch());
804 }
805 auto eventFunc = module.lookupSymbol<func::FuncOp>(funcName);
806 if (!eventFunc)
807 return op.emitOpError("Could not find the intrinsic function ")
808 << funcName;
809 func::CallOp::create(rewriter, op.getLoc(), eventFunc, args);
810 rewriter.eraseOp(op);
811 return success();
812 }
813};
814
815struct AIECoreToStandardPass
816 : xilinx::AIE::impl::AIECoreToStandardBase<AIECoreToStandardPass> {
817 AIECoreToStandardPass() = default;
818 AIECoreToStandardPass(const AIECoreToStandardOptions &options) {
819 deviceName = options.deviceName;
820 tileCol = options.tileCol;
821 tileRow = options.tileRow;
822 }
823
824 void runOnOperation() override {
825
826 ModuleOp m = getOperation();
827 OpBuilder builder = OpBuilder::atBlockEnd(m.getBody());
828
829 DeviceOp deviceOp = DeviceOp::getForSymbolInModuleOrError(m, deviceName);
830 if (!deviceOp) {
831 return signalPassFailure();
832 }
833 const auto &targetModel = deviceOp.getTargetModel();
834
835 // Copy data layout attribute from DeviceOp to ModuleOp if present
836 if (auto dlAttr = deviceOp->getAttr(DLTIDialect::kDataLayoutAttrName)) {
837 m->setAttr(DLTIDialect::kDataLayoutAttrName, dlAttr);
838 }
839
840 // Ensure that we don't have an incorrect target triple. This may override
841 // some bogus target triple in the original mlir.
842 m->setAttr(LLVM::LLVMDialect::getTargetTripleAttrName(),
843 builder.getStringAttr(
844 getArchTargetTriple(targetModel.getTargetArch())));
845
846 DenseMap<Operation *, SmallVector<BufferOp, 4>> tileToBuffers;
847
848 // Populate intrinsic functions
849 // Intrinsic information:
850 // peano/llvm-project/llvm/lib/Target/AIE/AIEInstrInfo.td Also take a look
851 // at the tests: peano/llvm-project/llvm/test/CodeGen/AIE
852 builder.setInsertionPointToStart(m.getBody());
853 declareAIEIntrinsics(targetModel.getTargetArch(), builder);
854
855 IRMapping mapper;
856 ConversionTarget target(getContext());
857 target.addLegalDialect<func::FuncDialect>();
858 target.addLegalDialect<cf::ControlFlowDialect>();
859 target.addLegalDialect<memref::MemRefDialect>();
860 target.addLegalDialect<VectorDialect>();
861 target.addLegalDialect<aievec::AIEVecDialect>();
862 target.addLegalDialect<arith::ArithDialect>();
863 target.addLegalDialect<ub::UBDialect>();
864 target.addLegalDialect<math::MathDialect>();
865 target.addLegalDialect<index::IndexDialect>();
866 target.addLegalDialect<ptr::PtrDialect>();
867 // A core body may already hold LLVM ops: aie.dma_push_queue lowers to the
868 // stores that push a task before the body is outlined.
869 target.addLegalDialect<LLVM::LLVMDialect>();
870 target.addLegalOp<func::FuncOp, ModuleOp, UnrealizedConversionCastOp>();
871 // Ops this pass lowers must be illegal: a failed rewrite of an op with
872 // unknown legality is silently left in place.
873 // A core that is not exported is erased, so its ops are left alone.
874 target.addIllegalOp<BufferOp>();
875 target.addDynamicallyLegalOp<PutStreamOp, GetStreamOp, PutCascadeOp,
876 GetCascadeOp, DebugOp, UseLockOp, EventOp>(
877 [col = static_cast<int>(tileCol),
878 row = static_cast<int>(tileRow)](Operation *op) {
879 auto core = op->getParentOfType<CoreOp>();
880 return core && ((row != core.rowIndex() && row != -1) ||
881 (col != core.colIndex() && col != -1));
882 });
883
884 RewritePatternSet patterns(&getContext());
885 patterns.add<AIEPutStreamToStdLowering, AIEGetStreamToStdLowering,
886 AIEPutCascadeToStdLowering, AIEGetCascadeToStdLowering,
887 AIEDebugOpToStdLowering, AIEUseLockToStdLowering,
888 AIEEventOpToStdLowering>(m.getContext(), m);
889
890 patterns.add<AIEBufferToStandard>(m.getContext(), m, /*benefit*/ 1);
891 if (failed(applyPartialConversion(deviceOp, target, std::move(patterns))))
892 return signalPassFailure();
893
894 // Unselected cores are erased, not outlined.
895 int col = static_cast<int>(tileCol);
896 int row = static_cast<int>(tileRow);
897 for (CoreOp core : deviceOp.getOps<CoreOp>()) {
898 if ((row != core.rowIndex() && row != -1) ||
899 (col != core.colIndex() && col != -1))
900 continue;
901 if (failed(sinkOutsideValuesIntoCore(core)))
902 return signalPassFailure();
903 }
904
905 RewritePatternSet outlinePatterns(&getContext());
906 outlinePatterns.add<AIECoreToStandardFunc>(m.getContext(), m, mapper,
907 tileToBuffers, /*benefit*/ 1,
908 tileCol, tileRow);
909 // Otherwise a core whose outlined body does not legalize is dropped.
910 target.addIllegalOp<CoreOp>();
911 if (failed(applyPartialConversion(deviceOp, target,
912 std::move(outlinePatterns))))
913 return signalPassFailure();
914
915 // Move all the func.func ops and memref.globals from the device to the
916 // module
917 outlineOps<memref::GlobalOp>(deviceOp);
918 outlineOps<func::FuncOp>(deviceOp);
919
920 RewritePatternSet removepatterns(&getContext());
921 removepatterns.add<
922 AIEOpRemoval<DeviceOp>, AIEOpRemoval<TileOp>, AIEOpRemoval<FlowOp>,
923 AIEOpRemoval<MemOp>, AIEOpRemoval<ShimDMAOp>, AIEOpRemoval<ShimMuxOp>,
924 AIEOpRemoval<SwitchboxOp>, AIEOpRemoval<LockOp>, AIEOpRemoval<BufferOp>,
925 AIEOpRemoval<ExternalBufferOp>, AIEOpRemoval<ShimDMAAllocationOp>,
926 AIEOpRemoval<CascadeFlowOp>, AIEOpRemoval<ConfigureCascadeOp>>(
927 m.getContext(), m);
928
929 if (failed(applyPartialConversion(m, target, std::move(removepatterns))))
930 return signalPassFailure();
931 }
932};
933} // namespace
934
935std::unique_ptr<OperationPass<ModuleOp>> AIE::createAIECoreToStandardPass() {
936 return std::make_unique<AIECoreToStandardPass>();
937}
938
939std::unique_ptr<OperationPass<ModuleOp>>
940AIE::createAIECoreToStandardPass(const AIECoreToStandardOptions &options) {
941 return std::make_unique<AIECoreToStandardPass>(options);
942}
std::tuple< const char *, std::vector< Type >, std::vector< Type > > IntrinsicDecl
std::vector< IntrinsicDecl > IntrinsicDecls
std::string coreFrameSymbolName(int col, int row)
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createAIECoreToStandardPass()
const AIETargetModel & getTargetModel(mlir::Operation *op)
AIEOpRemoval(MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(MyOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override