[clang] [flang] [Flang] Use simple summation by default at all optimization levels (PR #244546)

Tatsuhito Abe via cfe-commits cfe-commits at lists.llvm.org
Wed Dec 2 18:13:31 PST 2026


https://github.com/tatsuhito-fj updated https://github.com/llvm/llvm-project/pull/244546

>From 130736c2945f21bdb278b4914f4daab46846fc9f Mon Sep 17 00:00:00 2001
From: Tatsuhito Abe <abe.tatsuhito at fujitsu.com>
Date: Tue, 10 Nov 2026 15:00:28 +0900
Subject: [PATCH 1/5] [Flang] Use simple summation by default at all
 optimization levels

Add a scope option to SimplifyHLFIRIntrinsics and adjust the pipeline to
enable SUM expansion at -O0 while keeping other intrinsic expansions
conditional on array expression optimization. This makes simple
summation the default for SUM expansion across optimization levels.

Previously, floating-point SUM used the runtime's Kahan summation at
-O0, whereas -O1 and higher generally generated loops with simple
sequential addition. This expansion substituted a different algorithm
rather than inlining the runtime implementation, causing numerical
results to depend on the optimization level.

Add -fcompensated-sum to preserve the runtime's compensated algorithm
for REAL and COMPLEX SUM. When enabled, exclude SUM from HLFIR intrinsic
simplification and prevent SimplifyIntrinsics from replacing real SUM
runtime calls with uncompensated reduction loops.

Fixes #176282
---
 clang/include/clang/Options/FlangOptions.td   |  3 +
 clang/lib/Driver/ToolChains/Flang.cpp         |  2 +
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/include/flang/Optimizer/HLFIR/Passes.h  | 11 +++
 flang/include/flang/Optimizer/HLFIR/Passes.td | 25 +++++-
 .../flang/Optimizer/Transforms/Passes.td      |  6 +-
 flang/include/flang/Tools/CrossToolHelpers.h  |  2 +
 flang/lib/Frontend/CompilerInvocation.cpp     |  3 +
 flang/lib/Frontend/FrontendActions.cpp        |  1 +
 .../Transforms/SimplifyHLFIRIntrinsics.cpp    | 88 +++++++++++--------
 flang/lib/Optimizer/Passes/Pipelines.cpp      | 24 +++--
 .../Transforms/SimplifyIntrinsics.cpp         |  3 +
 flang/test/Driver/array-runtime.f90           | 32 +++++--
 flang/test/Driver/compensated-sum.f90         | 14 +++
 .../test/Driver/mlir-debug-pass-pipeline.f90  |  5 ++
 .../HLFIR/simplify-hlfir-intrinsics-scope.fir | 36 ++++++++
 .../parallel-private-reduction-worstcase.f90  | 47 ++++++----
 flang/test/Integration/compensated-sum.f90    | 60 +++++++++++++
 .../simplifyintrinsics-compensated-sum.fir    | 39 ++++++++
 19 files changed, 331 insertions(+), 71 deletions(-)
 create mode 100644 flang/test/Driver/compensated-sum.f90
 create mode 100644 flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir
 create mode 100644 flang/test/Integration/compensated-sum.f90
 create mode 100644 flang/test/Transforms/simplifyintrinsics-compensated-sum.fir

diff --git a/clang/include/clang/Options/FlangOptions.td b/clang/include/clang/Options/FlangOptions.td
index ad39d052bee6a..e1b8c2c42e6e6 100644
--- a/clang/include/clang/Options/FlangOptions.td
+++ b/clang/include/clang/Options/FlangOptions.td
@@ -335,6 +335,9 @@ def fcheck_integer_mod_zero_divisor
     : Flag<["-"], "fcheck-integer-mod-zero-divisor">, Group<f_Group>,
       HelpText<"Check for a zero divisor in integer MOD and MODULO">;
 
+def fcompensated_sum : Flag<["-"], "fcompensated-sum">, Group<f_Group>,
+  HelpText<"Use compensated algorithm for SUM intrinsic for REAL and COMPLEX types">;
+
 defm fp_sum_reassociation
     : BoolOptionWithoutMarshalling<
           "f", "fp-sum-reassociation",
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp
index 522907b58022f..ed3cbbfe06abf 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -391,6 +391,8 @@ void Flang::addCodegenOptions(const ArgList &Args,
   Args.AddLastArg(CmdArgs, options::OPT_ffp_sum_reassociation,
                   options::OPT_fno_fp_sum_reassociation);
 
+  Args.AddLastArg(CmdArgs, options::OPT_fcompensated_sum);
+
   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
                     options::OPT_fno_unique_internal_linkage_names);
 
diff --git a/flang/include/flang/Frontend/CodeGenOptions.def b/flang/include/flang/Frontend/CodeGenOptions.def
index 5043003feec1d..423ff7b0eda28 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -65,6 +65,7 @@ CODEGENOPT(DebugInfoForProfiling, 1, 0)  ///< Emit extra debug info to make samp
 CODEGENOPT(PseudoProbeForProfiling, 1, 0) ///< Emit pseudo probes for sample profiling.
 CODEGENOPT(UniqueInternalLinkageNames, 1, 0) ///< Append MD5 hash to internal linkage symbols.
 CODEGENOPT(ImplicitDefaultMapperAllocatableMembers, 1, 1) ///< Map allocatable members in generated OpenMP default mappers.
+CODEGENOPT(CompensatedSum, 1, 0) ///< Use compensated algorithm for SUM for REAL and COMPLEX.
 
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(FPMaxminBehavior, Fortran::common::FPMaxminBehavior, 2, Fortran::common::FPMaxminBehavior::Legacy)
diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.h b/flang/include/flang/Optimizer/HLFIR/Passes.h
index d009a31582470..3d9e4b12e06ff 100644
--- a/flang/include/flang/Optimizer/HLFIR/Passes.h
+++ b/flang/include/flang/Optimizer/HLFIR/Passes.h
@@ -21,6 +21,17 @@
 #include <memory>
 
 namespace hlfir {
+  /// Specifies the scope to which SimplifyHLFIRIntrinsics applies.
+  enum class HLFIRIntrinsicSimplificationScope {
+    /// Apply SimplifyHLFIRIntrinsics to all intrinsics.
+    All,
+    /// Apply SimplifyHLFIRIntrinsics only to sum intrinsics.
+    SumOnly,
+    /// Apply SimplifyHLFIRIntrinsics to all intrinsics except sum intrinsics.
+    ExceptSum,
+    /// Do not apply SimplifyHLFIRIntrinsics to any intrinsics.
+    None,
+  };
 #define GEN_PASS_DECL
 #define GEN_PASS_REGISTRATION
 #include "flang/Optimizer/HLFIR/Passes.h.inc"
diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.td b/flang/include/flang/Optimizer/HLFIR/Passes.td
index e0221c655834f..b31f0ca75a6a6 100644
--- a/flang/include/flang/Optimizer/HLFIR/Passes.td
+++ b/flang/include/flang/Optimizer/HLFIR/Passes.td
@@ -75,7 +75,30 @@ def SimplifyHLFIRIntrinsics : Pass<"simplify-hlfir-intrinsics"> {
                clEnumValN(Fortran::common::FPMaxminBehavior::Extremum,
                           "extremum", "arith.max/minimumf"),
                clEnumValN(Fortran::common::FPMaxminBehavior::ExtremeNum,
-                          "extremenum", "arith.max/minnumf"))}]>];
+                          "extremenum", "arith.max/minnumf"))}]>,
+                 Option<"scope", "scope",
+                        "::hlfir::HLFIRIntrinsicSimplificationScope",
+                        /*default=*/"::hlfir::HLFIRIntrinsicSimplificationScope::"
+                                    "All",
+                        "Select which HLFIR intrinsic operations to simplify",
+                        [{::llvm::cl::values(
+                          clEnumValN(
+                            ::hlfir::HLFIRIntrinsicSimplificationScope::All,
+                            "all",
+                            "Simplify all supported HLFIR intrinsic operations"),
+                          clEnumValN(
+                            ::hlfir::HLFIRIntrinsicSimplificationScope::SumOnly,
+                            "only-sum",
+                            "Simplify only hlfir.sum operations"),
+                          clEnumValN(
+                            ::hlfir::HLFIRIntrinsicSimplificationScope::ExceptSum,
+                            "except-sum",
+                            "Simplify all supported HLFIR intrinsic operations "
+                            "except hlfir.sum"),
+                          clEnumValN(
+                            ::hlfir::HLFIRIntrinsicSimplificationScope::None,
+                            "none",
+                            "Do not simplify any HLFIR intrinsic operations"))}]>];
 }
 
 def ExpressionSimplification : Pass<"hlfir-expression-simplification"> {
diff --git a/flang/include/flang/Optimizer/Transforms/Passes.td b/flang/include/flang/Optimizer/Transforms/Passes.td
index 34354eb3f6fed..55480d2cc308a 100644
--- a/flang/include/flang/Optimizer/Transforms/Passes.td
+++ b/flang/include/flang/Optimizer/Transforms/Passes.td
@@ -298,7 +298,11 @@ def SimplifyIntrinsics : Pass<"simplify-intrinsics", "mlir::ModuleOp"> {
   let options = [
     Option<"enableExperimental", "enable-experimental", "bool",
            /*default=*/"false",
-           "Enable experimental code that may not always work correctly">
+           "Enable experimental code that may not always work correctly">,
+    Option<"compensatedSum", "compensated-sum", "bool",
+           /*default=*/"false",
+           "Preserve runtime calls that use compensated summation for "
+           "floating-point SUM">
   ];
 }
 
diff --git a/flang/include/flang/Tools/CrossToolHelpers.h b/flang/include/flang/Tools/CrossToolHelpers.h
index 0b11c6be04946..4f66cff187c99 100644
--- a/flang/include/flang/Tools/CrossToolHelpers.h
+++ b/flang/include/flang/Tools/CrossToolHelpers.h
@@ -150,11 +150,13 @@ struct MLIRToLLVMPassPipelineConfig : public FlangEPCallBacks {
     SplitDwarfFile = opts.SplitDwarfFile;
     DwarfDebugFlags = opts.DwarfDebugFlags;
     DebugNameTable = opts.getDebugNameTable();
+    CompensatedSum = opts.CompensatedSum;
   }
 
   llvm::OptimizationLevel OptLevel; ///< optimisation level
   /// Enable HLFIR optimizations; expensive ones still require O3.
   bool optimizeArrayExpression;
+  bool CompensatedSum = false; ///< Preserve compensated real/complex SUM.
   bool StackArrays = false; ///< convert memory allocations to alloca.
   bool EnableSafeTrampoline{false}; ///< Use runtime trampoline pool (W^X).
   bool Underscoring = true; ///< add underscores to function names.
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp
index efbb938f6b597..dc4ebdd74cc0a 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -605,6 +605,9 @@ static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
           << arg->getAsString(args) << arg->getValue();
     }
   }
+
+  if (args.hasArg(clang::options::OPT_fcompensated_sum))
+    opts.CompensatedSum = 1;
 }
 
 /// Parses all target input arguments and populates the target
diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp
index d7f6658668a40..1bf5d4787911c 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -650,6 +650,7 @@ void CodeGenAction::lowerHLFIRToFIR() {
   if (ci.getInvocation().getLangOpts().OpenMPSimd)
     enableOpenMP = fir::EnableOpenMP::Simd;
   MLIRToLLVMPassPipelineConfig config(level);
+  config.CompensatedSum = opts.CompensatedSum;
   config.fpMaxminBehavior =
       ci.getInvocation().getLoweringOpts().getFPMaxminBehavior();
   // Give plugins a chance to register passes at the extension points.
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
index 9fbc05dda264a..34495e836f82f 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
@@ -3442,44 +3442,56 @@ class SimplifyHLFIRIntrinsics
         mlir::GreedySimplifyRegionLevel::Disabled);
 
     mlir::RewritePatternSet patterns(context);
-    patterns.insert<TransposeAsElementalConversion>(context);
-    patterns.insert<ReductionConversion<hlfir::SumOp>>(context);
-    patterns.insert<ReductionConversion<hlfir::ProductOp>>(context);
-    patterns.insert<ArrayShiftConversion<hlfir::CShiftOp>>(context);
-    patterns.insert<ArrayShiftConversion<hlfir::EOShiftOp>>(context);
-    patterns.insert<CmpCharOpConversion>(context);
-    patterns.insert<IndexOpConversion>(context);
-    patterns.insert<CharTrimOpConversion>(context);
-    patterns.insert<MatmulConversion<hlfir::MatmulTransposeOp>>(context);
-    patterns.insert<ReductionConversion<hlfir::CountOp>>(context);
-    patterns.insert<ReductionConversion<hlfir::AnyOp>>(context);
-    patterns.insert<ReductionConversion<hlfir::AllOp>>(context);
-    patterns.insert<ExtremumReductionConversion<hlfir::MaxlocOp>>(
-        context, this->fpMaxminBehavior);
-    patterns.insert<ExtremumReductionConversion<hlfir::MinlocOp>>(
-        context, this->fpMaxminBehavior);
-    patterns.insert<ExtremumReductionConversion<hlfir::MaxvalOp>>(
-        context, this->fpMaxminBehavior);
-    patterns.insert<ExtremumReductionConversion<hlfir::MinvalOp>>(
-        context, this->fpMaxminBehavior);
-
-    // If forceMatmulAsElemental is false, then hlfir.matmul inlining
-    // will introduce hlfir.eval_in_mem operation with new memory side
-    // effects. This conflicts with CSE and optimized bufferization, e.g.:
-    //   A(1:N,1:N) =  A(1:N,1:N) - MATMUL(...)
-    // If we introduce hlfir.eval_in_mem before CSE, then the current
-    // MLIR CSE won't be able to optimize the trivial loads of 'N' value
-    // that happen before and after hlfir.matmul.
-    // If 'N' loads are not optimized, then the optimized bufferization
-    // won't be able to prove that the slices of A are identical
-    // on both sides of the assignment.
-    // This is actually the CSE problem, but we can work it around
-    // for the time being.
-    if (forceMatmulAsElemental || this->allowNewSideEffects)
-      patterns.insert<MatmulConversion<hlfir::MatmulOp>>(context);
-
-    patterns.insert<DotProductConversion>(context);
-    patterns.insert<ReshapeAsElementalConversion>(context);
+
+    const bool simplifySum =
+        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::All ||
+        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::SumOnly;
+    const bool simplifyOtherIntrinsics =
+        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::All ||
+        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::ExceptSum;
+
+    if (simplifySum)
+      patterns.insert<ReductionConversion<hlfir::SumOp>>(context);
+
+    if (simplifyOtherIntrinsics) {
+      patterns.insert<TransposeAsElementalConversion>(context);
+      patterns.insert<ReductionConversion<hlfir::ProductOp>>(context);
+      patterns.insert<ArrayShiftConversion<hlfir::CShiftOp>>(context);
+      patterns.insert<ArrayShiftConversion<hlfir::EOShiftOp>>(context);
+      patterns.insert<CmpCharOpConversion>(context);
+      patterns.insert<IndexOpConversion>(context);
+      patterns.insert<CharTrimOpConversion>(context);
+      patterns.insert<MatmulConversion<hlfir::MatmulTransposeOp>>(context);
+      patterns.insert<ReductionConversion<hlfir::CountOp>>(context);
+      patterns.insert<ReductionConversion<hlfir::AnyOp>>(context);
+      patterns.insert<ReductionConversion<hlfir::AllOp>>(context);
+      patterns.insert<ExtremumReductionConversion<hlfir::MaxlocOp>>(
+          context, this->fpMaxminBehavior);
+      patterns.insert<ExtremumReductionConversion<hlfir::MinlocOp>>(
+          context, this->fpMaxminBehavior);
+      patterns.insert<ExtremumReductionConversion<hlfir::MaxvalOp>>(
+          context, this->fpMaxminBehavior);
+      patterns.insert<ExtremumReductionConversion<hlfir::MinvalOp>>(
+          context, this->fpMaxminBehavior);
+
+      // If forceMatmulAsElemental is false, then hlfir.matmul inlining
+      // will introduce hlfir.eval_in_mem operation with new memory side
+      // effects. This conflicts with CSE and optimized bufferization, e.g.:
+      //   A(1:N,1:N) =  A(1:N,1:N) - MATMUL(...)
+      // If we introduce hlfir.eval_in_mem before CSE, then the current
+      // MLIR CSE won't be able to optimize the trivial loads of 'N' value
+      // that happen before and after hlfir.matmul.
+      // If 'N' loads are not optimized, then the optimized bufferization
+      // won't be able to prove that the slices of A are identical
+      // on both sides of the assignment.
+      // This is actually the CSE problem, but we can work it around
+      // for the time being.
+      if (forceMatmulAsElemental || this->allowNewSideEffects)
+        patterns.insert<MatmulConversion<hlfir::MatmulOp>>(context);
+
+      patterns.insert<DotProductConversion>(context);
+      patterns.insert<ReshapeAsElementalConversion>(context);
+    }
 
     if (mlir::failed(mlir::applyPatternsGreedily(
             getOperation(), std::move(patterns), config))) {
diff --git a/flang/lib/Optimizer/Passes/Pipelines.cpp b/flang/lib/Optimizer/Passes/Pipelines.cpp
index 55a0b85618a70..919f2f6ff4e5b 100644
--- a/flang/lib/Optimizer/Passes/Pipelines.cpp
+++ b/flang/lib/Optimizer/Passes/Pipelines.cpp
@@ -12,6 +12,7 @@
 #include "flang/Optimizer/Passes/Pipelines.h"
 #include "flang/Optimizer/Builder/MIFCommon.h"
 #include "flang/Optimizer/Dialect/FIROps.h"
+#include "flang/Optimizer/HLFIR/Passes.h"
 #include "flang/Optimizer/OpenACC/Passes.h"
 #include "mlir/Conversion/Passes.h"
 #include "mlir/Dialect/LLVMIR/Transforms/Passes.h"
@@ -208,7 +209,8 @@ void createDefaultFIRPreCFGOptimizerPassPipeline(
   pm.addPass(fir::createSimplifyRegionLite());
   if (pc.OptLevel != llvm::OptimizationLevel::O0) {
     // These passes may increase code size.
-    pm.addPass(fir::createSimplifyIntrinsics());
+    pm.addPass(fir::createSimplifyIntrinsics(
+        {/*enableExperimental=*/false, pc.CompensatedSum}));
     pm.addPass(fir::createAlgebraicSimplificationPass(config));
     if (enableConstantArgumentGlobalisation)
       pm.addPass(fir::createConstantArgumentGlobalisationOpt());
@@ -318,11 +320,21 @@ void createHLFIRToFIRPassPipeline(mlir::PassManager &pm,
     addNestedPassToAllTopLevelOperations<PassConstructor>(
         pm, hlfir::createExpressionSimplification);
     addCanonicalizerPassWithoutRegionSimplification(pm);
-    addNestedPassToAllTopLevelOperations(pm, [&]() {
-      return hlfir::createSimplifyHLFIRIntrinsics(
-          {/*allowNewSideEffects=*/false, config.fpMaxminBehavior});
-    });
   }
+
+  using ScopeKind = hlfir::HLFIRIntrinsicSimplificationScope;
+  ScopeKind scope;
+  if (config.CompensatedSum)
+    scope =
+        config.optimizeArrayExpression ? ScopeKind::ExceptSum : ScopeKind::None;
+  else
+    scope =
+        config.optimizeArrayExpression ? ScopeKind::All : ScopeKind::SumOnly;
+
+  addNestedPassToAllTopLevelOperations(pm, [&]() {
+    return hlfir::createSimplifyHLFIRIntrinsics(
+        {/*allowNewSideEffects=*/false, config.fpMaxminBehavior, scope});
+  });
   addNestedPassToAllTopLevelOperations<PassConstructor>(
       pm, hlfir::createInlineElementals);
   addNestedPassToAllTopLevelOperations<PassConstructor>(
@@ -334,7 +346,7 @@ void createHLFIRToFIRPassPipeline(mlir::PassManager &pm,
     // and allow introducing operations with new side effects.
     addNestedPassToAllTopLevelOperations(pm, [&]() {
       return hlfir::createSimplifyHLFIRIntrinsics(
-          {/*allowNewSideEffects=*/true, config.fpMaxminBehavior});
+          {/*allowNewSideEffects=*/true, config.fpMaxminBehavior, scope});
     });
     addNestedPassToAllTopLevelOperations<PassConstructor>(
         pm, hlfir::createPropagateFortranVariableAttributes);
diff --git a/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp b/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp
index 78cb92ed9a8fa..5a983942fef22 100644
--- a/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp
+++ b/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp
@@ -1290,6 +1290,9 @@ void SimplifyIntrinsicsPass::runOnOperation() {
         //                int dim, const Descriptor *mask)
         //
         if (funcName.starts_with(RTNAME_STRING(Sum))) {
+          if (this->compensatedSum && call.getNumResults() == 1 &&
+              mlir::isa<mlir::FloatType>(call.getResult(0).getType()))
+            return;
           simplifyIntOrFloatReduction(call, kindMap, genRuntimeSumBody);
           return;
         }
diff --git a/flang/test/Driver/array-runtime.f90 b/flang/test/Driver/array-runtime.f90
index 9acec878fb3da..e20f201c800f0 100644
--- a/flang/test/Driver/array-runtime.f90
+++ b/flang/test/Driver/array-runtime.f90
@@ -1,5 +1,6 @@
-! Numeric broadcasts to non-allocatable arrays are expanded even at -O0.
-! Other array operations retain the optimization-level-dependent default.
+! Numeric broadcasts to non-allocatable arrays and SUM reductions are expanded
+! even at -O0. Other array operations retain the optimization-level-dependent
+! default.
 ! RUN: %flang_fc1 -emit-fir -O0 %s -o - | FileCheck %s --check-prefixes=ALL,RUNTIME
 ! RUN: %flang_fc1 -emit-fir -O1 %s -o - | FileCheck %s --check-prefixes=ALL,EXPAND
 ! RUN: %flang_fc1 -emit-fir -O2 %s -o - | FileCheck %s --check-prefixes=ALL,EXPAND
@@ -52,14 +53,27 @@ subroutine array_expression(x, y, z)
 ! EXPAND-NOT: fir.call @_FortranAAssign
 ! ALL: return
 
-function reduction(x)
-  real :: x(:), reduction
-  reduction = sum(x)
+function sum_reduction(x)
+  real :: x(:), sum_reduction
+  sum_reduction = sum(x)
 end function
 
-! ALL-LABEL: func{{(\.func)?}} @_QPreduction(
-! RUNTIME: fir.call @_FortranASumReal4
-! EXPAND-NOT: fir.call @_FortranASum
+! ALL-LABEL: func{{(\.func)?}} @_QPsum_reduction(
+! ALL-NOT: fir.call @_FortranASum
+! ALL: fir.do_loop
+! ALL: arith.addf
+! ALL-NOT: fir.call @_FortranASum
+! ALL: return
+
+function product_reduction(x)
+  real :: x(:), product_reduction
+  product_reduction = product(x)
+end function
+
+! ALL-LABEL: func{{(\.func)?}} @_QPproduct_reduction(
+! RUNTIME: fir.call @_FortranAProductReal4
+! EXPAND-NOT: fir.call @_FortranAProduct
 ! EXPAND: fir.do_loop
-! EXPAND-NOT: fir.call @_FortranASum
+! EXPAND: arith.mulf
+! EXPAND-NOT: fir.call @_FortranAProduct
 ! ALL: return
diff --git a/flang/test/Driver/compensated-sum.f90 b/flang/test/Driver/compensated-sum.f90
new file mode 100644
index 0000000000000..f9a56b78821a9
--- /dev/null
+++ b/flang/test/Driver/compensated-sum.f90
@@ -0,0 +1,14 @@
+! Test driver handling of -fcompensated-sum.
+
+! RUN: %flang -fsyntax-only -### %s -o %t 2>&1 \
+! RUN:   | FileCheck %s --check-prefix=OMITTED
+
+! RUN: %flang -fsyntax-only -### %s -o %t 2>&1 \
+! RUN:     -fcompensated-sum \
+! RUN:   | FileCheck %s --check-prefix=ENABLED
+
+! OMITTED: "-fc1"
+! OMITTED-NOT: "-fcompensated-sum"
+
+! ENABLED: "-fc1"
+! ENABLED: "-fcompensated-sum"
diff --git a/flang/test/Driver/mlir-debug-pass-pipeline.f90 b/flang/test/Driver/mlir-debug-pass-pipeline.f90
index 25fdc4ee55780..b395d4974e74b 100644
--- a/flang/test/Driver/mlir-debug-pass-pipeline.f90
+++ b/flang/test/Driver/mlir-debug-pass-pipeline.f90
@@ -29,22 +29,27 @@
 ! ALL: Fortran::lower::VerifierPass
 ! ALL-NEXT: Pipeline Collection : ['fir.global', 'func.func', 'omp.declare_mapper', 'omp.declare_reduction', 'omp.private']
 ! ALL-NEXT: 'fir.global' Pipeline
+! ALL-NEXT:   SimplifyHLFIRIntrinsics
 ! ALL-NEXT:   InlineElementals
 ! ALL-NEXT:   SeparateAllocatableAssign
 ! ALL-NEXT:   InlineHLFIRAssign
 ! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   SimplifyHLFIRIntrinsics
 ! ALL-NEXT:   InlineElementals
 ! ALL-NEXT:   SeparateAllocatableAssign
 ! ALL-NEXT:   InlineHLFIRAssign
 ! ALL-NEXT: 'omp.declare_mapper' Pipeline
+! ALL-NEXT:   SimplifyHLFIRIntrinsics
 ! ALL-NEXT:   InlineElementals
 ! ALL-NEXT:   SeparateAllocatableAssign
 ! ALL-NEXT:   InlineHLFIRAssign
 ! ALL-NEXT: 'omp.declare_reduction' Pipeline
+! ALL-NEXT:   SimplifyHLFIRIntrinsics
 ! ALL-NEXT:   InlineElementals
 ! ALL-NEXT:   SeparateAllocatableAssign
 ! ALL-NEXT:   InlineHLFIRAssign
 ! ALL-NEXT: 'omp.private' Pipeline
+! ALL-NEXT:   SimplifyHLFIRIntrinsics
 ! ALL-NEXT:   InlineElementals
 ! ALL-NEXT:   SeparateAllocatableAssign
 ! ALL-NEXT:   InlineHLFIRAssign
diff --git a/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir b/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir
new file mode 100644
index 0000000000000..3ddde409f9420
--- /dev/null
+++ b/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir
@@ -0,0 +1,36 @@
+// Test the scope option of --simplify-hlfir-intrinsics.
+// RUN: fir-opt %s --simplify-hlfir-intrinsics | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY
+// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=all | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY
+// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=only-sum | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-KEEP
+// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=except-sum | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-SIMPLIFY
+// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=none | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-KEEP
+
+func.func @sum_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 {
+  %res = hlfir.sum %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32
+  return %res : f32
+}
+// ALL-LABEL: func.func @sum_real(
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     fir.do_loop
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     arith.addf
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-KEEP-NOT:     fir.do_loop
+// SUM-KEEP:         hlfir.sum %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32
+// SUM-KEEP-NOT:     fir.do_loop
+// ALL:              return
+
+func.func @product_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 {
+  %res = hlfir.product %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32
+  return %res : f32
+}
+// ALL-LABEL: func.func @product_real(
+// OTHER-SIMPLIFY-NOT: hlfir.product
+// OTHER-SIMPLIFY:     fir.do_loop
+// OTHER-SIMPLIFY-NOT: hlfir.product
+// OTHER-SIMPLIFY:     arith.mulf
+// OTHER-SIMPLIFY-NOT: hlfir.product
+// OTHER-KEEP-NOT:     fir.do_loop
+// OTHER-KEEP:         hlfir.product %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32
+// OTHER-KEEP-NOT:     fir.do_loop
+// ALL:                return
diff --git a/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90 b/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90
index 4f86c590b7e95..21392f4f1e46d 100644
--- a/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90
+++ b/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90
@@ -162,17 +162,26 @@ subroutine worst_case(a, b, c, d)
 ! CHECK-NEXT:    br label %omp.par.region60
 
 ! CHECK:       omp.par.region60:                                 ; preds = %omp.par.region59
-!                [call SUM runtime function]
+!                [begin loop implementing SUM]
+! CHECK:         br label %omp.par.region61
+
+! CHECK:       omp.par.region61:                                 ; preds = %omp.par.region62, %omp.par.region60
+! CHECK-NEXT:    %{{.*}} = phi i64
+! CHECK-NEXT:    %{{.*}} = phi float
+! CHECK-NEXT:    %{{.*}} = phi i64
+! CHECK:         br i1 %{{.*}}, label %omp.par.region62, label %omp.par.region63
+
+! CHECK:       omp.par.region63:                                 ; preds = %omp.par.region61
 !                [if (sum(a) == 1)]
-! CHECK:         br i1 %{{.*}}, label %omp.par.region61, label %omp.par.region62
+! CHECK:         br i1 %{{.*}}, label %omp.par.region64, label %omp.par.region65
 
-! CHECK:       omp.par.region62:                                 ; preds = %omp.par.region60
-! CHECK-NEXT:    br label %omp.par.region63
+! CHECK:       omp.par.region65:                                 ; preds = %omp.par.region63
+! CHECK-NEXT:    br label %omp.par.region66
 
-! CHECK:       omp.par.region63:                                 ; preds = %omp.par.region62
+! CHECK:       omp.par.region66:                                 ; preds = %omp.par.region65
 ! CHECK-NEXT:    br label %omp.region.cont58
 
-! CHECK:       omp.region.cont58:                                ; preds = %omp.par.region63
+! CHECK:       omp.region.cont58:                                ; preds = %omp.par.region66
 !                [omp parallel region done, call into the runtime to complete reduction]
 ! CHECK:         %[[VAL_233:.*]] = call i32 @__kmpc_reduce(
 ! CHECK:         switch i32 %[[VAL_233]], label %reduce.finalize [
@@ -189,7 +198,7 @@ subroutine worst_case(a, b, c, d)
 
 !              [various blocks implementing the reduction]
 
-! CHECK:       omp.region.cont68:                                ; preds =
+! CHECK:       omp.region.cont71:                                ; preds =
 ! CHECK-NEXT:    %{{.*}} = phi ptr
 ! CHECK-NEXT:    call void @__kmpc_end_reduce(
 ! CHECK-NEXT:    br label %reduce.finalize
@@ -206,23 +215,29 @@ subroutine worst_case(a, b, c, d)
 
 ! CHECK:       omp.reduction.cleanup:                            ; preds = %.fini
 !                [null check]
-! CHECK:         br i1 %{{.*}}, label %omp.reduction.cleanup74, label %omp.reduction.cleanup75
+! CHECK:         br i1 %{{.*}}, label %omp.reduction.cleanup77, label %omp.reduction.cleanup78
 
-! CHECK:       omp.reduction.cleanup75:                          ; preds = %omp.reduction.cleanup74, %omp.reduction.cleanup
-! CHECK-NEXT:    br label %omp.region.cont73
+! CHECK:       omp.reduction.cleanup78:                          ; preds = %omp.reduction.cleanup77, %omp.reduction.cleanup
+! CHECK-NEXT:    br label %omp.region.cont76
 
-! CHECK:       omp.region.cont73:                                ; preds = %omp.reduction.cleanup75
+! CHECK:       omp.region.cont76:                                ; preds = %omp.reduction.cleanup78
 ! CHECK-NEXT:    %{{.*}} = load ptr, ptr
-! CHECK-NEXT:    br label %omp.reduction.cleanup77
+! CHECK-NEXT:    br label %omp.reduction.cleanup80
 
-! CHECK:       omp.reduction.cleanup77:                          ; preds = %omp.region.cont73
+! CHECK:       omp.reduction.cleanup80:                          ; preds = %omp.region.cont76
 !                [null check]
-! CHECK:         br i1 %{{.*}}, label %omp.reduction.cleanup78, label %omp.reduction.cleanup79
+! CHECK:         br i1 %{{.*}}, label %omp.reduction.cleanup81, label %omp.reduction.cleanup82
 
-! CHECK:       omp.par.region61:                                 ; preds = %omp.par.region60
+! CHECK:       omp.par.region64:                                 ; preds = %omp.par.region63
 ! CHECK-NEXT:    call void @_FortranAStopStatement
 ! CHECK-NEXT:    unreachable
 
+! CHECK:       omp.par.region62:                                 ; preds = %omp.par.region61
+!                [add an array element to the SUM accumulator]
+! CHECK:         %{{.*}} = load float, ptr %{{.*}}, align 4
+! CHECK-NEXT:    %{{.*}} = fadd contract float %{{.*}}, %{{.*}}
+! CHECK:         br label %omp.par.region61
+
 ! CHECK:       omp.reduction.neutral55:                          ; preds = %omp.reduction.neutral54
 ! CHECK:         store float 0.000000e+00, ptr %{{.*}}, align 4
 ! CHECK:         br label %omp.reduction.neutral54
@@ -273,5 +288,5 @@ subroutine worst_case(a, b, c, d)
 !                [var extent was non-zero: malloc a private array]
 ! CHECK:         br label %omp.private.init5
 
-! CHECK:       omp.par.exit.exitStub:                           ; preds = %omp.region.cont83
+! CHECK:       omp.par.exit.exitStub:                           ; preds = %omp.region.cont86
 ! CHECK-NEXT:    ret void
diff --git a/flang/test/Integration/compensated-sum.f90 b/flang/test/Integration/compensated-sum.f90
new file mode 100644
index 0000000000000..cb6c2d8c03e58
--- /dev/null
+++ b/flang/test/Integration/compensated-sum.f90
@@ -0,0 +1,60 @@
+!===----------------------------------------------------------------------===!
+! This directory can be used to add Integration tests involving multiple
+! stages of the compiler (for eg. from Fortran to LLVM IR). It should not
+! contain executable tests. We should only add tests here sparingly and only
+! if there is no other way to test. Repeat this message in each test that is
+! added to this directory and sub-directories.
+!===----------------------------------------------------------------------===!
+
+! RUN: %flang_fc1 -emit-llvm -O0 %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN: %flang_fc1 -emit-llvm -O1 %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN: %flang_fc1 -emit-llvm -O2 %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN: %flang_fc1 -emit-llvm -O3 %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN: %flang_fc1 -emit-llvm -O0 -fcompensated-sum %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-RUNTIME,FP-RUNTIME
+! RUN: %flang_fc1 -emit-llvm -O1 -fcompensated-sum %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+! RUN: %flang_fc1 -emit-llvm -O2 -fcompensated-sum %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+! RUN: %flang_fc1 -emit-llvm -O3 -fcompensated-sum %s -o - \
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+
+integer function sum_integer(x)
+  integer, intent(in) :: x(10)
+  sum_integer = sum(x)
+end function
+
+! CHECK-LABEL: define {{.*}}@sum_integer_(
+! INT-INLINE-NOT: @_FortranASumInteger4(
+! INT-INLINE: add {{.*}}i32
+! INT-INLINE-NOT: @_FortranASumInteger4(
+! INT-RUNTIME: call i32 @_FortranASumInteger4(
+! CHECK: ret i32
+
+real function sum_real(x)
+  real, intent(in) :: x(10)
+  sum_real = sum(x)
+end function
+
+! CHECK-LABEL: define {{.*}}@sum_real_(
+! FP-INLINE-NOT: @_FortranASumReal4(
+! FP-INLINE: fadd{{.*}}float
+! FP-INLINE-NOT: @_FortranASumReal4(
+! FP-RUNTIME: call {{.*}}@_FortranASumReal4(
+! CHECK: ret float
+
+complex function sum_complex(x)
+  complex, intent(in) :: x(10)
+  sum_complex = sum(x)
+end function
+
+! CHECK-LABEL: define {{.*}}@sum_complex_(
+! FP-INLINE-NOT: @_FortranACppSumComplex4(
+! FP-INLINE: fadd{{.*}}float
+! FP-INLINE-NOT: @_FortranACppSumComplex4(
+! FP-RUNTIME: call void @_FortranACppSumComplex4(
+! CHECK: ret
diff --git a/flang/test/Transforms/simplifyintrinsics-compensated-sum.fir b/flang/test/Transforms/simplifyintrinsics-compensated-sum.fir
new file mode 100644
index 0000000000000..f3450a046448e
--- /dev/null
+++ b/flang/test/Transforms/simplifyintrinsics-compensated-sum.fir
@@ -0,0 +1,39 @@
+// RUN: fir-opt --simplify-intrinsics %s | FileCheck %s --check-prefixes=CHECK,PLAIN
+// RUN: fir-opt --simplify-intrinsics="compensated-sum=false" %s | FileCheck %s --check-prefixes=CHECK,PLAIN
+// RUN: fir-opt --simplify-intrinsics="compensated-sum=true" %s | FileCheck %s --check-prefixes=CHECK,COMPENSATED
+
+// When compensated-sum is true, disable floating-point SUM simplification
+// while still attempting to simplify integer SUM.
+func.func @compensated_sum_mixed(%array: !fir.ref<!fir.array<10x10xf32>>,
+                                 %integers: !fir.ref<!fir.array<10xi32>>) -> (f32, i32) {
+  %c10 = arith.constant 10 : index
+  %c0 = arith.constant 0 : index
+  %dim = fir.convert %c0 : (index) -> i32
+  %line = arith.constant 1 : i32
+  %file = fir.zero_bits !fir.ref<i8>
+  %absent = fir.absent !fir.box<i1>
+  %mask = fir.convert %absent : (!fir.box<i1>) -> !fir.box<none>
+
+  %shape2d = fir.shape %c10, %c10 : (index, index) -> !fir.shape<2>
+  %box2d = fir.embox %array(%shape2d) : (!fir.ref<!fir.array<10x10xf32>>, !fir.shape<2>) -> !fir.box<!fir.array<10x10xf32>>
+  %array_box = fir.convert %box2d : (!fir.box<!fir.array<10x10xf32>>) -> !fir.box<none>
+  %sum_real = fir.call @_FortranASumReal4(%array_box, %file, %line, %dim, %mask) : (!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> f32
+
+  %shape1d = fir.shape %c10 : (index) -> !fir.shape<1>
+  %ibox = fir.embox %integers(%shape1d) : (!fir.ref<!fir.array<10xi32>>, !fir.shape<1>) -> !fir.box<!fir.array<10xi32>>
+  %integer_box = fir.convert %ibox : (!fir.box<!fir.array<10xi32>>) -> !fir.box<none>
+  %sum_integer = fir.call @_FortranASumInteger4(%integer_box, %file, %line, %dim, %mask) : (!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> i32
+
+  return %sum_real, %sum_integer : f32, i32
+}
+
+// CHECK-LABEL: func.func @compensated_sum_mixed(
+// PLAIN:       %[[SUM_REAL:.*]] = fir.call @_FortranASumReal4x2_simplified(%{{.*}}) : (!fir.box<none>) -> f32
+// PLAIN-NOT: fir.call @_FortranASumReal{{[0-9]+}}(
+// COMPENSATED: %[[SUM_REAL:.*]] = fir.call @_FortranASumReal4(%{{.*}}) : (!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> f32
+// COMPENSATED-NOT: _FortranASumReal{{.*}}_simplified
+// CHECK:       %[[SUM_INTEGER:.*]] = fir.call @_FortranASumInteger4x1_simplified(%{{.*}}) : (!fir.box<none>) -> i32
+// CHECK:       return %[[SUM_REAL]], %[[SUM_INTEGER]] : f32, i32
+
+func.func private @_FortranASumReal4(!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> f32 attributes {fir.runtime}
+func.func private @_FortranASumInteger4(!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> i32 attributes {fir.runtime}

>From 483670a40bf6229dc3dd0cf62778423b2dc0989e Mon Sep 17 00:00:00 2001
From: Tatsuhito Abe <abe.tatsuhito at fujitsu.com>
Date: Fri, 20 Nov 2026 19:17:20 +0900
Subject: [PATCH 2/5] Fix clang-format issues

---
 flang/include/flang/Optimizer/HLFIR/Passes.h | 22 ++++++++++----------
 1 file changed, 11 insertions(+), 11 deletions(-)

diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.h b/flang/include/flang/Optimizer/HLFIR/Passes.h
index 3d9e4b12e06ff..26a757b2b2a51 100644
--- a/flang/include/flang/Optimizer/HLFIR/Passes.h
+++ b/flang/include/flang/Optimizer/HLFIR/Passes.h
@@ -21,17 +21,17 @@
 #include <memory>
 
 namespace hlfir {
-  /// Specifies the scope to which SimplifyHLFIRIntrinsics applies.
-  enum class HLFIRIntrinsicSimplificationScope {
-    /// Apply SimplifyHLFIRIntrinsics to all intrinsics.
-    All,
-    /// Apply SimplifyHLFIRIntrinsics only to sum intrinsics.
-    SumOnly,
-    /// Apply SimplifyHLFIRIntrinsics to all intrinsics except sum intrinsics.
-    ExceptSum,
-    /// Do not apply SimplifyHLFIRIntrinsics to any intrinsics.
-    None,
-  };
+/// Specifies the scope to which SimplifyHLFIRIntrinsics applies.
+enum class HLFIRIntrinsicSimplificationScope {
+  /// Apply SimplifyHLFIRIntrinsics to all intrinsics.
+  All,
+  /// Apply SimplifyHLFIRIntrinsics only to sum intrinsics.
+  SumOnly,
+  /// Apply SimplifyHLFIRIntrinsics to all intrinsics except sum intrinsics.
+  ExceptSum,
+  /// Do not apply SimplifyHLFIRIntrinsics to any intrinsics.
+  None,
+};
 #define GEN_PASS_DECL
 #define GEN_PASS_REGISTRATION
 #include "flang/Optimizer/HLFIR/Passes.h.inc"

>From 889f675bad4b27bda7ba81f6f231b40552fd1679 Mon Sep 17 00:00:00 2001
From: Tatsuhito Abe <abe.tatsuhito at fujitsu.com>
Date: Wed, 25 Nov 2026 09:31:30 +0900
Subject: [PATCH 3/5] [Flang] Refactor HLFIR intrinsic simplification options

---
 flang/include/flang/Optimizer/HLFIR/Passes.h  | 11 ---
 flang/include/flang/Optimizer/HLFIR/Passes.td | 30 ++------
 .../Transforms/SimplifyHLFIRIntrinsics.cpp    | 27 +++++---
 flang/lib/Optimizer/Passes/Pipelines.cpp      | 28 ++++----
 ...plify-hlfir-intrinsics-compensated-sum.fir | 68 +++++++++++++++++++
 .../HLFIR/simplify-hlfir-intrinsics-scope.fir | 36 ----------
 flang/test/Integration/compensated-sum.f90    |  3 +-
 7 files changed, 105 insertions(+), 98 deletions(-)
 create mode 100644 flang/test/HLFIR/simplify-hlfir-intrinsics-compensated-sum.fir
 delete mode 100644 flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir

diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.h b/flang/include/flang/Optimizer/HLFIR/Passes.h
index 26a757b2b2a51..d009a31582470 100644
--- a/flang/include/flang/Optimizer/HLFIR/Passes.h
+++ b/flang/include/flang/Optimizer/HLFIR/Passes.h
@@ -21,17 +21,6 @@
 #include <memory>
 
 namespace hlfir {
-/// Specifies the scope to which SimplifyHLFIRIntrinsics applies.
-enum class HLFIRIntrinsicSimplificationScope {
-  /// Apply SimplifyHLFIRIntrinsics to all intrinsics.
-  All,
-  /// Apply SimplifyHLFIRIntrinsics only to sum intrinsics.
-  SumOnly,
-  /// Apply SimplifyHLFIRIntrinsics to all intrinsics except sum intrinsics.
-  ExceptSum,
-  /// Do not apply SimplifyHLFIRIntrinsics to any intrinsics.
-  None,
-};
 #define GEN_PASS_DECL
 #define GEN_PASS_REGISTRATION
 #include "flang/Optimizer/HLFIR/Passes.h.inc"
diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.td b/flang/include/flang/Optimizer/HLFIR/Passes.td
index b31f0ca75a6a6..0b2c606b16165 100644
--- a/flang/include/flang/Optimizer/HLFIR/Passes.td
+++ b/flang/include/flang/Optimizer/HLFIR/Passes.td
@@ -76,29 +76,13 @@ def SimplifyHLFIRIntrinsics : Pass<"simplify-hlfir-intrinsics"> {
                           "extremum", "arith.max/minimumf"),
                clEnumValN(Fortran::common::FPMaxminBehavior::ExtremeNum,
                           "extremenum", "arith.max/minnumf"))}]>,
-                 Option<"scope", "scope",
-                        "::hlfir::HLFIRIntrinsicSimplificationScope",
-                        /*default=*/"::hlfir::HLFIRIntrinsicSimplificationScope::"
-                                    "All",
-                        "Select which HLFIR intrinsic operations to simplify",
-                        [{::llvm::cl::values(
-                          clEnumValN(
-                            ::hlfir::HLFIRIntrinsicSimplificationScope::All,
-                            "all",
-                            "Simplify all supported HLFIR intrinsic operations"),
-                          clEnumValN(
-                            ::hlfir::HLFIRIntrinsicSimplificationScope::SumOnly,
-                            "only-sum",
-                            "Simplify only hlfir.sum operations"),
-                          clEnumValN(
-                            ::hlfir::HLFIRIntrinsicSimplificationScope::ExceptSum,
-                            "except-sum",
-                            "Simplify all supported HLFIR intrinsic operations "
-                            "except hlfir.sum"),
-                          clEnumValN(
-                            ::hlfir::HLFIRIntrinsicSimplificationScope::None,
-                            "none",
-                            "Do not simplify any HLFIR intrinsic operations"))}]>];
+                 Option<"onlySum", "only-sum", "bool",
+                        /*default=*/"false",
+                        "Simplify only hlfir.sum operations">,
+                 Option<"compensatedSum", "compensated-sum", "bool",
+                        /*default=*/"false",
+                        "Preserve runtime calls for real and complex SUM "
+                        "that use compensated summation">];
 }
 
 def ExpressionSimplification : Pass<"hlfir-expression-simplification"> {
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
index 34495e836f82f..797614e9dbcd5 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
@@ -1362,7 +1362,8 @@ mlir::Value ReductionAsElementalConverter::genMaskValue(
 template <typename Op>
 class ReductionConversion : public mlir::OpRewritePattern<Op> {
 public:
-  using mlir::OpRewritePattern<Op>::OpRewritePattern;
+  ReductionConversion(mlir::MLIRContext *context, bool compensatedSum = false)
+      : mlir::OpRewritePattern<Op>{context}, compensatedSum{compensatedSum} {}
 
   llvm::LogicalResult
   matchAndRewrite(Op op, mlir::PatternRewriter &rewriter) const override {
@@ -1374,6 +1375,14 @@ class ReductionConversion : public mlir::OpRewritePattern<Op> {
       AllAnyAsElementalConverter<Op> converter(op, rewriter);
       return converter.convert();
     } else if constexpr (std::is_same_v<Op, hlfir::SumOp>) {
+      mlir::Type elementType =
+          hlfir::getFortranElementType(op.getResult().getType());
+
+      if (compensatedSum &&
+          mlir::isa<mlir::FloatType, mlir::ComplexType>(elementType))
+        return rewriter.notifyMatchFailure(
+            op, "preserve compensated real or complex SUM");
+
       SumAsElementalConverter converter{op, rewriter};
       return converter.convert();
     } else if constexpr (std::is_same_v<Op, hlfir::ProductOp>) {
@@ -1382,6 +1391,9 @@ class ReductionConversion : public mlir::OpRewritePattern<Op> {
     }
     return rewriter.notifyMatchFailure(op, "unexpected reduction operation");
   }
+
+private:
+  bool compensatedSum;
 };
 
 /// Convert an operation that is a partial or total max/min reduction
@@ -3443,17 +3455,10 @@ class SimplifyHLFIRIntrinsics
 
     mlir::RewritePatternSet patterns(context);
 
-    const bool simplifySum =
-        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::All ||
-        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::SumOnly;
-    const bool simplifyOtherIntrinsics =
-        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::All ||
-        this->scope == hlfir::HLFIRIntrinsicSimplificationScope::ExceptSum;
-
-    if (simplifySum)
-      patterns.insert<ReductionConversion<hlfir::SumOp>>(context);
+    patterns.insert<ReductionConversion<hlfir::SumOp>>(context,
+                                                       this->compensatedSum);
 
-    if (simplifyOtherIntrinsics) {
+    if (!this->onlySum) {
       patterns.insert<TransposeAsElementalConversion>(context);
       patterns.insert<ReductionConversion<hlfir::ProductOp>>(context);
       patterns.insert<ArrayShiftConversion<hlfir::CShiftOp>>(context);
diff --git a/flang/lib/Optimizer/Passes/Pipelines.cpp b/flang/lib/Optimizer/Passes/Pipelines.cpp
index 919f2f6ff4e5b..e24410fa375d6 100644
--- a/flang/lib/Optimizer/Passes/Pipelines.cpp
+++ b/flang/lib/Optimizer/Passes/Pipelines.cpp
@@ -12,7 +12,6 @@
 #include "flang/Optimizer/Passes/Pipelines.h"
 #include "flang/Optimizer/Builder/MIFCommon.h"
 #include "flang/Optimizer/Dialect/FIROps.h"
-#include "flang/Optimizer/HLFIR/Passes.h"
 #include "flang/Optimizer/OpenACC/Passes.h"
 #include "mlir/Conversion/Passes.h"
 #include "mlir/Dialect/LLVMIR/Transforms/Passes.h"
@@ -320,21 +319,19 @@ void createHLFIRToFIRPassPipeline(mlir::PassManager &pm,
     addNestedPassToAllTopLevelOperations<PassConstructor>(
         pm, hlfir::createExpressionSimplification);
     addCanonicalizerPassWithoutRegionSimplification(pm);
+    addNestedPassToAllTopLevelOperations(pm, [&]() {
+      return hlfir::createSimplifyHLFIRIntrinsics(
+          {/*allowNewSideEffects=*/false, config.fpMaxminBehavior,
+           /*onlySum=*/false, config.CompensatedSum});
+    });
+  } else {
+    addNestedPassToAllTopLevelOperations(pm, [&]() {
+      return hlfir::createSimplifyHLFIRIntrinsics(
+          {/*allowNewSideEffects=*/false, config.fpMaxminBehavior,
+           /*onlySum=*/true, config.CompensatedSum});
+    });
   }
 
-  using ScopeKind = hlfir::HLFIRIntrinsicSimplificationScope;
-  ScopeKind scope;
-  if (config.CompensatedSum)
-    scope =
-        config.optimizeArrayExpression ? ScopeKind::ExceptSum : ScopeKind::None;
-  else
-    scope =
-        config.optimizeArrayExpression ? ScopeKind::All : ScopeKind::SumOnly;
-
-  addNestedPassToAllTopLevelOperations(pm, [&]() {
-    return hlfir::createSimplifyHLFIRIntrinsics(
-        {/*allowNewSideEffects=*/false, config.fpMaxminBehavior, scope});
-  });
   addNestedPassToAllTopLevelOperations<PassConstructor>(
       pm, hlfir::createInlineElementals);
   addNestedPassToAllTopLevelOperations<PassConstructor>(
@@ -346,7 +343,8 @@ void createHLFIRToFIRPassPipeline(mlir::PassManager &pm,
     // and allow introducing operations with new side effects.
     addNestedPassToAllTopLevelOperations(pm, [&]() {
       return hlfir::createSimplifyHLFIRIntrinsics(
-          {/*allowNewSideEffects=*/true, config.fpMaxminBehavior, scope});
+          {/*allowNewSideEffects=*/true, config.fpMaxminBehavior,
+           /*onlySum=*/false, config.CompensatedSum});
     });
     addNestedPassToAllTopLevelOperations<PassConstructor>(
         pm, hlfir::createPropagateFortranVariableAttributes);
diff --git a/flang/test/HLFIR/simplify-hlfir-intrinsics-compensated-sum.fir b/flang/test/HLFIR/simplify-hlfir-intrinsics-compensated-sum.fir
new file mode 100644
index 0000000000000..970ecee9fa304
--- /dev/null
+++ b/flang/test/HLFIR/simplify-hlfir-intrinsics-compensated-sum.fir
@@ -0,0 +1,68 @@
+// Test SUM inlining and pattern selection independently.
+// RUN: fir-opt %s --simplify-hlfir-intrinsics | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY
+// RUN: fir-opt %s --simplify-hlfir-intrinsics="only-sum=false compensated-sum=false" | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY
+// RUN: fir-opt %s --simplify-hlfir-intrinsics="only-sum=true compensated-sum=false" | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-KEEP
+// RUN: fir-opt %s --simplify-hlfir-intrinsics="only-sum=false compensated-sum=true" | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-SIMPLIFY
+// RUN: fir-opt %s --simplify-hlfir-intrinsics="only-sum=true compensated-sum=true" | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-KEEP
+
+func.func @sum_integer(%arg0: !fir.box<!fir.array<?xi32>>) -> i32 {
+  %res = hlfir.sum %arg0 : (!fir.box<!fir.array<?xi32>>) -> i32
+  return %res : i32
+}
+// ALL-LABEL: func.func @sum_integer(
+// ALL-NOT:   hlfir.sum
+// ALL:       fir.do_loop
+// ALL-NOT:   hlfir.sum
+// ALL:       arith.addi
+// ALL-NOT:   hlfir.sum
+// ALL:       return
+
+func.func @sum_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 {
+  %res = hlfir.sum %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32
+  return %res : f32
+}
+// ALL-LABEL: func.func @sum_real(
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     fir.do_loop
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     arith.addf
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-KEEP-NOT:     fir.do_loop
+// SUM-KEEP:         hlfir.sum %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32
+// SUM-KEEP-NOT:     fir.do_loop
+// ALL:              return
+
+func.func @sum_complex_dim(%arg0: !fir.box<!fir.array<?x3xcomplex<f64>>>) -> !hlfir.expr<3xcomplex<f64>> {
+  %dim = arith.constant 1 : i32
+  %res = hlfir.sum %arg0 dim %dim : (!fir.box<!fir.array<?x3xcomplex<f64>>>, i32) -> !hlfir.expr<3xcomplex<f64>>
+  return %res : !hlfir.expr<3xcomplex<f64>>
+}
+// ALL-LABEL: func.func @sum_complex_dim(
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     hlfir.elemental
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     fir.do_loop
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-SIMPLIFY:     fir.addc
+// SUM-SIMPLIFY-NOT: hlfir.sum
+// SUM-KEEP-NOT:     hlfir.elemental
+// SUM-KEEP-NOT:     fir.do_loop
+// SUM-KEEP:         hlfir.sum
+// SUM-KEEP-NOT:     hlfir.elemental
+// SUM-KEEP-NOT:     fir.do_loop
+// ALL:              return
+
+func.func @product_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 {
+  %res = hlfir.product %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32
+  return %res : f32
+}
+// ALL-LABEL: func.func @product_real(
+// OTHER-SIMPLIFY-NOT: hlfir.product
+// OTHER-SIMPLIFY:     fir.do_loop
+// OTHER-SIMPLIFY-NOT: hlfir.product
+// OTHER-SIMPLIFY:     arith.mulf
+// OTHER-SIMPLIFY-NOT: hlfir.product
+// OTHER-KEEP-NOT:     fir.do_loop
+// OTHER-KEEP:         hlfir.product %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32
+// OTHER-KEEP-NOT:     fir.do_loop
+// ALL:                return
diff --git a/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir b/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir
deleted file mode 100644
index 3ddde409f9420..0000000000000
--- a/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir
+++ /dev/null
@@ -1,36 +0,0 @@
-// Test the scope option of --simplify-hlfir-intrinsics.
-// RUN: fir-opt %s --simplify-hlfir-intrinsics | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY
-// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=all | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY
-// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=only-sum | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-KEEP
-// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=except-sum | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-SIMPLIFY
-// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=none | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-KEEP
-
-func.func @sum_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 {
-  %res = hlfir.sum %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32
-  return %res : f32
-}
-// ALL-LABEL: func.func @sum_real(
-// SUM-SIMPLIFY-NOT: hlfir.sum
-// SUM-SIMPLIFY:     fir.do_loop
-// SUM-SIMPLIFY-NOT: hlfir.sum
-// SUM-SIMPLIFY:     arith.addf
-// SUM-SIMPLIFY-NOT: hlfir.sum
-// SUM-KEEP-NOT:     fir.do_loop
-// SUM-KEEP:         hlfir.sum %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32
-// SUM-KEEP-NOT:     fir.do_loop
-// ALL:              return
-
-func.func @product_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 {
-  %res = hlfir.product %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32
-  return %res : f32
-}
-// ALL-LABEL: func.func @product_real(
-// OTHER-SIMPLIFY-NOT: hlfir.product
-// OTHER-SIMPLIFY:     fir.do_loop
-// OTHER-SIMPLIFY-NOT: hlfir.product
-// OTHER-SIMPLIFY:     arith.mulf
-// OTHER-SIMPLIFY-NOT: hlfir.product
-// OTHER-KEEP-NOT:     fir.do_loop
-// OTHER-KEEP:         hlfir.product %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32
-// OTHER-KEEP-NOT:     fir.do_loop
-// ALL:                return
diff --git a/flang/test/Integration/compensated-sum.f90 b/flang/test/Integration/compensated-sum.f90
index cb6c2d8c03e58..f60d653ebc1f6 100644
--- a/flang/test/Integration/compensated-sum.f90
+++ b/flang/test/Integration/compensated-sum.f90
@@ -15,7 +15,7 @@
 ! RUN: %flang_fc1 -emit-llvm -O3 %s -o - \
 ! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
 ! RUN: %flang_fc1 -emit-llvm -O0 -fcompensated-sum %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-RUNTIME,FP-RUNTIME
+! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
 ! RUN: %flang_fc1 -emit-llvm -O1 -fcompensated-sum %s -o - \
 ! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
 ! RUN: %flang_fc1 -emit-llvm -O2 -fcompensated-sum %s -o - \
@@ -32,7 +32,6 @@ integer function sum_integer(x)
 ! INT-INLINE-NOT: @_FortranASumInteger4(
 ! INT-INLINE: add {{.*}}i32
 ! INT-INLINE-NOT: @_FortranASumInteger4(
-! INT-RUNTIME: call i32 @_FortranASumInteger4(
 ! CHECK: ret i32
 
 real function sum_real(x)

>From a2f6809293de22c2fa44be2d1000b8d6bb25643d Mon Sep 17 00:00:00 2001
From: Tatsuhito Abe <abe.tatsuhito at fujitsu.com>
Date: Wed, 2 Dec 2026 10:11:37 +0900
Subject: [PATCH 4/5] [Flang] Document -fcompensated-sum and simplify its tests

---
 clang/include/clang/Options/FlangOptions.td |  6 +++++-
 flang/docs/ReleaseNotes.md                  |  5 +++++
 flang/test/Driver/compensated-sum.f90       |  5 ++---
 flang/test/Integration/compensated-sum.f90  | 22 ++++++++++-----------
 4 files changed, 23 insertions(+), 15 deletions(-)

diff --git a/clang/include/clang/Options/FlangOptions.td b/clang/include/clang/Options/FlangOptions.td
index e1b8c2c42e6e6..aa85fa0099e45 100644
--- a/clang/include/clang/Options/FlangOptions.td
+++ b/clang/include/clang/Options/FlangOptions.td
@@ -336,7 +336,11 @@ def fcheck_integer_mod_zero_divisor
       HelpText<"Check for a zero divisor in integer MOD and MODULO">;
 
 def fcompensated_sum : Flag<["-"], "fcompensated-sum">, Group<f_Group>,
-  HelpText<"Use compensated algorithm for SUM intrinsic for REAL and COMPLEX types">;
+  HelpText<"Use compensated algorithm for SUM intrinsic for REAL and COMPLEX types">,
+  DocBrief<[{Use a compensated summation algorithm for the SUM intrinsic on REAL and
+COMPLEX types. This algorithm tracks and compensates for rounding errors in
+floating-point summation, generally achieving higher accuracy than a simple
+summation algorithm. Disabled by default.}]>;
 
 defm fp_sum_reassociation
     : BoolOptionWithoutMarshalling<
diff --git a/flang/docs/ReleaseNotes.md b/flang/docs/ReleaseNotes.md
index f7181b1fe5b47..3f44c31e672a7 100644
--- a/flang/docs/ReleaseNotes.md
+++ b/flang/docs/ReleaseNotes.md
@@ -177,6 +177,11 @@ page](https://llvm.org/releases/).
   
 - Added `-b <arg>` on AIX, which passes `-b <arg>` to the linker.
 
+- Added `-fcompensated-sum` to enable compensated summation for the
+  `SUM` intrinsic on `REAL` and `COMPLEX` arrays. This can reduce the rounding
+  error that accumulates when adding array elements. The option is disabled
+  by default.
+
 ## Windows Support
 
 ## Fortran Language Changes in Flang
diff --git a/flang/test/Driver/compensated-sum.f90 b/flang/test/Driver/compensated-sum.f90
index f9a56b78821a9..ade4dfbb646c3 100644
--- a/flang/test/Driver/compensated-sum.f90
+++ b/flang/test/Driver/compensated-sum.f90
@@ -1,10 +1,9 @@
 ! Test driver handling of -fcompensated-sum.
 
-! RUN: %flang -fsyntax-only -### %s -o %t 2>&1 \
+! RUN: %flang -### %s 2>&1 \
 ! RUN:   | FileCheck %s --check-prefix=OMITTED
 
-! RUN: %flang -fsyntax-only -### %s -o %t 2>&1 \
-! RUN:     -fcompensated-sum \
+! RUN: %flang -### -fcompensated-sum %s 2>&1 \
 ! RUN:   | FileCheck %s --check-prefix=ENABLED
 
 ! OMITTED: "-fc1"
diff --git a/flang/test/Integration/compensated-sum.f90 b/flang/test/Integration/compensated-sum.f90
index f60d653ebc1f6..768fd86e29ea4 100644
--- a/flang/test/Integration/compensated-sum.f90
+++ b/flang/test/Integration/compensated-sum.f90
@@ -7,21 +7,21 @@
 !===----------------------------------------------------------------------===!
 
 ! RUN: %flang_fc1 -emit-llvm -O0 %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-INLINE
 ! RUN: %flang_fc1 -emit-llvm -O1 %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-INLINE
 ! RUN: %flang_fc1 -emit-llvm -O2 %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-INLINE
 ! RUN: %flang_fc1 -emit-llvm -O3 %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-INLINE
 ! RUN: %flang_fc1 -emit-llvm -O0 -fcompensated-sum %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-RUNTIME
 ! RUN: %flang_fc1 -emit-llvm -O1 -fcompensated-sum %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-RUNTIME
 ! RUN: %flang_fc1 -emit-llvm -O2 -fcompensated-sum %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-RUNTIME
 ! RUN: %flang_fc1 -emit-llvm -O3 -fcompensated-sum %s -o - \
-! RUN:   | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME
+! RUN:   | FileCheck %s --check-prefixes=CHECK,FP-RUNTIME
 
 integer function sum_integer(x)
   integer, intent(in) :: x(10)
@@ -29,9 +29,9 @@ integer function sum_integer(x)
 end function
 
 ! CHECK-LABEL: define {{.*}}@sum_integer_(
-! INT-INLINE-NOT: @_FortranASumInteger4(
-! INT-INLINE: add {{.*}}i32
-! INT-INLINE-NOT: @_FortranASumInteger4(
+! CHECK-NOT: @_FortranASumInteger4(
+! CHECK: add {{.*}}i32
+! CHECK-NOT: @_FortranASumInteger4(
 ! CHECK: ret i32
 
 real function sum_real(x)

>From a9449ab1636c636ea9f771a20ce1e809ec2be242 Mon Sep 17 00:00:00 2001
From: Tatsuhito Abe <abe.tatsuhito at fujitsu.com>
Date: Thu, 3 Dec 2026 10:33:16 +0900
Subject: [PATCH 5/5] Update documentation for -fcompensated-sum option

---
 clang/include/clang/Options/FlangOptions.td | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Options/FlangOptions.td b/clang/include/clang/Options/FlangOptions.td
index aa85fa0099e45..70255695e3932 100644
--- a/clang/include/clang/Options/FlangOptions.td
+++ b/clang/include/clang/Options/FlangOptions.td
@@ -340,7 +340,7 @@ def fcompensated_sum : Flag<["-"], "fcompensated-sum">, Group<f_Group>,
   DocBrief<[{Use a compensated summation algorithm for the SUM intrinsic on REAL and
 COMPLEX types. This algorithm tracks and compensates for rounding errors in
 floating-point summation, generally achieving higher accuracy than a simple
-summation algorithm. Disabled by default.}]>;
+summation algorithm. However, this algorithm is slower than a simple summation.}]>;
 
 defm fp_sum_reassociation
     : BoolOptionWithoutMarshalling<



More information about the cfe-commits mailing list