[flang-commits] [flang] [Flang] Avoid crash when a function return is undefined (PR #151577)

Carlos Seo via flang-commits flang-commits at lists.llvm.org
Mon Aug 4 09:48:47 PDT 2025


https://github.com/ceseo updated https://github.com/llvm/llvm-project/pull/151577

>From c82e9612d1b7d13e9ddc709e3327aa39a2eb4a5d Mon Sep 17 00:00:00 2001
From: Carlos Seo <carlos.seo at linaro.org>
Date: Thu, 31 Jul 2025 18:51:02 +0000
Subject: [PATCH] [Flang] Avoid crash when a function return is undefined

Properly terminate the StatementContext cleanup when a function return value is
undefined.

Fixes #126452
---
 flang/lib/Lower/Bridge.cpp             | 8 +++++++-
 flang/test/Lower/undef-func-result.f90 | 7 +++++++
 2 files changed, 14 insertions(+), 1 deletion(-)
 create mode 100644 flang/test/Lower/undef-func-result.f90

diff --git a/flang/lib/Lower/Bridge.cpp b/flang/lib/Lower/Bridge.cpp
index 059b467655358..6343866a5066d 100644
--- a/flang/lib/Lower/Bridge.cpp
+++ b/flang/lib/Lower/Bridge.cpp
@@ -1732,7 +1732,13 @@ class FirConverter : public Fortran::lower::AbstractConverter {
     Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym);
     mlir::Location loc = toLocation();
     if (!resultSymBox) {
-      mlir::emitError(loc, "internal error when processing function return");
+      // Create a dummy undefined value of the expected return type.
+      // This prevents improper cleanup of StatementContext, which would lead
+      // to a crash due to a block with no terminator. See issue #126452.
+      mlir::FunctionType funcType = builder->getFunction().getFunctionType();
+      mlir::Type resultType = funcType.getResult(0);
+      mlir::Value undefResult = builder->create<fir::UndefOp>(loc, resultType);
+      genExitRoutine(false, undefResult);
       return;
     }
     mlir::Value resultVal = resultSymBox.match(
diff --git a/flang/test/Lower/undef-func-result.f90 b/flang/test/Lower/undef-func-result.f90
new file mode 100644
index 0000000000000..e3d3e23614a53
--- /dev/null
+++ b/flang/test/Lower/undef-func-result.f90
@@ -0,0 +1,7 @@
+!RUN: %flang -c %s -### 2>&1
+function s(x) result(i)
+!CHECK-WARNING: Function result is never defined
+integer::x
+procedure():: i
+end function
+end



More information about the flang-commits mailing list