[clang] [flang] [llvm] [flang] Add -fbacktrace and -fno-backtrace (PR #241967)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 12 08:55:43 PST 2026
https://github.com/shivaramaarao created https://github.com/llvm/llvm-project/pull/241967
Match gfortran by printing a stack trace on fatal runtime errors and deadly signals by default. -fno-backtrace turns the trace off. The driver forwards whichever of -fbacktrace or -fno-backtrace appears last. Without either flag, nothing is passed and the frontend leaves tracing on. -fno-backtrace adds FLANG_ERROR_BACKTRACE=0 to the environment defaults, which the runtime reads at startup. An existing value of FLANG_ERROR_BACKTRACE in the environment takes precedence. The runtime reads the first character of FLANG_ERROR_BACKTRACE: 1/Y/y enables the trace and 0/N/n disables it. Other values are ignored.
When enabled, the trace is printed for host :
- runtime errors (Terminator::CrashFooter)
- ERROR STOP
- ABORT
- SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGBUS, SIGSYS, SIGTRAP, SIGXCPU and SIGXFSZ, where the platform defines them
Assisted by Cursor
>From ad202aed57348cfbe29a68d10c6cdca7e6ac6ccc Mon Sep 17 00:00:00 2001
From: Shivarama Rao <shivarama.rao at amd.com>
Date: Thu, 12 Nov 2026 22:14:22 +0530
Subject: [PATCH] [flang] Add -fbacktrace and -fno-backtrace
Match gfortran by printing a stack trace on fatal runtime errors and
deadly signals by default. -fno-backtrace turns the trace off.
The driver forwards whichever of -fbacktrace or -fno-backtrace appears
last. Without either flag, nothing is passed and the frontend leaves
tracing on. -fno-backtrace adds FLANG_ERROR_BACKTRACE=0 to the
environment defaults, which the runtime reads at startup. An existing
value of FLANG_ERROR_BACKTRACE in the environment takes precedence.
The runtime reads the first character of FLANG_ERROR_BACKTRACE:
1/Y/y enables the trace and 0/N/n disables it. Other values are
ignored.
When enabled, the trace is printed for host :
- runtime errors (Terminator::CrashFooter)
- ERROR STOP
- ABORT
- SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGBUS, SIGSYS, SIGTRAP,
SIGXCPU and SIGXFSZ, where the platform defines them
Assisted by Cursor
---
clang/include/clang/Options/FlangOptions.td | 5 +-
clang/lib/Driver/ToolChains/Flang.cpp | 4 +
.../include/flang-rt/runtime/environment.h | 5 +
.../include/flang-rt/runtime/terminator.h | 14 +++
flang-rt/lib/runtime/environment.cpp | 13 ++
flang-rt/lib/runtime/main.cpp | 4 +
flang-rt/lib/runtime/stop.cpp | 115 +++++++++++++++++-
flang-rt/lib/runtime/terminator.cpp | 6 +
flang/docs/ReleaseNotes.md | 6 +
flang/docs/RuntimeEnvironment.md | 18 +++
flang/lib/Frontend/CompilerInvocation.cpp | 7 ++
flang/test/Driver/fbacktrace.f90 | 22 ++++
flang/test/Lower/backtrace.f90 | 15 +++
13 files changed, 229 insertions(+), 5 deletions(-)
create mode 100644 flang/test/Driver/fbacktrace.f90
create mode 100644 flang/test/Lower/backtrace.f90
diff --git a/clang/include/clang/Options/FlangOptions.td b/clang/include/clang/Options/FlangOptions.td
index ad39d052bee6a..93f822e9f019c 100644
--- a/clang/include/clang/Options/FlangOptions.td
+++ b/clang/include/clang/Options/FlangOptions.td
@@ -37,7 +37,6 @@ defm aggressive_function_elimination : BooleanFFlag<"aggressive-function-elimina
defm align_commons : BooleanFFlag<"align-commons">, Group<gfortran_Group>;
defm all_intrinsics : BooleanFFlag<"all-intrinsics">, Group<gfortran_Group>;
def fautomatic : Flag<["-"], "fautomatic">; // -fno-automatic is significant
-defm backtrace : BooleanFFlag<"backtrace">, Group<gfortran_Group>;
defm bounds_check : BooleanFFlag<"bounds-check">, Group<gfortran_Group>;
defm check_array_temporaries : BooleanFFlag<"check-array-temporaries">, Group<gfortran_Group>;
defm cray_pointer : BooleanFFlag<"cray-pointer">, Group<gfortran_Group>;
@@ -146,6 +145,10 @@ def ffixed_line_length_EQ : Joined<["-"], "ffixed-line-length=">, Group<f_Group>
DocBrief<[{Set column after which characters are ignored in typical fixed-form lines in the source
file}]>;
def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, Group<f_Group>, Alias<ffixed_line_length_EQ>;
+def fbacktrace : Flag<["-"], "fbacktrace">, Group<f_Group>,
+ HelpText<"Print a stack trace on a fatal runtime error or deadly signal (default)">;
+def fno_backtrace : Flag<["-"], "fno-backtrace">, Group<f_Group>,
+ HelpText<"Do not print a stack trace on a fatal runtime error or deadly signal">;
def fconvert_EQ : Joined<["-"], "fconvert=">, Group<f_Group>,
HelpText<"Set endian conversion of data for unformatted files">;
def fdefault_double_8 : Flag<["-"],"fdefault-double-8">, Group<f_Group>,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp
index 522907b58022f..bdd0d9e41b596 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -292,6 +292,10 @@ void Flang::addDebugOptions(const llvm::opt::ArgList &Args, const JobAction &JA,
options::OPT_fno_openacc_multiple_names_in_routine,
options::OPT_finstrument_functions});
+ // Forward whichever of -fbacktrace/-fno-backtrace appears last. Pass
+ // neither when the user did not specify one; the frontend default is on.
+ Args.addLastArg(CmdArgs, options::OPT_fbacktrace, options::OPT_fno_backtrace);
+
llvm::codegenoptions::DebugInfoKind DebugInfoKind;
bool hasDwarfNArg = getDwarfNArg(Args) != nullptr;
if (Args.hasArg(options::OPT_gN_Group)) {
diff --git a/flang-rt/include/flang-rt/runtime/environment.h b/flang-rt/include/flang-rt/runtime/environment.h
index 332330e651c94..c06600abd3801 100644
--- a/flang-rt/include/flang-rt/runtime/environment.h
+++ b/flang-rt/include/flang-rt/runtime/environment.h
@@ -80,6 +80,11 @@ struct ExecutionEnvironment {
ConvertUnit *convertUnits{nullptr}; // FORT_CONVERT_UNIT
std::size_t numConvertUnits{0};
bool noStopMessage{false}; // NO_STOP_MESSAGE=1 inhibits "Fortran STOP"
+ // Print a stack trace for a fatal runtime error, ERROR STOP, or a deadly
+ // signal. On by default, matching gfortran -fbacktrace.
+ // ExecutionEnvironment::Configure() applies FLANG_ERROR_BACKTRACE
+ // when this variable is set.
+ bool backtrace{true};
// FLANG_TIMEF_IN_MILLISECONDS=1 sets TIMEF resolution to milliseconds.
// Default resolution is seconds.
bool timefInMillisec{false};
diff --git a/flang-rt/include/flang-rt/runtime/terminator.h b/flang-rt/include/flang-rt/runtime/terminator.h
index a856c4eb76188..43fe325faaf54 100644
--- a/flang-rt/include/flang-rt/runtime/terminator.h
+++ b/flang-rt/include/flang-rt/runtime/terminator.h
@@ -16,6 +16,12 @@
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
+// <csignal> is not available for device compilation or a native GPU build.
+// FLANG_RT_HAVE_CSIGNAL marks the host builds where std::signal is declared.
+#if !defined(RT_DEVICE_COMPILATION) && !RT_GPU_TARGET
+#include <csignal>
+#define FLANG_RT_HAVE_CSIGNAL 1
+#endif
namespace Fortran::runtime {
@@ -120,6 +126,14 @@ void SetErrorCallback(void (*callback)(int));
[[noreturn]] void NormalExit(int exitCode);
[[noreturn]] void ErrorExit(int exitCode);
+#ifdef FLANG_RT_HAVE_CSIGNAL
+// Host only. Device and native GPU builds do not include <csignal>.
+// Print a stack trace when -fbacktrace is enabled. heading may be null.
+void PrintFatalBacktrace(const char *heading);
+// Install handlers for deadly signals.
+void InstallFatalBacktraceHandlers();
+#endif
+
RT_API_ATTRS void SynchronizeImagesOfNormalEnd(int);
RT_API_ATTRS void NotifyOtherImagesOfFailImageStatement();
RT_API_ATTRS void NotifyOtherImagesOfErrorTermination(int);
diff --git a/flang-rt/lib/runtime/environment.cpp b/flang-rt/lib/runtime/environment.cpp
index f02e8b0172b7b..f4cb2c2675b7a 100644
--- a/flang-rt/lib/runtime/environment.cpp
+++ b/flang-rt/lib/runtime/environment.cpp
@@ -326,6 +326,19 @@ void ExecutionEnvironment::Configure(int ac, const char *av[],
}
}
+ // FLANG_ERROR_BACKTRACE overrides the -fbacktrace default. Only the first
+ // character is significant, matching gfortran: 1/Y/y enables, 0/N/n disables.
+ // Any other value is ignored. -fno-backtrace supplies "0" when the variable
+ // is not already set.
+ backtrace = true;
+ if (auto *x{std::getenv("FLANG_ERROR_BACKTRACE")}) {
+ if (*x == '1' || *x == 'Y' || *x == 'y') {
+ backtrace = true;
+ } else if (*x == '0' || *x == 'N' || *x == 'n') {
+ backtrace = false;
+ }
+ }
+
if (auto *x{std::getenv("NO_STOP_MESSAGE")}) {
char *end;
auto n{std::strtol(x, &end, 10)};
diff --git a/flang-rt/lib/runtime/main.cpp b/flang-rt/lib/runtime/main.cpp
index 950d0839863f0..893a074e5c5e4 100644
--- a/flang-rt/lib/runtime/main.cpp
+++ b/flang-rt/lib/runtime/main.cpp
@@ -32,6 +32,10 @@ void RTNAME(ProgramStart)(int argc, const char *argv[], const char *envp[],
const EnvironmentDefaultList *envDefaults) {
Fortran::runtime::executionEnvironment.Configure(
argc, argv, envp, envDefaults);
+#ifdef FLANG_RT_HAVE_CSIGNAL
+ if (Fortran::runtime::executionEnvironment.backtrace)
+ Fortran::runtime::InstallFatalBacktraceHandlers();
+#endif
ConfigureFloatingPoint();
Fortran::runtime::io::RegisterRPCHandlers();
// I/O is initialized on demand so that it works for non-Fortran main().
diff --git a/flang-rt/lib/runtime/stop.cpp b/flang-rt/lib/runtime/stop.cpp
index 561ea41642aaf..8b81ff2e54444 100644
--- a/flang-rt/lib/runtime/stop.cpp
+++ b/flang-rt/lib/runtime/stop.cpp
@@ -102,10 +102,15 @@ static void CloseAllExternalUnits(const char *why) {
std::fputc('\n', stderr);
DescribeIEEESignaledExceptions();
}
- if (isErrorStop)
+ if (isErrorStop) {
+#ifdef FLANG_RT_HAVE_CSIGNAL
+ Fortran::runtime::PrintFatalBacktrace(
+ "\nError termination. Backtrace:\n");
+#endif
Fortran::runtime::ErrorExit(code);
- else
+ } else {
Fortran::runtime::NormalExit(code);
+ }
#endif
}
@@ -133,6 +138,10 @@ static void CloseAllExternalUnits(const char *why) {
DescribeIEEESignaledExceptions();
}
if (isErrorStop) {
+#ifdef FLANG_RT_HAVE_CSIGNAL
+ Fortran::runtime::PrintFatalBacktrace(
+ "\nError termination. Backtrace:\n");
+#endif
Fortran::runtime::ErrorExit(EXIT_FAILURE);
} else {
Fortran::runtime::NormalExit(EXIT_SUCCESS);
@@ -237,8 +246,11 @@ static RT_NOINLINE_ATTR void PrintBacktrace() {
}
[[noreturn]] RT_OPTNONE_ATTR void RTNAME(Abort)() {
-#ifdef HAVE_BACKTRACE
- PrintBacktrace();
+#ifdef FLANG_RT_HAVE_CSIGNAL
+ Fortran::runtime::PrintFatalBacktrace("\nProgram aborted. Backtrace:\n");
+ // The fatal-signal handler also traces SIGABRT. Reset it so abort() does
+ // not print a second trace.
+ std::signal(SIGABRT, SIG_DFL);
#endif
std::abort();
}
@@ -307,3 +319,98 @@ RT_EXT_API_GROUP_BEGIN
}
RT_EXT_API_GROUP_END
}
+
+#ifdef FLANG_RT_HAVE_CSIGNAL
+void Fortran::runtime::PrintFatalBacktrace(const char *heading) {
+ if (!Fortran::runtime::executionEnvironment.backtrace)
+ return;
+ if (heading)
+ std::fputs(heading, stderr);
+ PrintBacktrace();
+}
+
+static volatile std::sig_atomic_t fatalErrorInProgress{0};
+
+static const char *SignalDescription(int signum) {
+ switch (signum) {
+#ifdef SIGQUIT
+ case SIGQUIT:
+ return "SIGQUIT: Terminal quit signal";
+#endif
+ case SIGILL:
+ return "SIGILL: Illegal instruction";
+ case SIGABRT:
+ return "SIGABRT: Process abort signal";
+ case SIGFPE:
+ return "SIGFPE: Floating-point exception";
+ case SIGSEGV:
+ return "SIGSEGV: Segmentation fault";
+#ifdef SIGBUS
+ case SIGBUS:
+ return "SIGBUS: Access to an undefined portion of a memory object";
+#endif
+#ifdef SIGSYS
+ case SIGSYS:
+ return "SIGSYS: Bad system call";
+#endif
+#ifdef SIGTRAP
+ case SIGTRAP:
+ return "SIGTRAP: Trace/breakpoint trap";
+#endif
+#ifdef SIGXCPU
+ case SIGXCPU:
+ return "SIGXCPU: CPU time limit exceeded";
+#endif
+#ifdef SIGXFSZ
+ case SIGXFSZ:
+ return "SIGXFSZ: File size limit exceeded";
+#endif
+ default:
+ return nullptr;
+ }
+}
+
+static void BacktraceSignalHandler(int signum) {
+ if (fatalErrorInProgress)
+ std::raise(signum);
+ fatalErrorInProgress = 1;
+ if (const char *desc{SignalDescription(signum)}) {
+ std::fprintf(stderr, "\nProgram received signal %s.\n", desc);
+ } else {
+ std::fprintf(stderr, "\nProgram received signal %d.\n", signum);
+ }
+ std::fputs("\nBacktrace for this error:\n", stderr);
+ PrintBacktrace();
+ std::signal(signum, SIG_DFL);
+ std::raise(signum);
+}
+
+static void InstallOneBacktraceHandler(int signum) {
+ std::signal(signum, BacktraceSignalHandler);
+}
+
+void Fortran::runtime::InstallFatalBacktraceHandlers() {
+#ifdef SIGQUIT
+ InstallOneBacktraceHandler(SIGQUIT);
+#endif
+ InstallOneBacktraceHandler(SIGILL);
+ InstallOneBacktraceHandler(SIGABRT);
+ InstallOneBacktraceHandler(SIGFPE);
+ InstallOneBacktraceHandler(SIGSEGV);
+#ifdef SIGBUS
+ InstallOneBacktraceHandler(SIGBUS);
+#endif
+#ifdef SIGSYS
+ InstallOneBacktraceHandler(SIGSYS);
+#endif
+#ifdef SIGTRAP
+ InstallOneBacktraceHandler(SIGTRAP);
+#endif
+#ifdef SIGXCPU
+ InstallOneBacktraceHandler(SIGXCPU);
+#endif
+#ifdef SIGXFSZ
+ InstallOneBacktraceHandler(SIGXFSZ);
+#endif
+}
+#endif
diff --git a/flang-rt/lib/runtime/terminator.cpp b/flang-rt/lib/runtime/terminator.cpp
index 2c06c8de74d0f..73997fd950920 100644
--- a/flang-rt/lib/runtime/terminator.cpp
+++ b/flang-rt/lib/runtime/terminator.cpp
@@ -75,6 +75,12 @@ RT_API_ATTRS void Terminator::CrashHeader() const {
// FIXME: re-enable the flush along with the IO enabling.
io::FlushOutputOnCrash(*this);
#endif
+#ifdef FLANG_RT_HAVE_CSIGNAL
+ // Print before abort(). Reset SIGABRT so the fatal-signal handler does not
+ // print a second trace. Both are compiled only where <csignal> is included.
+ PrintFatalBacktrace("\nError termination. Backtrace:\n");
+ std::signal(SIGABRT, SIG_DFL);
+#endif
#endif
NotifyOtherImagesOfErrorTermination(EXIT_FAILURE);
#if defined(RT_DEVICE_COMPILATION)
diff --git a/flang/docs/ReleaseNotes.md b/flang/docs/ReleaseNotes.md
index f7181b1fe5b47..7058cf308aa48 100644
--- a/flang/docs/ReleaseNotes.md
+++ b/flang/docs/ReleaseNotes.md
@@ -142,6 +142,12 @@ page](https://llvm.org/releases/).
`-Wno-out-of-bounds-subscripts` to silence the warning.
## New Compiler Flags
+- Added `-fbacktrace` and `-fno-backtrace`. A fatal runtime error, `ERROR STOP`,
+ `ABORT`, or a deadly signal prints a stack trace. This is the default.
+ `-fno-backtrace` disables those traces. `CALL BACKTRACE()` still prints one.
+ `FLANG_ERROR_BACKTRACE` overrides the option when it is already set. See
+ [RuntimeEnvironment.md](RuntimeEnvironment.md).
+
- Added `-fno-out-of-bounds-subscripts`, which restores the previous behavior of
rejecting an out-of-range constant subscript with an error. See the entry above
for the change in default behavior.
diff --git a/flang/docs/RuntimeEnvironment.md b/flang/docs/RuntimeEnvironment.md
index 8b1ead298f45d..b39c243476f57 100644
--- a/flang/docs/RuntimeEnvironment.md
+++ b/flang/docs/RuntimeEnvironment.md
@@ -100,6 +100,24 @@ treated as big-endian for both input and output, while units 26 and 27 will be
treated as little-endian for both input and output.
+## `FLANG_ERROR_BACKTRACE`
+
+Controls the stack trace printed for a fatal runtime error, an `ERROR STOP`
+statement, the `ABORT` extension, or a deadly signal such as `SIGSEGV` or
+`SIGFPE`. A normal `STOP` statement does not print a trace.
+`CALL BACKTRACE()` always prints one, whether or not this variable disables
+the others.
+
+Only the first character is significant. `1`, `Y`, or `y` enables the trace,
+and `0`, `N`, or `n` disables it. Any other value is ignored. When the
+variable is unset, the trace is enabled.
+
+`-fbacktrace` is the compiler default and does not set the variable.
+`-fno-backtrace` sets `FLANG_ERROR_BACKTRACE=0` only when the variable is not
+already set, so a value in the environment wins over the option. The variable
+is not read when the runtime is built for a GPU, and signal handlers are not
+installed there.
+
## `FLANG_RT_COPYOUT_MODIFIED_ONLY`
The system environment variable `FLANG_RT_COPYOUT_MODIFIED_ONLY` selects how
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp
index efbb938f6b597..f6f87423f62a8 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -924,6 +924,13 @@ static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
}
}
+ // -fbacktrace is the default, matching gfortran. -fno-backtrace is passed to
+ // the runtime by setting FLANG_ERROR_BACKTRACE when that variable is not
+ // already set, so an explicit environment value still wins.
+ if (!args.hasFlag(clang::options::OPT_fbacktrace,
+ clang::options::OPT_fno_backtrace, /*Default=*/true))
+ opts.envDefaults.push_back({"FLANG_ERROR_BACKTRACE", "0"});
+
// Set conversion based on -fconvert=<value>
if (const auto *arg = args.getLastArg(clang::options::OPT_fconvert_EQ)) {
const char *argValue = arg->getValue();
diff --git a/flang/test/Driver/fbacktrace.f90 b/flang/test/Driver/fbacktrace.f90
new file mode 100644
index 0000000000000..05e3b1c9290a2
--- /dev/null
+++ b/flang/test/Driver/fbacktrace.f90
@@ -0,0 +1,22 @@
+! Test -f[no-]backtrace driver forwarding to flang -fc1.
+! An explicit -fbacktrace or -fno-backtrace is forwarded. The last flag wins.
+! The default passes neither flag, and the frontend leaves the trace on.
+
+! RUN: %flang -### %s 2>&1 | FileCheck %s --check-prefixes=FC1,DEFAULT
+! RUN: %flang -### -fno-backtrace %s 2>&1 | FileCheck %s --check-prefixes=FC1,NO-BACKTRACE
+! RUN: %flang -### -fbacktrace -fno-backtrace %s 2>&1 | FileCheck %s --check-prefixes=FC1,NO-BACKTRACE
+! RUN: %flang -### -fbacktrace %s 2>&1 | FileCheck %s --check-prefixes=FC1,BACKTRACE
+! RUN: %flang -### -fno-backtrace -fbacktrace %s 2>&1 | FileCheck %s --check-prefixes=FC1,BACKTRACE
+
+! The frontend accepts both flags.
+! RUN: %flang_fc1 -emit-hlfir -fbacktrace %s -o -
+! RUN: %flang_fc1 -emit-hlfir -fno-backtrace %s -o -
+
+! FC1: "-fc1"
+! BACKTRACE-SAME: "-fbacktrace"
+! NO-BACKTRACE-SAME: "-fno-backtrace"
+! BACKTRACE-NOT: "-fno-backtrace"
+! DEFAULT-NOT: "-fno-backtrace"
+! DEFAULT-NOT: "-fbacktrace"
+
+end program
diff --git a/flang/test/Lower/backtrace.f90 b/flang/test/Lower/backtrace.f90
new file mode 100644
index 0000000000000..3b69140e2fd5f
--- /dev/null
+++ b/flang/test/Lower/backtrace.f90
@@ -0,0 +1,15 @@
+! -fno-backtrace tells the runtime to disable the stack trace by setting
+! FLANG_ERROR_BACKTRACE when that variable is not already set.
+! The default and an explicit -fbacktrace do not emit a setting, and the
+! runtime leaves tracing on.
+
+! RUN: %flang_fc1 -emit-fir -o - %s | FileCheck --check-prefix=CHECK-DEFAULT %s
+! RUN: %flang_fc1 -emit-fir -fbacktrace -o - %s | FileCheck --check-prefix=CHECK-DEFAULT %s
+! RUN: %flang_fc1 -emit-fir -fno-backtrace -o - %s | FileCheck --check-prefix=CHECK-NO-BACKTRACE %s
+
+program test
+end
+
+! CHECK-DEFAULT-NOT: FLANG_ERROR_BACKTRACE
+! CHECK-NO-BACKTRACE: fir.string_lit "FLANG_ERROR_BACKTRACE\00"
+! CHECK-NO-BACKTRACE: fir.string_lit "0\00"
More information about the cfe-commits
mailing list