[Mlir-commits] [mlir] [mlir][core|ptr] Add `PtrLikeTypeInterface` and casting ops to the `ptr` dialect (PR #137469)

Fabian Mora llvmlistbot at llvm.org
Sun Apr 27 04:44:38 PDT 2025


================
@@ -17,6 +17,75 @@ include "mlir/Interfaces/SideEffectInterfaces.td"
 include "mlir/Interfaces/ViewLikeInterface.td"
 include "mlir/IR/OpAsmInterface.td"
 
+//===----------------------------------------------------------------------===//
+// FromPtrOp
+//===----------------------------------------------------------------------===//
+
+def Ptr_FromPtrOp : Pointer_Op<"from_ptr", [
+    Pure, OptionalTypesMatchWith<"metadata type", "result", "metadata",
+            "PtrMetadataType::get(cast<PtrLikeTypeInterface>($_self))">
+  ]> {
+  let summary = "Casts a `!ptr.ptr` value to a ptr-like value.";
+  let description = [{
+    The `from_ptr` operation casts a `ptr` value to a ptr-like object. It's
+    important to note that:
+    - The ptr-like object cannot be a `!ptr.ptr`.
+    - The memory-space of both the `ptr` and ptr-like object must match.
+    - The cast is side-effect free.
+
+    If the ptr-like object type has metadata, then the operation expects the
+    metadata as an argument or expects that the flag `trivial_metadata` is set.
+    If `trivial_metadata` is set, then it is assumed that the metadata can be
+    reconstructed statically from the pointer-like type.
----------------
fabianmcg wrote:

Let's suppose that we have `%v0: memref<f32, 0>` in which `alignedPtr != allocatedPtr`.  Then in the following example `%v1 != %v0`:

```mlir
%p = to.ptr %v : memref<f32, 0> -> !ptr.ptr<0>
%v1 = from_ptr %p : !ptr.ptr<0> -> memref<f32, 0>
```

So in that case the cast sequence is a lossy conversion, which might be fine for the user and it should be possible to do. However, I think it makes for a less buggy experience to explicitly state that the user is ignoring the metadata.  

Currently, the above IR will generate a verification error saying that `from_ptr` requires metadata because the type says so. 



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


More information about the Mlir-commits mailing list