[flang-commits] [flang] [flang][cuda] Fix invalid host free of managed allocatable function results (PR #209945)

via flang-commits flang-commits at lists.llvm.org
Thu Jul 16 01:48:49 PDT 2026


================
@@ -1972,25 +1973,52 @@ genUserCall(Fortran::lower::PreparedActualArguments &loweredActuals,
     // Allocatable result must be freed, other results are stack allocated.
     const auto *allocatable = result.getBoxOf<fir::MutableBoxValue>();
     const bool mustFree = allocatable != nullptr;
+    // A CUDA allocatable result is allocated with the CUDA allocator and must
+    // be released with the CUDA-aware deallocation, not the host free emitted
+    // by the plain hlfir.expr move + destroy path.
+    const Fortran::semantics::Symbol *resultSym = nullptr;
+    cuf::DataAttributeAttr resultCudaAttr;
+    if (mustFree && caller.getInterfaceDetails()) {
+      resultSym = &caller.getResultSymbol();
+      resultCudaAttr = Fortran::lower::translateSymbolCUFDataAttribute(
+          builder.getContext(), *resultSym);
+    }
+    const bool isCudaAllocatableResult = static_cast<bool>(resultCudaAttr);
+    auto genCudaResultCleanUp = [&]() {
+      callContext.stmtCtx.attachCleanup([&converter = callContext.converter,
+                                         loc, box = *allocatable, resultSym]() {
+        Fortran::lower::genDeallocateIfAllocated(converter, box, loc,
+                                                 resultSym);
+      });
+    };
     resultEntity = loadTrivialScalar(loc, builder, resultEntity);
----------------
jeanPerier wrote:

I think you should skip the whole part below when  the result is in managed memory.
The goal of the code below is to "move" the result storage into a value. But if your storage is managed, I do not think it is OK to move it in general.

So I think you should do something like this here:

```
 if (isCudaAllocatableResult) {
     callContext.stmtCtx.attachCleanup([&converter = callContext.converter,
                                         loc, box = *allocatable, resultSym]() {
        Fortran::lower::genDeallocateIfAllocated(converter, box, loc,
                                                 resultSym);
      });
     return hlfir::EntityWithAttributes{resultEntity};
 }
```

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


More information about the flang-commits mailing list