[Mlir-commits] [mlir] [mlir][EmitC]Expand the MemRefToEmitC pass - Lowering `AllocOp` (PR #148257)

Gil Rapaport llvmlistbot at llvm.org
Fri Jul 25 08:37:02 PDT 2025


================
@@ -77,6 +81,75 @@ struct ConvertAlloca final : public OpConversionPattern<memref::AllocaOp> {
   }
 };
 
+struct ConvertAlloc final : public OpConversionPattern<memref::AllocOp> {
+  using OpConversionPattern::OpConversionPattern;
+  LogicalResult
+  matchAndRewrite(memref::AllocOp allocOp, OpAdaptor operands,
+                  ConversionPatternRewriter &rewriter) const override {
+    mlir::Location loc = allocOp.getLoc();
+    MemRefType memrefType = allocOp.getType();
+    if (!memrefType.hasStaticShape()) {
+      // TODO: Handle Dynamic shapes in the future. If the size
+      // of the allocation is the result of some function, we could
+      // potentially evaluate the function and use the result in the call to
+      // allocate.
+      return rewriter.notifyMatchFailure(
+          loc, "cannot transform alloc with dynamic shape");
+    }
+
+    mlir::Type sizeTType = mlir::emitc::SizeTType::get(rewriter.getContext());
+    Type elementType = memrefType.getElementType();
+    mlir::emitc::CallOpaqueOp sizeofElementOp =
+        rewriter.create<mlir::emitc::CallOpaqueOp>(
+            loc, sizeTType, rewriter.getStringAttr("sizeof"),
+            mlir::ValueRange{},
+            mlir::ArrayAttr::get(rewriter.getContext(),
+                                 {mlir::TypeAttr::get(elementType)}));
+    mlir::Value sizeofElement = sizeofElementOp.getResult(0);
+
+    long val = memrefType.getShape().front();
----------------
aniragil wrote:

This only works for 1D memrefs (please also give `val` a more meaningful name).
Relying on the shape for allocation is only correct for identity-stride memrefs. The `MemrefToLLVM` pass enforces this constraint when lowering `AllocOp`, so we should probably do the same.

https://github.com/llvm/llvm-project/pull/148257


More information about the Mlir-commits mailing list