Skip to content

[mlir][bufferization] Handle custom tensor memory space at function boundaries - #248055

Merged
aidint merged 2 commits into
llvm:mainfrom
aidint:aidint/function-boundary-memory-space-for-custom-tensors
Dec 3, 2026
Merged

aidint merged 2 commits into
llvm:mainfrom
aidint:aidint/function-boundary-memory-space-for-custom-tensors

Conversation

@aidint

@aidint aidint commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Building on top of #201350, which made defaultMemorySpaceFn and unknownTypeConverterFn support tensor-like types, this PR removes the restriction that defaultMemorySpaceFn is only queried for builtin tensor types at function boundaries.

If defaultMemorySpaceFn returns std::nullopt for a custom tensor type, an error is now emitted, as for builtin tensors.

Assisted-by: Claude Code

…oundaries

Building on top of llvm#201350, which made `defaultMemorySpaceFn` and
`unknownTypeConverterFn` support tensor-like types, this PR removes the
restriction that `defaultMemorySpaceFn` is only queried for builtin
tensor types at function boundaries.

If `defaultMemorySpaceFn` returns `std::nullopt` for a custom tensor type,
an error is now emitted, as for builtin tensors.
@llvmorg-github-actions llvmorg-github-actions Bot added mlir mlir:bufferization Bufferization infrastructure labels Dec 2, 2026
@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-mlir-bufferization

Author: AidinT (aidint)

Changes

Building on top of #201350, which made defaultMemorySpaceFn and unknownTypeConverterFn support tensor-like types, this PR removes the restriction that defaultMemorySpaceFn is only queried for builtin tensor types at function boundaries.

If defaultMemorySpaceFn returns std::nullopt for a custom tensor type, an error is now emitted, as for builtin tensors.


Full diff: https://github.com/llvm/llvm-project/pull/248055.diff

4 Files Affected:

  • (modified) mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp (+11-15)
  • (added) mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir (+34)
  • (added) mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir (+36)
  • (modified) mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp (+46)
diff --git a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
index 372b3678df4889..35fcf027cb02c3 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
@@ -63,9 +63,6 @@ getFunctionResultMemorySpace(FuncOp funcOp, int64_t index,
       dyn_cast<TensorLikeType>(funcOp.getFunctionType().getResult(index));
   assert(type && "expected TensorLikeType");
 
-  if (!isa<TensorType>(type))
-    return Attribute();
-
   auto memorySpace = options.defaultMemorySpaceFn(type);
   if (!memorySpace)
     return funcOp.emitError("could not infer memory space for result #")
@@ -85,21 +82,21 @@ getBufferizedFunctionArgType(FuncOp funcOp, int64_t index,
       dyn_cast<TensorLikeType>(funcOp.getFunctionType().getInput(index));
   assert(type && "expected TensorLikeType");
 
-  // Note: For builtin tensors there is additional logic related to layout.
-  if (auto tensorType = dyn_cast<TensorType>(type)) {
-    auto memorySpace = options.defaultMemorySpaceFn(type);
-    if (!memorySpace)
-      return funcOp.emitError("could not infer memory space for argument #")
-             << index;
-    BufferLikeType memrefType =
-        options.functionArgTypeConverterFn(type, *memorySpace, funcOp, options);
+  auto memorySpace = options.defaultMemorySpaceFn(type);
+  if (!memorySpace)
+    return funcOp.emitError("could not infer memory space for argument #")
+           << index;
+  BufferLikeType bufferType =
+      options.functionArgTypeConverterFn(type, *memorySpace, funcOp, options);
 
+  // Note: For builtin tensors there is additional logic related to layout.
+  if (isa<TensorType>(type)) {
     auto layoutAttr = funcOp.getArgAttrOfType<MemRefLayoutAttrInterface>(
         index, BufferizationDialect::kBufferLayoutAttrName);
     if (!layoutAttr)
-      return memrefType;
+      return bufferType;
 
-    auto rankedMemrefType = dyn_cast<MemRefType>(memrefType);
+    auto rankedMemrefType = dyn_cast<MemRefType>(bufferType);
     assert(rankedMemrefType &&
            "buffer layout not supported on unranked tensors");
     return cast<BufferLikeType>(MemRefType::get(
@@ -107,8 +104,7 @@ getBufferizedFunctionArgType(FuncOp funcOp, int64_t index,
         layoutAttr, rankedMemrefType.getMemorySpace()));
   }
 
-  return options.functionArgTypeConverterFn(type, /*memSpace=*/nullptr, funcOp,
-                                            options);
+  return bufferType;
 }
 
 /// Return the FuncOp called by `callOp`.
diff --git a/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir
new file mode 100644
index 00000000000000..c11133d09e849c
--- /dev/null
+++ b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir
@@ -0,0 +1,34 @@
+// RUN: mlir-opt %s -test-one-shot-module-bufferize="cannot-infer-memory-space-for-test-tensors" -split-input-file -verify-diagnostics
+
+// Function boundaries ask defaultMemorySpaceFn about custom tensor types, not
+// only about builtin tensors. The memory space cannot be inferred for test
+// tensors, while builtin tensors get the default memory space.
+
+// expected-error @+2 {{could not infer memory space for argument #1}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func @test_tensor_arg(%b: tensor<4xf64>, %t: !test.test_tensor<[4], f64>)
+    -> !test.test_tensor<[4], f64> {
+  return %t : !test.test_tensor<[4], f64>
+}
+
+// -----
+
+// expected-error @+2 {{could not infer memory space for result #0}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func @test_tensor_result() -> !test.test_tensor<[4], f64> {
+  %0 = "test.create_tensor_op"() : () -> !test.test_tensor<[4], f64>
+  return %0 : !test.test_tensor<[4], f64>
+}
+
+// -----
+
+// expected-error @+2 {{could not infer memory space for argument #0}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func private @test_tensor_arg_declaration(!test.test_tensor<[4], f64>)
+
+// -----
+
+// expected-error @+2 {{could not infer memory space for result #1}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func private @test_tensor_result_declaration()
+    -> (tensor<4xf64>, !test.test_tensor<[4], f64>)
diff --git a/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir
new file mode 100644
index 00000000000000..61dcd7eda9e2a4
--- /dev/null
+++ b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir
@@ -0,0 +1,36 @@
+// RUN: mlir-opt %s -test-one-shot-module-bufferize="test-tensor-to-memref use-memory-space-1-for-test-tensors" -split-input-file | FileCheck %s
+
+// Function boundaries ask defaultMemorySpaceFn about custom tensor types, not
+// only about builtin tensors. Test tensors get memory space 1 and builtin
+// tensors the default memory space.
+
+// CHECK-LABEL: func.func @test_tensor_arg_and_result(
+// CHECK-SAME:    %[[T:[^:]+]]: memref<4xf64, 1>, %[[B:[^:]+]]: memref<4xf64>
+// CHECK-SAME:  ) -> memref<4xf64, 1>
+// CHECK:         return %[[T]] : memref<4xf64, 1>
+func.func @test_tensor_arg_and_result(%t: !test.test_tensor<[4], f64>,
+                                      %b: tensor<4xf64>)
+    -> !test.test_tensor<[4], f64> {
+  return %t : !test.test_tensor<[4], f64>
+}
+
+// -----
+
+// CHECK-LABEL: func.func private @test_tensor_declaration(
+// CHECK-SAME:    memref<4xf64, 1>) -> memref<4xf64, 1>
+func.func private @test_tensor_declaration(!test.test_tensor<[4], f64>)
+    -> !test.test_tensor<[4], f64>
+
+// CHECK-LABEL: func.func @call_test_tensor_declaration(
+// CHECK-SAME:    %[[T:[^:]+]]: memref<4xf64, 1>) -> memref<4xf64, 1>
+// CHECK:         %[[ALLOC:.*]] = memref.alloc() {{.*}} : memref<4xf64, 1>
+// CHECK:         memref.copy %[[T]], %[[ALLOC]]
+// CHECK:         %[[R:.*]] = call @test_tensor_declaration(%[[ALLOC]])
+// CHECK-SAME:      : (memref<4xf64, 1>) -> memref<4xf64, 1>
+// CHECK:         return %[[R]] : memref<4xf64, 1>
+func.func @call_test_tensor_declaration(%t: !test.test_tensor<[4], f64>)
+    -> !test.test_tensor<[4], f64> {
+  %0 = call @test_tensor_declaration(%t)
+      : (!test.test_tensor<[4], f64>) -> !test.test_tensor<[4], f64>
+  return %0 : !test.test_tensor<[4], f64>
+}
diff --git a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
index cb60b63ad35d98..e083afea3ae212 100644
--- a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
+++ b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
@@ -80,6 +80,19 @@ struct TestOneShotModuleBufferizePass
       llvm::cl::desc("Convert test tensors to builtin memrefs with dynamic "
                      "extents."),
       llvm::cl::init(false)};
+  Option<bool> cannotInferMemorySpaceForTestTensors{
+      *this, "cannot-infer-memory-space-for-test-tensors",
+      llvm::cl::desc("defaultMemorySpaceFn returns std::nullopt (memory space "
+                     "cannot be inferred) for test tensors and the default "
+                     "memory space for all other tensors."),
+      llvm::cl::init(false)};
+  Option<bool> useMemorySpace1ForTestTensors{
+      *this, "use-memory-space-1-for-test-tensors",
+      llvm::cl::desc("defaultMemorySpaceFn returns memory space 1 for test "
+                     "tensors and the default memory space for all other "
+                     "tensors. Requires 'test-tensor-to-memref' or "
+                     "'test-tensor-to-dynamic-memref'."),
+      llvm::cl::init(false)};
 
   void runOnOperation() override {
 
@@ -89,6 +102,39 @@ struct TestOneShotModuleBufferizePass
 
     opt.bufferizeFunctionBoundaries = true;
     opt.allowReturnAllocsFromLoops = allowReturnAllocsFromLoops;
+
+    if (cannotInferMemorySpaceForTestTensors && useMemorySpace1ForTestTensors) {
+      emitError(getOperation()->getLoc())
+          << "only one of 'cannot-infer-memory-space-for-test-tensors' and "
+             "'use-memory-space-1-for-test-tensors' is allowed in "
+          << getArgument();
+      return signalPassFailure();
+    }
+    if (cannotInferMemorySpaceForTestTensors) {
+      opt.defaultMemorySpaceFn =
+          [](bufferization::TensorLikeType type) -> std::optional<Attribute> {
+        if (isa<test::TestTensorType>(type))
+          return std::nullopt;
+        return Attribute();
+      };
+    }
+    if (useMemorySpace1ForTestTensors) {
+      // Test memrefs have no memory space, so test tensors must bufferize to
+      // builtin memrefs.
+      if (!testTensorToMemRef && !testTensorToDynamicMemRef) {
+        emitError(getOperation()->getLoc())
+            << "'use-memory-space-1-for-test-tensors' requires "
+               "'test-tensor-to-memref' or 'test-tensor-to-dynamic-memref' in "
+            << getArgument();
+        return signalPassFailure();
+      }
+      opt.defaultMemorySpaceFn =
+          [](bufferization::TensorLikeType type) -> std::optional<Attribute> {
+        if (isa<test::TestTensorType>(type))
+          return IntegerAttr::get(IntegerType::get(type.getContext(), 64), 1);
+        return Attribute();
+      };
+    }
     opt.functionArgTypeConverterFn =
         [&](bufferization::TensorLikeType tensor, Attribute memSpace,
             func::FuncOp, const bufferization::BufferizationOptions &options) {

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-mlir

Author: AidinT (aidint)

Changes

Building on top of #201350, which made defaultMemorySpaceFn and unknownTypeConverterFn support tensor-like types, this PR removes the restriction that defaultMemorySpaceFn is only queried for builtin tensor types at function boundaries.

If defaultMemorySpaceFn returns std::nullopt for a custom tensor type, an error is now emitted, as for builtin tensors.


Full diff: https://github.com/llvm/llvm-project/pull/248055.diff

4 Files Affected:

  • (modified) mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp (+11-15)
  • (added) mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir (+34)
  • (added) mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir (+36)
  • (modified) mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp (+46)
diff --git a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
index 372b3678df4889..35fcf027cb02c3 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
@@ -63,9 +63,6 @@ getFunctionResultMemorySpace(FuncOp funcOp, int64_t index,
       dyn_cast<TensorLikeType>(funcOp.getFunctionType().getResult(index));
   assert(type && "expected TensorLikeType");
 
-  if (!isa<TensorType>(type))
-    return Attribute();
-
   auto memorySpace = options.defaultMemorySpaceFn(type);
   if (!memorySpace)
     return funcOp.emitError("could not infer memory space for result #")
@@ -85,21 +82,21 @@ getBufferizedFunctionArgType(FuncOp funcOp, int64_t index,
       dyn_cast<TensorLikeType>(funcOp.getFunctionType().getInput(index));
   assert(type && "expected TensorLikeType");
 
-  // Note: For builtin tensors there is additional logic related to layout.
-  if (auto tensorType = dyn_cast<TensorType>(type)) {
-    auto memorySpace = options.defaultMemorySpaceFn(type);
-    if (!memorySpace)
-      return funcOp.emitError("could not infer memory space for argument #")
-             << index;
-    BufferLikeType memrefType =
-        options.functionArgTypeConverterFn(type, *memorySpace, funcOp, options);
+  auto memorySpace = options.defaultMemorySpaceFn(type);
+  if (!memorySpace)
+    return funcOp.emitError("could not infer memory space for argument #")
+           << index;
+  BufferLikeType bufferType =
+      options.functionArgTypeConverterFn(type, *memorySpace, funcOp, options);
 
+  // Note: For builtin tensors there is additional logic related to layout.
+  if (isa<TensorType>(type)) {
     auto layoutAttr = funcOp.getArgAttrOfType<MemRefLayoutAttrInterface>(
         index, BufferizationDialect::kBufferLayoutAttrName);
     if (!layoutAttr)
-      return memrefType;
+      return bufferType;
 
-    auto rankedMemrefType = dyn_cast<MemRefType>(memrefType);
+    auto rankedMemrefType = dyn_cast<MemRefType>(bufferType);
     assert(rankedMemrefType &&
            "buffer layout not supported on unranked tensors");
     return cast<BufferLikeType>(MemRefType::get(
@@ -107,8 +104,7 @@ getBufferizedFunctionArgType(FuncOp funcOp, int64_t index,
         layoutAttr, rankedMemrefType.getMemorySpace()));
   }
 
-  return options.functionArgTypeConverterFn(type, /*memSpace=*/nullptr, funcOp,
-                                            options);
+  return bufferType;
 }
 
 /// Return the FuncOp called by `callOp`.
diff --git a/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir
new file mode 100644
index 00000000000000..c11133d09e849c
--- /dev/null
+++ b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space-invalid.mlir
@@ -0,0 +1,34 @@
+// RUN: mlir-opt %s -test-one-shot-module-bufferize="cannot-infer-memory-space-for-test-tensors" -split-input-file -verify-diagnostics
+
+// Function boundaries ask defaultMemorySpaceFn about custom tensor types, not
+// only about builtin tensors. The memory space cannot be inferred for test
+// tensors, while builtin tensors get the default memory space.
+
+// expected-error @+2 {{could not infer memory space for argument #1}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func @test_tensor_arg(%b: tensor<4xf64>, %t: !test.test_tensor<[4], f64>)
+    -> !test.test_tensor<[4], f64> {
+  return %t : !test.test_tensor<[4], f64>
+}
+
+// -----
+
+// expected-error @+2 {{could not infer memory space for result #0}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func @test_tensor_result() -> !test.test_tensor<[4], f64> {
+  %0 = "test.create_tensor_op"() : () -> !test.test_tensor<[4], f64>
+  return %0 : !test.test_tensor<[4], f64>
+}
+
+// -----
+
+// expected-error @+2 {{could not infer memory space for argument #0}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func private @test_tensor_arg_declaration(!test.test_tensor<[4], f64>)
+
+// -----
+
+// expected-error @+2 {{could not infer memory space for result #1}}
+// expected-error @+1 {{failed to bufferize op}}
+func.func private @test_tensor_result_declaration()
+    -> (tensor<4xf64>, !test.test_tensor<[4], f64>)
diff --git a/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir
new file mode 100644
index 00000000000000..61dcd7eda9e2a4
--- /dev/null
+++ b/mlir/test/Dialect/Bufferization/Transforms/test-one-shot-module-bufferize-memory-space.mlir
@@ -0,0 +1,36 @@
+// RUN: mlir-opt %s -test-one-shot-module-bufferize="test-tensor-to-memref use-memory-space-1-for-test-tensors" -split-input-file | FileCheck %s
+
+// Function boundaries ask defaultMemorySpaceFn about custom tensor types, not
+// only about builtin tensors. Test tensors get memory space 1 and builtin
+// tensors the default memory space.
+
+// CHECK-LABEL: func.func @test_tensor_arg_and_result(
+// CHECK-SAME:    %[[T:[^:]+]]: memref<4xf64, 1>, %[[B:[^:]+]]: memref<4xf64>
+// CHECK-SAME:  ) -> memref<4xf64, 1>
+// CHECK:         return %[[T]] : memref<4xf64, 1>
+func.func @test_tensor_arg_and_result(%t: !test.test_tensor<[4], f64>,
+                                      %b: tensor<4xf64>)
+    -> !test.test_tensor<[4], f64> {
+  return %t : !test.test_tensor<[4], f64>
+}
+
+// -----
+
+// CHECK-LABEL: func.func private @test_tensor_declaration(
+// CHECK-SAME:    memref<4xf64, 1>) -> memref<4xf64, 1>
+func.func private @test_tensor_declaration(!test.test_tensor<[4], f64>)
+    -> !test.test_tensor<[4], f64>
+
+// CHECK-LABEL: func.func @call_test_tensor_declaration(
+// CHECK-SAME:    %[[T:[^:]+]]: memref<4xf64, 1>) -> memref<4xf64, 1>
+// CHECK:         %[[ALLOC:.*]] = memref.alloc() {{.*}} : memref<4xf64, 1>
+// CHECK:         memref.copy %[[T]], %[[ALLOC]]
+// CHECK:         %[[R:.*]] = call @test_tensor_declaration(%[[ALLOC]])
+// CHECK-SAME:      : (memref<4xf64, 1>) -> memref<4xf64, 1>
+// CHECK:         return %[[R]] : memref<4xf64, 1>
+func.func @call_test_tensor_declaration(%t: !test.test_tensor<[4], f64>)
+    -> !test.test_tensor<[4], f64> {
+  %0 = call @test_tensor_declaration(%t)
+      : (!test.test_tensor<[4], f64>) -> !test.test_tensor<[4], f64>
+  return %0 : !test.test_tensor<[4], f64>
+}
diff --git a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
index cb60b63ad35d98..e083afea3ae212 100644
--- a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
+++ b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
@@ -80,6 +80,19 @@ struct TestOneShotModuleBufferizePass
       llvm::cl::desc("Convert test tensors to builtin memrefs with dynamic "
                      "extents."),
       llvm::cl::init(false)};
+  Option<bool> cannotInferMemorySpaceForTestTensors{
+      *this, "cannot-infer-memory-space-for-test-tensors",
+      llvm::cl::desc("defaultMemorySpaceFn returns std::nullopt (memory space "
+                     "cannot be inferred) for test tensors and the default "
+                     "memory space for all other tensors."),
+      llvm::cl::init(false)};
+  Option<bool> useMemorySpace1ForTestTensors{
+      *this, "use-memory-space-1-for-test-tensors",
+      llvm::cl::desc("defaultMemorySpaceFn returns memory space 1 for test "
+                     "tensors and the default memory space for all other "
+                     "tensors. Requires 'test-tensor-to-memref' or "
+                     "'test-tensor-to-dynamic-memref'."),
+      llvm::cl::init(false)};
 
   void runOnOperation() override {
 
@@ -89,6 +102,39 @@ struct TestOneShotModuleBufferizePass
 
     opt.bufferizeFunctionBoundaries = true;
     opt.allowReturnAllocsFromLoops = allowReturnAllocsFromLoops;
+
+    if (cannotInferMemorySpaceForTestTensors && useMemorySpace1ForTestTensors) {
+      emitError(getOperation()->getLoc())
+          << "only one of 'cannot-infer-memory-space-for-test-tensors' and "
+             "'use-memory-space-1-for-test-tensors' is allowed in "
+          << getArgument();
+      return signalPassFailure();
+    }
+    if (cannotInferMemorySpaceForTestTensors) {
+      opt.defaultMemorySpaceFn =
+          [](bufferization::TensorLikeType type) -> std::optional<Attribute> {
+        if (isa<test::TestTensorType>(type))
+          return std::nullopt;
+        return Attribute();
+      };
+    }
+    if (useMemorySpace1ForTestTensors) {
+      // Test memrefs have no memory space, so test tensors must bufferize to
+      // builtin memrefs.
+      if (!testTensorToMemRef && !testTensorToDynamicMemRef) {
+        emitError(getOperation()->getLoc())
+            << "'use-memory-space-1-for-test-tensors' requires "
+               "'test-tensor-to-memref' or 'test-tensor-to-dynamic-memref' in "
+            << getArgument();
+        return signalPassFailure();
+      }
+      opt.defaultMemorySpaceFn =
+          [](bufferization::TensorLikeType type) -> std::optional<Attribute> {
+        if (isa<test::TestTensorType>(type))
+          return IntegerAttr::get(IntegerType::get(type.getContext(), 64), 1);
+        return Attribute();
+      };
+    }
     opt.functionArgTypeConverterFn =
         [&](bufferization::TensorLikeType tensor, Attribute memSpace,
             func::FuncOp, const bufferization::BufferizationOptions &options) {

@matthias-springer matthias-springer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about buffer types that do not have a memory space?

@aidint

aidint commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

What about buffer types that do not have a memory space?

I assume defaultMemorySpaceFn shouldn't return std::nullopt in that case because it indicates failure in bufferization based on this comment:

// Returning std::nullopt will cause bufferization to fail (useful to indicate
// failure to determine memory space for a tensor type).

Then functionArgTypeConverterFn handles that case, which will pass the type to the unknownTypeConverterFn, and there it can discard nullptr memory space for that specific tensor/buffer type.

@aidint
aidint merged commit 0932918 into llvm:main Dec 3, 2026
9 checks passed
@aidint
aidint deleted the aidint/function-boundary-memory-space-for-custom-tensors branch December 3, 2026 10:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mlir:bufferization Bufferization infrastructure mlir

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants