[Git][ghc/ghc][wip/sjakobi/T25450-march-native] Implement -march=native for x86/x86_64
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/T25450-march-native at Glasgow Haskell Compiler / GHC
Commits:
50b789bf by Simon Jakobi at 2026-11-23T08:17:40+01:00
Implement -march=native for x86/x86_64
-march=native detects the CPU features of the host and enables the
corresponding -m⟨feature⟩ flags.
The features are detected using GCC/Clang's __builtin_cpu_supports.
The RTS's symbol table needed to be extended with the
libgcc/compiler-rt symbols behind this builtin, so that a statically
linked GHCi, e.g. on Windows, can still load the ghc library.
As a side effect, every Haskell program on x86 now links the object
that defines these symbols and runs its initialiser, which probes the
CPU once at program start. On my machine (x86_64 Linux, GCC 13) this
adds about 5 KB and about a microsecond to a hello-world that runs for
about 2 ms.
GCC 5 and older reject some of the AVX-512 feature names that we probe
for. configure therefore requires GCC 6 now, up from 4.7.
The flag is registered in expected-undocumented-flags.txt due to #27321.
Closes #25450
Assisted-by: Claude Fable 5.2
- - - - -
19 changed files:
- + changelog.d/gcc-6-minimum
- + changelog.d/march-native
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Platform/CpuFeatures.hs
- + compiler/GHC/Platform/HostCpuFeatures.hs
- + compiler/HostCpuFeaturesX86.h
- + compiler/cbits/host_cpu_features_x86.c
- compiler/ghc.cabal.in
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/using.rst
- m4/fp_gcc_version.m4
- rts/RtsSymbols.c
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/all.T
- + testsuite/tests/driver/march_native_matches_cc.hs
- + testsuite/tests/driver/march_native_unsupported_arch.hs
- + testsuite/tests/driver/march_native_unsupported_arch.stderr
- testsuite/tests/rts/symbols/Main.hs
Changes:
=====================================
changelog.d/gcc-6-minimum
=====================================
@@ -0,0 +1,4 @@
+section: packaging
+synopsis: GHC's configure scripts now require GCC 6 or newer, up from 4.7.
+issues: #25450
+mrs: !16126
=====================================
changelog.d/march-native
=====================================
@@ -0,0 +1,5 @@
+section: compiler
+synopsis: Add :ghc-flag:`-march=native`, which on x86 and x86_64 enables the
+ CPU features of the machine running GHC.
+issues: #25450
+mrs: !16126
=====================================
compiler/GHC/Driver/DynFlags.hs
=====================================
@@ -450,7 +450,7 @@ data DynFlags = DynFlags {
interactivePrint :: Maybe String,
-- Machine dependent flags (-m\<blah> stuff)
- cpuFeatures :: EnumSet CpuFeature, -- ^ The @-m\<feature\>@ flags that were passed.
+ cpuFeatures :: EnumSet CpuFeature, -- ^ The CPU features requested by @-m...@ flags.
-- See Note [CPU features] in GHC.Platform.CpuFeatures.
la664 :: Bool, -- ^ Enable LA664 instructions
=====================================
compiler/GHC/Driver/Session.hs
=====================================
@@ -1,4 +1,5 @@
{-# LANGUAGE CPP #-}
+{-# LANGUAGE MultiWayIf #-}
-------------------------------------------------------------------------------
--
@@ -228,6 +229,8 @@ import GHC.Platform.CpuFeatures
import GHC.Platform.Ways
import GHC.Platform.Profile
import GHC.Platform.ArchOS
+import GHC.Platform.Host (hostPlatformArch)
+import GHC.Platform.HostCpuFeatures (hostX86CpuFeatures)
import GHC.Unit.Types
import GHC.Unit.Parser
@@ -1737,6 +1740,7 @@ dynamic_flags_deps = [
(setDumpFlag Opt_D_dump_faststrings)
------ Machine dependent (-m<blah>) stuff ---------------------------
+ , make_ord_flag defGhcFlag "march=native" (NoArg enableHostCpuFeatures)
, make_ord_flag defGhcFlag "mla664" (noArg (\d -> d { la664 = True }))
@@ -2863,6 +2867,17 @@ setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
setCpuFeature :: CpuFeature -> DynFlags -> DynFlags
setCpuFeature feat dflags = dflags { cpuFeatures = EnumSet.insert feat (cpuFeatures dflags) }
+-- | @-march=native@: enable the CPU features of the host GHC is running on.
+enableHostCpuFeatures :: DynP ()
+enableHostCpuFeatures = do
+ arch <- platformArch . targetPlatform <$> liftEwM getCmdLineState
+ if | arch /= ArchX86 && arch /= ArchX86_64
+ -> addErr "-march=native is only supported on x86 and x86_64 targets"
+ | arch /= hostPlatformArch
+ -> addErr "-march=native is not supported when the target architecture differs from the host's"
+ | otherwise
+ -> upd $ \d -> d { cpuFeatures = cpuFeatures d `mappend` hostX86CpuFeatures }
+
-- | The @-m\<feature\>@ flag for a 'CpuFeature'.
cpuFeatureFlagDep :: CpuFeature -> (Deprecation, Flag (CmdLineP DynFlags))
cpuFeatureFlagDep feat =
=====================================
compiler/GHC/Platform/CpuFeatures.hs
=====================================
@@ -64,8 +64,9 @@ others:
We keep two representations:
- A. 'DynFlags' records the set of flags that were passed, as an
- 'EnumSet' of 'CpuFeature'. Nothing is implied at this stage.
+ A. 'DynFlags' records the set of requested features, as an 'EnumSet' of
+ 'CpuFeature': one per -m<feature> flag passed, plus the features of the
+ host under -march=native. Nothing is implied at this stage.
B. 'initCpuFeatures' turns this set into a 'CpuFeatures' value, applying the
implications and the baseline of the target architecture. This
=====================================
compiler/GHC/Platform/HostCpuFeatures.hs
=====================================
@@ -0,0 +1,41 @@
+{-# LANGUAGE CPP #-}
+
+module GHC.Platform.HostCpuFeatures
+ ( hostX86CpuFeatures
+ ) where
+
+import GHC.Prelude
+
+import GHC.Data.EnumSet (EnumSet)
+import qualified GHC.Data.EnumSet as EnumSet
+import GHC.Platform.CpuFeatures (CpuFeature(..))
+
+import Data.Word (Word64)
+import System.IO.Unsafe (unsafePerformIO)
+
+#include "HostCpuFeaturesX86.h"
+
+#define GHC_X86_FEATURE_CONS(feat, cond) feat :
+
+-- | The features of the table in @HostCpuFeaturesX86.h@, in row order.
+probedX86CpuFeatures :: [CpuFeature]
+probedX86CpuFeatures = GHC_X86_PROBED_FEATURES(GHC_X86_FEATURE_CONS) []
+
+-- | The host's x86 CPU features.
+hostX86CpuFeatures :: EnumSet CpuFeature
+hostX86CpuFeatures = unsafePerformIO $ do
+ mask <- hostX86CpuFeatureMask
+ pure $ EnumSet.fromList
+ [ feat
+ | (bit, feat) <- zip [0 ..] probedX86CpuFeatures
+ , testBit mask bit
+ ]
+{-# NOINLINE hostX86CpuFeatures #-}
+
+#if defined(javascript_HOST_ARCH)
+hostX86CpuFeatureMask :: IO Word64
+hostX86CpuFeatureMask = pure 0
+#else
+foreign import ccall unsafe "ghc_host_x86_cpu_feature_mask"
+ hostX86CpuFeatureMask :: IO Word64
+#endif
=====================================
compiler/HostCpuFeaturesX86.h
=====================================
@@ -0,0 +1,24 @@
+/* The x86 features that -march=native probes. Each row pairs a CpuFeature
+ constructor with the C condition (see cbits/host_cpu_features_x86.c) that
+ detects the feature on the host. SSE and SSE2 are not probed: they are
+ GHC's x86 baseline.
+
+ Row i is bit i of the mask that ghc_host_x86_cpu_feature_mask returns and
+ GHC.Platform.HostCpuFeatures decodes, so the table can hold at most 64
+ rows. */
+#define GHC_X86_PROBED_FEATURES(F) \
+ F(Feat_SSE3, SUPPORTS("sse3")) \
+ F(Feat_SSSE3, SUPPORTS("ssse3")) \
+ F(Feat_SSE4, SUPPORTS("sse4.1")) \
+ F(Feat_SSE4_2, SUPPORTS("sse4.2")) \
+ F(Feat_AVX, SUPPORTS("avx")) \
+ F(Feat_AVX2, SUPPORTS("avx2")) \
+ F(Feat_AVX512F, SUPPORTS("avx512f")) \
+ F(Feat_AVX512BW, SUPPORTS("avx512bw")) \
+ F(Feat_AVX512CD, SUPPORTS("avx512cd")) \
+ F(Feat_AVX512DQ, SUPPORTS("avx512dq")) \
+ F(Feat_AVX512VL, SUPPORTS("avx512vl")) \
+ F(Feat_BMI, SUPPORTS("bmi")) \
+ F(Feat_BMI2, SUPPORTS("bmi2")) \
+ F(Feat_FMA, SUPPORTS_FMA) \
+ F(Feat_GFNI, SUPPORTS_GFNI)
=====================================
compiler/cbits/host_cpu_features_x86.c
=====================================
@@ -0,0 +1,63 @@
+#include <HsFFI.h>
+
+/* Host x86 CPU feature detection for GHC.Platform.HostCpuFeatures
+ (-march=native).
+
+ The RTS has to export the libgcc/compiler-rt symbols that the
+ __builtin_cpu_* calls refer to: see RTS_X86_CPU_MODEL_SYMBOLS in
+ rts/RtsSymbols.c. */
+
+#include "HostCpuFeaturesX86.h"
+
+#if defined(__i386__) || defined(__x86_64__)
+
+#define SUPPORTS(name) __builtin_cpu_supports(name)
+
+/* FMA is usable only when the OS saves the AVX register state, but
+ compiler-rt's cpu_model/x86.c reports "fma" from the raw CPUID bit. */
+#define SUPPORTS_FMA (SUPPORTS("fma") && SUPPORTS("avx"))
+
+/* __builtin_cpu_supports accepts "gfni" from GCC 8 and LLVM 8 on, and reads
+ it from __cpu_features2, which libgcc provides only from GCC 8 on. */
+#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 8
+/* Weak, so that programs using the ghc library from a binary distribution
+ can link against a libgcc older than GCC 8. The declaration also makes
+ the builtin's own reference weak. */
+extern unsigned int __cpu_features2[] __attribute__((weak));
+#define SUPPORTS_GFNI (__cpu_features2 != 0 && SUPPORTS("gfni"))
+#elif defined(__clang__) \
+ && __clang_major__ >= (defined(__apple_build_version__) ? 11 : 8)
+/* Apple clang numbers its releases separately: 11 is its first based on
+ LLVM 8. Clang marks its reference dso_local, so a weak declaration would
+ not help: an older libgcc fails the link. */
+#define SUPPORTS_GFNI SUPPORTS("gfni")
+#else
+#define SUPPORTS_GFNI 0
+#endif
+
+HsWord64 ghc_host_x86_cpu_feature_mask(void)
+{
+ __builtin_cpu_init();
+
+ HsWord64 mask = 0;
+ int bit = 0;
+
+#define GHC_X86_PROBE(feat, cond) \
+ if (cond) { mask |= (HsWord64)1 << bit; } \
+ bit++;
+
+ GHC_X86_PROBED_FEATURES(GHC_X86_PROBE)
+
+#undef GHC_X86_PROBE
+
+ return mask;
+}
+
+#else
+
+HsWord64 ghc_host_x86_cpu_feature_mask(void)
+{
+ return 0;
+}
+
+#endif
=====================================
compiler/ghc.cabal.in
=====================================
@@ -32,6 +32,7 @@ extra-source-files:
GHC/Builtin/primops.txt.pp
Unique.h
CodeGen.Platform.h
+ HostCpuFeaturesX86.h
-- Shared with rts via hard-link at configure time. This is safer
-- for Windows, where symlinks don't work out of the box, so we
-- can't just commit some in git.
@@ -186,6 +187,7 @@ Library
c-sources:
cbits/cutils.c
cbits/genSym.c
+ cbits/host_cpu_features_x86.c
cbits/keepCAFsForGHCi.c
hs-source-dirs:
@@ -691,6 +693,7 @@ Library
GHC.Platform.AArch64
GHC.Platform.Constants
GHC.Platform.CpuFeatures
+ GHC.Platform.HostCpuFeatures
GHC.Platform.LA64
GHC.Platform.NoRegs
GHC.Platform.PPC
=====================================
docs/users_guide/expected-undocumented-flags.txt
=====================================
@@ -55,6 +55,7 @@
-instantiated-with
-keep-hi-file
-keep-o-file
+-march=native
-no-keep-hi-file
-no-keep-o-file
-no-link
=====================================
docs/users_guide/using.rst
=====================================
@@ -1887,6 +1887,30 @@ Some flags only make sense for particular target platforms.
so this flag has no effect when used with the :ref:`native code generator <native-code-gen>`
or the :ref:`LLVM backend <llvm-code-gen>`.
+.. ghc-flag:: -march=native
+ :shortdesc: (x86 only) Enable the CPU features of the host
+ :type: dynamic
+ :category: platform-options
+
+ (x86 only) Probe the CPU of the machine running GHC and enable the
+ corresponding ``-m...`` CPU-feature options (for example ``-msse4.2``,
+ ``-mavx2``, ``-mbmi2``, ``-mfma``). The detected features apply to both the
+ :ref:`native code generator <native-code-gen>` and the
+ :ref:`LLVM backend <llvm-code-gen>`.
+
+ The detected features are enabled in addition to any ``-m...`` options
+ given explicitly, regardless of their order on the command line.
+
+ .. warning::
+
+ Code compiled with ``-march=native`` may use instructions that are not
+ available on other CPUs, and is therefore not portable to a different
+ machine.
+
+ The flag is rejected on other targets. A cross-compiler also rejects it
+ when its target architecture differs from the one GHC itself runs on, since
+ the probed CPU then says nothing about the target.
+
Haddock
-------
=====================================
m4/fp_gcc_version.m4
=====================================
@@ -16,9 +16,10 @@ AC_DEFUN([FP_GCC_VERSION], [
AC_MSG_CHECKING([version of gcc])
fp_cv_gcc_version="`$CC -v 2>&1 | sed -n -e '1,/version /s/.*version [[^0-9]]*\([[0-9.]]*\).*/\1/p'`"
AC_MSG_RESULT([$fp_cv_gcc_version])
- # 4.7 is needed for __atomic_ builtins.
- FP_COMPARE_VERSIONS([$fp_cv_gcc_version], [-lt], [4.7],
- [AC_MSG_ERROR([Need at least gcc version 4.7 (newer recommended)])])
+ # GCC 5 rejects some of the AVX-512 feature names that -march=native
+ # passes to __builtin_cpu_supports.
+ FP_COMPARE_VERSIONS([$fp_cv_gcc_version], [-lt], [6],
+ [AC_MSG_ERROR([Need at least gcc version 6 (newer recommended)])])
])
AC_SUBST([GccVersion], [$fp_cv_gcc_version])
else
=====================================
rts/RtsSymbols.c
=====================================
@@ -1050,6 +1050,33 @@ extern char **environ;
#define RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
#endif
+// libgcc/compiler-rt symbols behind __builtin_cpu_supports and
+// __builtin_cpu_init, used by compiler/cbits/host_cpu_features_x86.c for
+// -march=native. Without them the runtime linker cannot load the ghc
+// library's object code, e.g. for plugins in a statically linked GHCi.
+#if defined(i386_HOST_ARCH) || defined(x86_64_HOST_ARCH)
+// Weak: missing before GCC 8 and LLVM 8.
+extern StgWord __cpu_features2[] __attribute__((weak));
+#define RTS_X86_CPU_MODEL_SYMBOLS \
+ SymI_NeedsProto(__cpu_indicator_init) \
+ SymI_NeedsDataProto(__cpu_model) \
+ SymI_HasDataProto(__cpu_features2) \
+ RTS_X86_CPU_INIT_LOCAL_SYMBOLS
+#else
+#define RTS_X86_CPU_MODEL_SYMBOLS
+#endif
+
+// Alpine's and Gentoo's musl GCCs patch __builtin_cpu_init to call this
+// alias of __cpu_indicator_init. Weak: other musl toolchains lack it.
+#if (defined(i386_HOST_ARCH) || defined(x86_64_HOST_ARCH)) \
+ && defined(linux_HOST_OS) && !defined(__GLIBC__)
+extern void __cpu_indicator_init_local(void) __attribute__((weak));
+#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS \
+ SymI_HasProto(__cpu_indicator_init_local)
+#else
+#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS
+#endif
+
// Symbols defined by libc
#define RTS_LIBC_SYMBOLS \
SymI_HasProto_redirect(atexit, atexit, STRENGTH_STRONG, SYM_TYPE_CODE) /* See Note [Strong symbols] */ \
@@ -1210,6 +1237,7 @@ RTS_OPENBSD_ONLY_SYMBOLS
RTS_LIBC_SYMBOLS
RTS_LIBGCC_SYMBOLS
RTS_ARCH_LIBGCC_SYMBOLS
+RTS_X86_CPU_MODEL_SYMBOLS
RTS_FINI_ARRAY_SYMBOLS
RTS_LIBFFI_SYMBOLS
RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
@@ -1265,6 +1293,7 @@ RtsSymbolVal const * getRtsSymbols(void) {
RTS_OPENBSD_ONLY_SYMBOLS
RTS_LIBGCC_SYMBOLS
RTS_ARCH_LIBGCC_SYMBOLS
+ RTS_X86_CPU_MODEL_SYMBOLS
RTS_FINI_ARRAY_SYMBOLS
RTS_LIBFFI_SYMBOLS
RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
=====================================
testsuite/tests/driver/Makefile
=====================================
@@ -500,6 +500,15 @@ withRtsOpts:
T3364:
-"$(TEST_HC)" $(TEST_HC_OPTS) -H
+# GHC and the C compiler should detect the same host CPU features.
+.PHONY: march_native_matches_cc
+march_native_matches_cc:
+ "$(TEST_HC)" $(TEST_HC_OPTS) -march=native -E -cpp march_native_matches_cc.hs -o ghc.out
+ "$(TEST_CC)" $(TEST_CC_OPTS) -march=native -E -x c march_native_matches_cc.hs > cc.out
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' ghc.out > ghc.feats
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' cc.out > cc.feats
+ diff -u ghc.feats cc.feats
+
.PHONY: T706
T706:
cp T706a.hs T706.hs
=====================================
testsuite/tests/driver/all.T
=====================================
@@ -223,6 +223,15 @@ test('T9938B', [], makefile_test, [])
test('T9963', exit_code(1), run_command,
['{compiler} --interactive -ignore-dot-ghci --print-libdir'])
+test('march_native_unsupported_arch',
+ [when(arch('x86_64') or arch('i386'), skip)],
+ compile_fail,
+ ['-march=native'])
+
+test('march_native_matches_cc',
+ [unless(arch('x86_64') or arch('i386'), skip), when(config.cross, skip)],
+ makefile_test, [])
+
test('T10219', normal, run_command,
# `-x hspp` in make mode should work.
# Note: need to specify `-x hspp` before the filename.
=====================================
testsuite/tests/driver/march_native_matches_cc.hs
=====================================
@@ -0,0 +1,40 @@
+-- BMI and BMI2 are not listed: GHC defines no macros for them.
+#if defined(__SSE3__)
+feat sse3
+#endif
+#if defined(__SSSE3__)
+feat ssse3
+#endif
+#if defined(__SSE4_1__)
+feat sse4.1
+#endif
+#if defined(__SSE4_2__)
+feat sse4.2
+#endif
+#if defined(__AVX__)
+feat avx
+#endif
+#if defined(__AVX2__)
+feat avx2
+#endif
+#if defined(__AVX512F__)
+feat avx512f
+#endif
+#if defined(__AVX512BW__)
+feat avx512bw
+#endif
+#if defined(__AVX512CD__)
+feat avx512cd
+#endif
+#if defined(__AVX512DQ__)
+feat avx512dq
+#endif
+#if defined(__AVX512VL__)
+feat avx512vl
+#endif
+#if defined(__FMA__)
+feat fma
+#endif
+#if defined(__GFNI__)
+feat gfni
+#endif
=====================================
testsuite/tests/driver/march_native_unsupported_arch.hs
=====================================
@@ -0,0 +1 @@
+module M where
=====================================
testsuite/tests/driver/march_native_unsupported_arch.stderr
=====================================
@@ -0,0 +1,2 @@
+ghc: on the commandline: -march=native is only supported on x86 and x86_64 targets
+Usage: For basic information, try the `--help' option.
=====================================
testsuite/tests/rts/symbols/Main.hs
=====================================
@@ -31,6 +31,13 @@ ignoreSymbols = S.fromList [
"__umoddi3",
"__umodti3",
+ -- Defined in libgcc/compiler-rt. RtsSymbols.c declares them on x86 only
+ -- (+Declared)
+ "__cpu_features2",
+ "__cpu_indicator_init",
+ "__cpu_indicator_init_local",
+ "__cpu_model",
+
-- These may be a CPP mismatch between rts/prim/vectorQuotRem.c and RtsSymbols.c
"hs_quotInt16X8",
"hs_quotInt32X4",
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/50b789bf42660c657de974f918ab268…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/50b789bf42660c657de974f918ab268…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/sjakobi/T25450-march-native] Implement -march=native for x86/x86_64
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/T25450-march-native at Glasgow Haskell Compiler / GHC
Commits:
38e61025 by Simon Jakobi at 2026-11-23T07:56:20+01:00
Implement -march=native for x86/x86_64
-march=native detects the CPU features of the host and enables the
corresponding -m⟨feature⟩ flags.
The features are detected using GCC/Clang's __builtin_cpu_supports.
The RTS's symbol table needed to be extended with the
libgcc/compiler-rt symbols behind this builtin, so that a statically
linked GHCi, e.g. on Windows, can still load the ghc library.
As a side effect, every Haskell program on x86 now links the object
that defines these symbols and runs its initialiser, which probes the
CPU once at program start. On my machine (x86_64 Linux, GCC 13) this
adds about 5 KB and about a microsecond to a hello-world that runs for
about 2 ms.
GCC 5 and older reject some of the AVX-512 feature names that we probe
for. configure therefore requires GCC 6 now, up from 4.7.
The flag is registered in expected-undocumented-flags.txt due to #27321.
Closes #25450
Assisted-by: Claude Fable 5.2
- - - - -
19 changed files:
- + changelog.d/gcc-6-minimum
- + changelog.d/march-native
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Platform/CpuFeatures.hs
- + compiler/GHC/Platform/HostCpuFeatures.hs
- + compiler/HostCpuFeaturesX86.h
- + compiler/cbits/host_cpu_features_x86.c
- compiler/ghc.cabal.in
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/using.rst
- m4/fp_gcc_version.m4
- rts/RtsSymbols.c
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/all.T
- + testsuite/tests/driver/march_native_matches_cc.hs
- + testsuite/tests/driver/march_native_unsupported_arch.hs
- + testsuite/tests/driver/march_native_unsupported_arch.stderr
- testsuite/tests/rts/symbols/Main.hs
Changes:
=====================================
changelog.d/gcc-6-minimum
=====================================
@@ -0,0 +1,4 @@
+section: packaging
+synopsis: Building GHC with GCC now requires GCC 6 or newer.
+issues: #25450
+mrs: !16126
=====================================
changelog.d/march-native
=====================================
@@ -0,0 +1,5 @@
+section: compiler
+synopsis: Add :ghc-flag:`-march=native`, which on x86 and x86_64 enables the
+ CPU features of the machine running GHC.
+issues: #25450
+mrs: !16126
=====================================
compiler/GHC/Driver/DynFlags.hs
=====================================
@@ -450,7 +450,7 @@ data DynFlags = DynFlags {
interactivePrint :: Maybe String,
-- Machine dependent flags (-m\<blah> stuff)
- cpuFeatures :: EnumSet CpuFeature, -- ^ The @-m\<feature\>@ flags that were passed.
+ cpuFeatures :: EnumSet CpuFeature, -- ^ The CPU features requested by @-m...@ flags.
-- See Note [CPU features] in GHC.Platform.CpuFeatures.
la664 :: Bool, -- ^ Enable LA664 instructions
=====================================
compiler/GHC/Driver/Session.hs
=====================================
@@ -1,4 +1,5 @@
{-# LANGUAGE CPP #-}
+{-# LANGUAGE MultiWayIf #-}
-------------------------------------------------------------------------------
--
@@ -228,6 +229,8 @@ import GHC.Platform.CpuFeatures
import GHC.Platform.Ways
import GHC.Platform.Profile
import GHC.Platform.ArchOS
+import GHC.Platform.Host (hostPlatformArch)
+import GHC.Platform.HostCpuFeatures (hostX86CpuFeatures)
import GHC.Unit.Types
import GHC.Unit.Parser
@@ -1737,6 +1740,7 @@ dynamic_flags_deps = [
(setDumpFlag Opt_D_dump_faststrings)
------ Machine dependent (-m<blah>) stuff ---------------------------
+ , make_ord_flag defGhcFlag "march=native" (NoArg enableHostCpuFeatures)
, make_ord_flag defGhcFlag "mla664" (noArg (\d -> d { la664 = True }))
@@ -2863,6 +2867,17 @@ setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
setCpuFeature :: CpuFeature -> DynFlags -> DynFlags
setCpuFeature feat dflags = dflags { cpuFeatures = EnumSet.insert feat (cpuFeatures dflags) }
+-- | @-march=native@: enable the CPU features of the host GHC is running on.
+enableHostCpuFeatures :: DynP ()
+enableHostCpuFeatures = do
+ arch <- platformArch . targetPlatform <$> liftEwM getCmdLineState
+ if | arch /= ArchX86 && arch /= ArchX86_64
+ -> addErr "-march=native is only supported on x86 and x86_64 targets"
+ | arch /= hostPlatformArch
+ -> addErr "-march=native is not supported when the target architecture differs from the host's"
+ | otherwise
+ -> upd $ \d -> d { cpuFeatures = cpuFeatures d `mappend` hostX86CpuFeatures }
+
-- | The @-m\<feature\>@ flag for a 'CpuFeature'.
cpuFeatureFlagDep :: CpuFeature -> (Deprecation, Flag (CmdLineP DynFlags))
cpuFeatureFlagDep feat =
=====================================
compiler/GHC/Platform/CpuFeatures.hs
=====================================
@@ -64,8 +64,9 @@ others:
We keep two representations:
- A. 'DynFlags' records the set of flags that were passed, as an
- 'EnumSet' of 'CpuFeature'. Nothing is implied at this stage.
+ A. 'DynFlags' records the set of requested features, as an 'EnumSet' of
+ 'CpuFeature': one per -m<feature> flag passed, plus the features of the
+ host under -march=native. Nothing is implied at this stage.
B. 'initCpuFeatures' turns this set into a 'CpuFeatures' value, applying the
implications and the baseline of the target architecture. This
=====================================
compiler/GHC/Platform/HostCpuFeatures.hs
=====================================
@@ -0,0 +1,41 @@
+{-# LANGUAGE CPP #-}
+
+module GHC.Platform.HostCpuFeatures
+ ( hostX86CpuFeatures
+ ) where
+
+import GHC.Prelude
+
+import GHC.Data.EnumSet (EnumSet)
+import qualified GHC.Data.EnumSet as EnumSet
+import GHC.Platform.CpuFeatures (CpuFeature(..))
+
+import Data.Word (Word64)
+import System.IO.Unsafe (unsafePerformIO)
+
+#include "HostCpuFeaturesX86.h"
+
+#define GHC_X86_FEATURE_CONS(feat, cond) feat :
+
+-- | The features of the table in @HostCpuFeaturesX86.h@, in row order.
+probedX86CpuFeatures :: [CpuFeature]
+probedX86CpuFeatures = GHC_X86_PROBED_FEATURES(GHC_X86_FEATURE_CONS) []
+
+-- | The host's x86 CPU features.
+hostX86CpuFeatures :: EnumSet CpuFeature
+hostX86CpuFeatures = unsafePerformIO $ do
+ mask <- hostX86CpuFeatureMask
+ pure $ EnumSet.fromList
+ [ feat
+ | (bit, feat) <- zip [0 ..] probedX86CpuFeatures
+ , testBit mask bit
+ ]
+{-# NOINLINE hostX86CpuFeatures #-}
+
+#if defined(javascript_HOST_ARCH)
+hostX86CpuFeatureMask :: IO Word64
+hostX86CpuFeatureMask = pure 0
+#else
+foreign import ccall unsafe "ghc_host_x86_cpu_feature_mask"
+ hostX86CpuFeatureMask :: IO Word64
+#endif
=====================================
compiler/HostCpuFeaturesX86.h
=====================================
@@ -0,0 +1,24 @@
+/* The x86 features that -march=native probes. Each row pairs a CpuFeature
+ constructor with the C condition (see cbits/host_cpu_features_x86.c) that
+ detects the feature on the host. SSE and SSE2 are not probed: they are
+ GHC's x86 baseline.
+
+ Row i is bit i of the mask that ghc_host_x86_cpu_feature_mask returns and
+ GHC.Platform.HostCpuFeatures decodes, so the table can hold at most 64
+ rows. */
+#define GHC_X86_PROBED_FEATURES(F) \
+ F(Feat_SSE3, SUPPORTS("sse3")) \
+ F(Feat_SSSE3, SUPPORTS("ssse3")) \
+ F(Feat_SSE4, SUPPORTS("sse4.1")) \
+ F(Feat_SSE4_2, SUPPORTS("sse4.2")) \
+ F(Feat_AVX, SUPPORTS("avx")) \
+ F(Feat_AVX2, SUPPORTS("avx2")) \
+ F(Feat_AVX512F, SUPPORTS("avx512f")) \
+ F(Feat_AVX512BW, SUPPORTS("avx512bw")) \
+ F(Feat_AVX512CD, SUPPORTS("avx512cd")) \
+ F(Feat_AVX512DQ, SUPPORTS("avx512dq")) \
+ F(Feat_AVX512VL, SUPPORTS("avx512vl")) \
+ F(Feat_BMI, SUPPORTS("bmi")) \
+ F(Feat_BMI2, SUPPORTS("bmi2")) \
+ F(Feat_FMA, SUPPORTS_FMA) \
+ F(Feat_GFNI, SUPPORTS_GFNI)
=====================================
compiler/cbits/host_cpu_features_x86.c
=====================================
@@ -0,0 +1,63 @@
+#include <HsFFI.h>
+
+/* Host x86 CPU feature detection for GHC.Platform.HostCpuFeatures
+ (-march=native).
+
+ The RTS has to export the libgcc/compiler-rt symbols that the
+ __builtin_cpu_* calls refer to: see RTS_X86_CPU_MODEL_SYMBOLS in
+ rts/RtsSymbols.c. */
+
+#include "HostCpuFeaturesX86.h"
+
+#if defined(__i386__) || defined(__x86_64__)
+
+#define SUPPORTS(name) __builtin_cpu_supports(name)
+
+/* FMA is usable only when the OS saves the AVX register state, but
+ compiler-rt's cpu_model/x86.c reports "fma" from the raw CPUID bit. */
+#define SUPPORTS_FMA (SUPPORTS("fma") && SUPPORTS("avx"))
+
+/* __builtin_cpu_supports accepts "gfni" from GCC 8 and LLVM 8 on, and reads
+ it from __cpu_features2, which libgcc provides only from GCC 8 on. */
+#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 8
+/* Weak, so that programs using the ghc library from a binary distribution
+ can link against a libgcc older than GCC 8. The declaration also makes
+ the builtin's own reference weak. */
+extern unsigned int __cpu_features2[] __attribute__((weak));
+#define SUPPORTS_GFNI (__cpu_features2 != 0 && SUPPORTS("gfni"))
+#elif defined(__clang__) \
+ && __clang_major__ >= (defined(__apple_build_version__) ? 11 : 8)
+/* Apple clang numbers its releases separately: 11 is its first based on
+ LLVM 8. Clang marks its reference dso_local, so a weak declaration would
+ not help: an older libgcc fails the link. */
+#define SUPPORTS_GFNI SUPPORTS("gfni")
+#else
+#define SUPPORTS_GFNI 0
+#endif
+
+HsWord64 ghc_host_x86_cpu_feature_mask(void)
+{
+ __builtin_cpu_init();
+
+ HsWord64 mask = 0;
+ int bit = 0;
+
+#define GHC_X86_PROBE(feat, cond) \
+ if (cond) { mask |= (HsWord64)1 << bit; } \
+ bit++;
+
+ GHC_X86_PROBED_FEATURES(GHC_X86_PROBE)
+
+#undef GHC_X86_PROBE
+
+ return mask;
+}
+
+#else
+
+HsWord64 ghc_host_x86_cpu_feature_mask(void)
+{
+ return 0;
+}
+
+#endif
=====================================
compiler/ghc.cabal.in
=====================================
@@ -32,6 +32,7 @@ extra-source-files:
GHC/Builtin/primops.txt.pp
Unique.h
CodeGen.Platform.h
+ HostCpuFeaturesX86.h
-- Shared with rts via hard-link at configure time. This is safer
-- for Windows, where symlinks don't work out of the box, so we
-- can't just commit some in git.
@@ -186,6 +187,7 @@ Library
c-sources:
cbits/cutils.c
cbits/genSym.c
+ cbits/host_cpu_features_x86.c
cbits/keepCAFsForGHCi.c
hs-source-dirs:
@@ -691,6 +693,7 @@ Library
GHC.Platform.AArch64
GHC.Platform.Constants
GHC.Platform.CpuFeatures
+ GHC.Platform.HostCpuFeatures
GHC.Platform.LA64
GHC.Platform.NoRegs
GHC.Platform.PPC
=====================================
docs/users_guide/expected-undocumented-flags.txt
=====================================
@@ -55,6 +55,7 @@
-instantiated-with
-keep-hi-file
-keep-o-file
+-march=native
-no-keep-hi-file
-no-keep-o-file
-no-link
=====================================
docs/users_guide/using.rst
=====================================
@@ -1887,6 +1887,30 @@ Some flags only make sense for particular target platforms.
so this flag has no effect when used with the :ref:`native code generator <native-code-gen>`
or the :ref:`LLVM backend <llvm-code-gen>`.
+.. ghc-flag:: -march=native
+ :shortdesc: (x86 only) Enable the CPU features of the host
+ :type: dynamic
+ :category: platform-options
+
+ (x86 only) Probe the CPU of the machine running GHC and enable the
+ corresponding ``-m...`` CPU-feature options (for example ``-msse4.2``,
+ ``-mavx2``, ``-mbmi2``, ``-mfma``). The detected features apply to both the
+ :ref:`native code generator <native-code-gen>` and the
+ :ref:`LLVM backend <llvm-code-gen>`.
+
+ The detected features are enabled in addition to any ``-m...`` options
+ given explicitly, regardless of their order on the command line.
+
+ .. warning::
+
+ Code compiled with ``-march=native`` may use instructions that are not
+ available on other CPUs, and is therefore not portable to a different
+ machine.
+
+ The flag is rejected on other targets. A cross-compiler also rejects it
+ when its target architecture differs from the one GHC itself runs on, since
+ the probed CPU then says nothing about the target.
+
Haddock
-------
=====================================
m4/fp_gcc_version.m4
=====================================
@@ -16,9 +16,10 @@ AC_DEFUN([FP_GCC_VERSION], [
AC_MSG_CHECKING([version of gcc])
fp_cv_gcc_version="`$CC -v 2>&1 | sed -n -e '1,/version /s/.*version [[^0-9]]*\([[0-9.]]*\).*/\1/p'`"
AC_MSG_RESULT([$fp_cv_gcc_version])
- # 4.7 is needed for __atomic_ builtins.
- FP_COMPARE_VERSIONS([$fp_cv_gcc_version], [-lt], [4.7],
- [AC_MSG_ERROR([Need at least gcc version 4.7 (newer recommended)])])
+ # GCC 5 rejects some of the AVX-512 feature names that -march=native
+ # passes to __builtin_cpu_supports.
+ FP_COMPARE_VERSIONS([$fp_cv_gcc_version], [-lt], [6],
+ [AC_MSG_ERROR([Need at least gcc version 6 (newer recommended)])])
])
AC_SUBST([GccVersion], [$fp_cv_gcc_version])
else
=====================================
rts/RtsSymbols.c
=====================================
@@ -1050,6 +1050,33 @@ extern char **environ;
#define RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
#endif
+// libgcc/compiler-rt symbols behind __builtin_cpu_supports and
+// __builtin_cpu_init, used by compiler/cbits/host_cpu_features_x86.c for
+// -march=native. Without them the runtime linker cannot load the ghc
+// library's object code, e.g. for plugins in a statically linked GHCi.
+#if defined(i386_HOST_ARCH) || defined(x86_64_HOST_ARCH)
+// Weak: missing before GCC 8 and LLVM 8.
+extern StgWord __cpu_features2[] __attribute__((weak));
+#define RTS_X86_CPU_MODEL_SYMBOLS \
+ SymI_NeedsProto(__cpu_indicator_init) \
+ SymI_NeedsDataProto(__cpu_model) \
+ SymI_HasDataProto(__cpu_features2) \
+ RTS_X86_CPU_INIT_LOCAL_SYMBOLS
+#else
+#define RTS_X86_CPU_MODEL_SYMBOLS
+#endif
+
+// Alpine's and Gentoo's musl GCCs patch __builtin_cpu_init to call this
+// alias of __cpu_indicator_init. Weak: other musl toolchains lack it.
+#if (defined(i386_HOST_ARCH) || defined(x86_64_HOST_ARCH)) \
+ && defined(linux_HOST_OS) && !defined(__GLIBC__)
+extern void __cpu_indicator_init_local(void) __attribute__((weak));
+#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS \
+ SymI_HasProto(__cpu_indicator_init_local)
+#else
+#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS
+#endif
+
// Symbols defined by libc
#define RTS_LIBC_SYMBOLS \
SymI_HasProto_redirect(atexit, atexit, STRENGTH_STRONG, SYM_TYPE_CODE) /* See Note [Strong symbols] */ \
@@ -1210,6 +1237,7 @@ RTS_OPENBSD_ONLY_SYMBOLS
RTS_LIBC_SYMBOLS
RTS_LIBGCC_SYMBOLS
RTS_ARCH_LIBGCC_SYMBOLS
+RTS_X86_CPU_MODEL_SYMBOLS
RTS_FINI_ARRAY_SYMBOLS
RTS_LIBFFI_SYMBOLS
RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
@@ -1265,6 +1293,7 @@ RtsSymbolVal const * getRtsSymbols(void) {
RTS_OPENBSD_ONLY_SYMBOLS
RTS_LIBGCC_SYMBOLS
RTS_ARCH_LIBGCC_SYMBOLS
+ RTS_X86_CPU_MODEL_SYMBOLS
RTS_FINI_ARRAY_SYMBOLS
RTS_LIBFFI_SYMBOLS
RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
=====================================
testsuite/tests/driver/Makefile
=====================================
@@ -500,6 +500,15 @@ withRtsOpts:
T3364:
-"$(TEST_HC)" $(TEST_HC_OPTS) -H
+# GHC and the C compiler should detect the same host CPU features.
+.PHONY: march_native_matches_cc
+march_native_matches_cc:
+ "$(TEST_HC)" $(TEST_HC_OPTS) -march=native -E -cpp march_native_matches_cc.hs -o ghc.out
+ "$(TEST_CC)" $(TEST_CC_OPTS) -march=native -E -x c march_native_matches_cc.hs > cc.out
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' ghc.out > ghc.feats
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' cc.out > cc.feats
+ diff -u ghc.feats cc.feats
+
.PHONY: T706
T706:
cp T706a.hs T706.hs
=====================================
testsuite/tests/driver/all.T
=====================================
@@ -223,6 +223,15 @@ test('T9938B', [], makefile_test, [])
test('T9963', exit_code(1), run_command,
['{compiler} --interactive -ignore-dot-ghci --print-libdir'])
+test('march_native_unsupported_arch',
+ [when(arch('x86_64') or arch('i386'), skip)],
+ compile_fail,
+ ['-march=native'])
+
+test('march_native_matches_cc',
+ [unless(arch('x86_64') or arch('i386'), skip), when(config.cross, skip)],
+ makefile_test, [])
+
test('T10219', normal, run_command,
# `-x hspp` in make mode should work.
# Note: need to specify `-x hspp` before the filename.
=====================================
testsuite/tests/driver/march_native_matches_cc.hs
=====================================
@@ -0,0 +1,40 @@
+-- BMI and BMI2 are not listed: GHC defines no macros for them.
+#if defined(__SSE3__)
+feat sse3
+#endif
+#if defined(__SSSE3__)
+feat ssse3
+#endif
+#if defined(__SSE4_1__)
+feat sse4.1
+#endif
+#if defined(__SSE4_2__)
+feat sse4.2
+#endif
+#if defined(__AVX__)
+feat avx
+#endif
+#if defined(__AVX2__)
+feat avx2
+#endif
+#if defined(__AVX512F__)
+feat avx512f
+#endif
+#if defined(__AVX512BW__)
+feat avx512bw
+#endif
+#if defined(__AVX512CD__)
+feat avx512cd
+#endif
+#if defined(__AVX512DQ__)
+feat avx512dq
+#endif
+#if defined(__AVX512VL__)
+feat avx512vl
+#endif
+#if defined(__FMA__)
+feat fma
+#endif
+#if defined(__GFNI__)
+feat gfni
+#endif
=====================================
testsuite/tests/driver/march_native_unsupported_arch.hs
=====================================
@@ -0,0 +1 @@
+module M where
=====================================
testsuite/tests/driver/march_native_unsupported_arch.stderr
=====================================
@@ -0,0 +1,2 @@
+ghc: on the commandline: -march=native is only supported on x86 and x86_64 targets
+Usage: For basic information, try the `--help' option.
=====================================
testsuite/tests/rts/symbols/Main.hs
=====================================
@@ -31,6 +31,13 @@ ignoreSymbols = S.fromList [
"__umoddi3",
"__umodti3",
+ -- Defined in libgcc/compiler-rt. RtsSymbols.c declares them on x86 only
+ -- (+Declared)
+ "__cpu_features2",
+ "__cpu_indicator_init",
+ "__cpu_indicator_init_local",
+ "__cpu_model",
+
-- These may be a CPP mismatch between rts/prim/vectorQuotRem.c and RtsSymbols.c
"hs_quotInt16X8",
"hs_quotInt32X4",
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/38e61025830a37d55972a4017db2d03…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/38e61025830a37d55972a4017db2d03…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/sjakobi/T25450-march-native] Implement -march=native for x86/x86_64
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/T25450-march-native at Glasgow Haskell Compiler / GHC
Commits:
35755033 by Simon Jakobi at 2026-11-23T05:48:17+01:00
Implement -march=native for x86/x86_64
-march=native detects the CPU features of the host and enables the
corresponding -m⟨feature⟩ flags.
The features are detected using GCC/Clang's __builtin_cpu_supports.
The RTS's symbol table needed to be extended with the
libgcc/compiler-rt symbols behind the builtin, so that a statically
linked GHCi, e.g. on Windows, can still load the ghc library.
As a side effect, every Haskell program on x86 now links the object
that defines these symbols and runs its initialiser, which probes the
CPU once at program start. On my machine (x86_64 Linux, GCC 13) this
adds about 5 KB and about a microsecond to a hello-world that runs for
about 2 ms.
GCC 5 and older reject some of the AVX-512 feature names that we probe
for. configure therefore requires GCC 6 now, up from 4.7.
The flag is registered in expected-undocumented-flags.txt due to #27321.
Closes #25450
Assisted-by: Claude Fable 5.2
- - - - -
19 changed files:
- + changelog.d/gcc-6-minimum
- + changelog.d/march-native
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Platform/CpuFeatures.hs
- + compiler/GHC/Platform/HostCpuFeatures.hs
- + compiler/HostCpuFeaturesX86.h
- + compiler/cbits/host_cpu_features_x86.c
- compiler/ghc.cabal.in
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/using.rst
- m4/fp_gcc_version.m4
- rts/RtsSymbols.c
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/all.T
- + testsuite/tests/driver/march_native_matches_cc.hs
- + testsuite/tests/driver/march_native_unsupported_arch.hs
- + testsuite/tests/driver/march_native_unsupported_arch.stderr
- testsuite/tests/rts/symbols/Main.hs
Changes:
=====================================
changelog.d/gcc-6-minimum
=====================================
@@ -0,0 +1,4 @@
+section: packaging
+synopsis: Building GHC with GCC now requires GCC 6 or newer.
+issues: #25450
+mrs: !16126
=====================================
changelog.d/march-native
=====================================
@@ -0,0 +1,5 @@
+section: compiler
+synopsis: Add :ghc-flag:`-march=native`, which on x86 and x86_64 enables the
+ CPU features of the machine running GHC.
+issues: #25450
+mrs: !16126
=====================================
compiler/GHC/Driver/DynFlags.hs
=====================================
@@ -450,7 +450,7 @@ data DynFlags = DynFlags {
interactivePrint :: Maybe String,
-- Machine dependent flags (-m\<blah> stuff)
- cpuFeatures :: EnumSet CpuFeature, -- ^ The @-m\<feature\>@ flags that were passed.
+ cpuFeatures :: EnumSet CpuFeature, -- ^ The CPU features requested by @-m...@ flags.
-- See Note [CPU features] in GHC.Platform.CpuFeatures.
la664 :: Bool, -- ^ Enable LA664 instructions
=====================================
compiler/GHC/Driver/Session.hs
=====================================
@@ -1,4 +1,5 @@
{-# LANGUAGE CPP #-}
+{-# LANGUAGE MultiWayIf #-}
-------------------------------------------------------------------------------
--
@@ -228,6 +229,8 @@ import GHC.Platform.CpuFeatures
import GHC.Platform.Ways
import GHC.Platform.Profile
import GHC.Platform.ArchOS
+import GHC.Platform.Host (hostPlatformArch)
+import GHC.Platform.HostCpuFeatures (hostX86CpuFeatures)
import GHC.Unit.Types
import GHC.Unit.Parser
@@ -1737,6 +1740,7 @@ dynamic_flags_deps = [
(setDumpFlag Opt_D_dump_faststrings)
------ Machine dependent (-m<blah>) stuff ---------------------------
+ , make_ord_flag defGhcFlag "march=native" (NoArg enableHostCpuFeatures)
, make_ord_flag defGhcFlag "mla664" (noArg (\d -> d { la664 = True }))
@@ -2863,6 +2867,17 @@ setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
setCpuFeature :: CpuFeature -> DynFlags -> DynFlags
setCpuFeature feat dflags = dflags { cpuFeatures = EnumSet.insert feat (cpuFeatures dflags) }
+-- | @-march=native@: enable the CPU features of the host GHC is running on.
+enableHostCpuFeatures :: DynP ()
+enableHostCpuFeatures = do
+ arch <- platformArch . targetPlatform <$> liftEwM getCmdLineState
+ if | arch /= ArchX86 && arch /= ArchX86_64
+ -> addErr "-march=native is only supported on x86 and x86_64 targets"
+ | arch /= hostPlatformArch
+ -> addErr "-march=native is not supported when the target architecture differs from the host's"
+ | otherwise
+ -> upd $ \d -> d { cpuFeatures = cpuFeatures d `mappend` hostX86CpuFeatures }
+
-- | The @-m\<feature\>@ flag for a 'CpuFeature'.
cpuFeatureFlagDep :: CpuFeature -> (Deprecation, Flag (CmdLineP DynFlags))
cpuFeatureFlagDep feat =
=====================================
compiler/GHC/Platform/CpuFeatures.hs
=====================================
@@ -64,8 +64,9 @@ others:
We keep two representations:
- A. 'DynFlags' records the set of flags that were passed, as an
- 'EnumSet' of 'CpuFeature'. Nothing is implied at this stage.
+ A. 'DynFlags' records the set of requested features, as an 'EnumSet' of
+ 'CpuFeature': one per -m<feature> flag passed, plus the features of the
+ host under -march=native. Nothing is implied at this stage.
B. 'initCpuFeatures' turns this set into a 'CpuFeatures' value, applying the
implications and the baseline of the target architecture. This
=====================================
compiler/GHC/Platform/HostCpuFeatures.hs
=====================================
@@ -0,0 +1,41 @@
+{-# LANGUAGE CPP #-}
+
+module GHC.Platform.HostCpuFeatures
+ ( hostX86CpuFeatures
+ ) where
+
+import GHC.Prelude
+
+import GHC.Data.EnumSet (EnumSet)
+import qualified GHC.Data.EnumSet as EnumSet
+import GHC.Platform.CpuFeatures (CpuFeature(..))
+
+import Data.Word (Word64)
+import System.IO.Unsafe (unsafePerformIO)
+
+#include "HostCpuFeaturesX86.h"
+
+#define GHC_X86_FEATURE_CONS(feat, cond) feat :
+
+-- | The features of the table in @HostCpuFeaturesX86.h@, in row order.
+probedX86CpuFeatures :: [CpuFeature]
+probedX86CpuFeatures = GHC_X86_PROBED_FEATURES(GHC_X86_FEATURE_CONS) []
+
+-- | The host's x86 CPU features.
+hostX86CpuFeatures :: EnumSet CpuFeature
+hostX86CpuFeatures = unsafePerformIO $ do
+ mask <- hostX86CpuFeatureMask
+ pure $ EnumSet.fromList
+ [ feat
+ | (bit, feat) <- zip [0 ..] probedX86CpuFeatures
+ , testBit mask bit
+ ]
+{-# NOINLINE hostX86CpuFeatures #-}
+
+#if defined(javascript_HOST_ARCH)
+hostX86CpuFeatureMask :: IO Word64
+hostX86CpuFeatureMask = pure 0
+#else
+foreign import ccall unsafe "ghc_host_x86_cpu_feature_mask"
+ hostX86CpuFeatureMask :: IO Word64
+#endif
=====================================
compiler/HostCpuFeaturesX86.h
=====================================
@@ -0,0 +1,24 @@
+/* The x86 features that -march=native probes. Each row pairs a CpuFeature
+ constructor with the C condition (see cbits/host_cpu_features_x86.c) that
+ detects the feature on the host. SSE and SSE2 are not probed: they are
+ GHC's x86 baseline.
+
+ Row i is bit i of the mask that ghc_host_x86_cpu_feature_mask returns and
+ GHC.Platform.HostCpuFeatures decodes, so the table can hold at most 64
+ rows. */
+#define GHC_X86_PROBED_FEATURES(F) \
+ F(Feat_SSE3, SUPPORTS("sse3")) \
+ F(Feat_SSSE3, SUPPORTS("ssse3")) \
+ F(Feat_SSE4, SUPPORTS("sse4.1")) \
+ F(Feat_SSE4_2, SUPPORTS("sse4.2")) \
+ F(Feat_AVX, SUPPORTS("avx")) \
+ F(Feat_AVX2, SUPPORTS("avx2")) \
+ F(Feat_AVX512F, SUPPORTS("avx512f")) \
+ F(Feat_AVX512BW, SUPPORTS("avx512bw")) \
+ F(Feat_AVX512CD, SUPPORTS("avx512cd")) \
+ F(Feat_AVX512DQ, SUPPORTS("avx512dq")) \
+ F(Feat_AVX512VL, SUPPORTS("avx512vl")) \
+ F(Feat_BMI, SUPPORTS("bmi")) \
+ F(Feat_BMI2, SUPPORTS("bmi2")) \
+ F(Feat_FMA, SUPPORTS_FMA) \
+ F(Feat_GFNI, SUPPORTS_GFNI)
=====================================
compiler/cbits/host_cpu_features_x86.c
=====================================
@@ -0,0 +1,64 @@
+#include <HsFFI.h>
+
+/* Runtime x86 CPU feature detection backing GHC.Platform.HostCpuFeatures
+ (-march=native).
+
+ The __builtin_cpu_* calls below compile to references to libgcc/compiler-rt
+ symbols (__cpu_model & co.), which GHCi's runtime linker can only resolve
+ because the RTS exports them: see RTS_X86_CPU_MODEL_SYMBOLS in
+ rts/RtsSymbols.c. */
+
+#include "HostCpuFeaturesX86.h"
+
+#if defined(__i386__) || defined(__x86_64__)
+
+#define SUPPORTS(name) __builtin_cpu_supports(name)
+
+/* FMA is usable only when the OS saves the AVX register state, but
+ compiler-rt's cpu_model/x86.c reports "fma" from the raw CPUID bit. */
+#define SUPPORTS_FMA (SUPPORTS("fma") && SUPPORTS("avx"))
+
+/* __builtin_cpu_supports accepts "gfni" from GCC 8 and LLVM 8 on, and reads
+ it from __cpu_features2, which libgcc provides only from GCC 8 on. */
+#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 8
+/* A program that links the ghc library from a binary distribution may use
+ an older libgcc. The weak declaration also applies to the builtin's own
+ reference, so such a link succeeds, and we then report no GFNI. */
+extern unsigned int __cpu_features2[] __attribute__((weak));
+#define SUPPORTS_GFNI (__cpu_features2 != 0 && SUPPORTS("gfni"))
+#elif defined(__clang__) \
+ && __clang_major__ >= (defined(__apple_build_version__) ? 11 : 8)
+/* Apple clang numbers its releases separately: 11 is its first based on
+ LLVM 8. Clang marks its reference dso_local, so a weak declaration would
+ not help: an older libgcc fails the link. */
+#define SUPPORTS_GFNI SUPPORTS("gfni")
+#else
+#define SUPPORTS_GFNI 0
+#endif
+
+HsWord64 ghc_host_x86_cpu_feature_mask(void)
+{
+ __builtin_cpu_init();
+
+ HsWord64 mask = 0;
+ int bit = 0;
+
+#define GHC_X86_PROBE(feat, cond) \
+ if (cond) { mask |= (HsWord64)1 << bit; } \
+ bit++;
+
+ GHC_X86_PROBED_FEATURES(GHC_X86_PROBE)
+
+#undef GHC_X86_PROBE
+
+ return mask;
+}
+
+#else
+
+HsWord64 ghc_host_x86_cpu_feature_mask(void)
+{
+ return 0;
+}
+
+#endif
=====================================
compiler/ghc.cabal.in
=====================================
@@ -32,6 +32,7 @@ extra-source-files:
GHC/Builtin/primops.txt.pp
Unique.h
CodeGen.Platform.h
+ HostCpuFeaturesX86.h
-- Shared with rts via hard-link at configure time. This is safer
-- for Windows, where symlinks don't work out of the box, so we
-- can't just commit some in git.
@@ -186,6 +187,7 @@ Library
c-sources:
cbits/cutils.c
cbits/genSym.c
+ cbits/host_cpu_features_x86.c
cbits/keepCAFsForGHCi.c
hs-source-dirs:
@@ -691,6 +693,7 @@ Library
GHC.Platform.AArch64
GHC.Platform.Constants
GHC.Platform.CpuFeatures
+ GHC.Platform.HostCpuFeatures
GHC.Platform.LA64
GHC.Platform.NoRegs
GHC.Platform.PPC
=====================================
docs/users_guide/expected-undocumented-flags.txt
=====================================
@@ -55,6 +55,7 @@
-instantiated-with
-keep-hi-file
-keep-o-file
+-march=native
-no-keep-hi-file
-no-keep-o-file
-no-link
=====================================
docs/users_guide/using.rst
=====================================
@@ -1887,6 +1887,30 @@ Some flags only make sense for particular target platforms.
so this flag has no effect when used with the :ref:`native code generator <native-code-gen>`
or the :ref:`LLVM backend <llvm-code-gen>`.
+.. ghc-flag:: -march=native
+ :shortdesc: (x86 only) Enable the CPU features of the host
+ :type: dynamic
+ :category: platform-options
+
+ (x86 only) Probe the CPU of the machine running GHC and enable the
+ corresponding ``-m...`` CPU-feature options (for example ``-msse4.2``,
+ ``-mavx2``, ``-mbmi2``, ``-mfma``). The detected features apply to both the
+ :ref:`native code generator <native-code-gen>` and the
+ :ref:`LLVM backend <llvm-code-gen>`.
+
+ The detected features are enabled in addition to any ``-m...`` options
+ given explicitly, regardless of their order on the command line.
+
+ .. warning::
+
+ Code compiled with ``-march=native`` may use instructions that are not
+ available on other CPUs, and is therefore not portable to a different
+ machine.
+
+ The flag is rejected on other targets. A cross-compiler also rejects it
+ when its target architecture differs from the one GHC itself runs on, since
+ the probed CPU then says nothing about the target.
+
Haddock
-------
=====================================
m4/fp_gcc_version.m4
=====================================
@@ -16,9 +16,10 @@ AC_DEFUN([FP_GCC_VERSION], [
AC_MSG_CHECKING([version of gcc])
fp_cv_gcc_version="`$CC -v 2>&1 | sed -n -e '1,/version /s/.*version [[^0-9]]*\([[0-9.]]*\).*/\1/p'`"
AC_MSG_RESULT([$fp_cv_gcc_version])
- # 4.7 is needed for __atomic_ builtins.
- FP_COMPARE_VERSIONS([$fp_cv_gcc_version], [-lt], [4.7],
- [AC_MSG_ERROR([Need at least gcc version 4.7 (newer recommended)])])
+ # 6 is needed for the AVX-512 names of __builtin_cpu_supports, which
+ # -march=native probes.
+ FP_COMPARE_VERSIONS([$fp_cv_gcc_version], [-lt], [6],
+ [AC_MSG_ERROR([Need at least gcc version 6 (newer recommended)])])
])
AC_SUBST([GccVersion], [$fp_cv_gcc_version])
else
=====================================
rts/RtsSymbols.c
=====================================
@@ -1050,6 +1050,35 @@ extern char **environ;
#define RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
#endif
+// libgcc/compiler-rt symbols behind __builtin_cpu_supports and
+// __builtin_cpu_init, which compiler/cbits/host_cpu_features_x86.c uses
+// (-march=native). Without them the runtime linker cannot load the ghc
+// library's object code, e.g. for plugins in a statically linked GHCi.
+#if defined(i386_HOST_ARCH) || defined(x86_64_HOST_ARCH)
+
+// Weak: missing before GCC 8 and LLVM 8.
+extern StgWord __cpu_features2[] __attribute__((weak));
+
+// Alpine's and Gentoo's musl GCCs patch __builtin_cpu_init to call this
+// alias of __cpu_indicator_init. Weak: other musl toolchains lack it.
+#if defined(linux_HOST_OS) && !defined(__GLIBC__)
+extern void __cpu_indicator_init_local(void) __attribute__((weak));
+#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS \
+ SymI_HasProto(__cpu_indicator_init_local)
+#else
+#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS
+#endif
+
+#define RTS_X86_CPU_MODEL_SYMBOLS \
+ SymI_NeedsProto(__cpu_indicator_init) \
+ SymI_NeedsDataProto(__cpu_model) \
+ SymI_HasDataProto(__cpu_features2) \
+ RTS_X86_CPU_INIT_LOCAL_SYMBOLS
+
+#else
+#define RTS_X86_CPU_MODEL_SYMBOLS
+#endif
+
// Symbols defined by libc
#define RTS_LIBC_SYMBOLS \
SymI_HasProto_redirect(atexit, atexit, STRENGTH_STRONG, SYM_TYPE_CODE) /* See Note [Strong symbols] */ \
@@ -1210,6 +1239,7 @@ RTS_OPENBSD_ONLY_SYMBOLS
RTS_LIBC_SYMBOLS
RTS_LIBGCC_SYMBOLS
RTS_ARCH_LIBGCC_SYMBOLS
+RTS_X86_CPU_MODEL_SYMBOLS
RTS_FINI_ARRAY_SYMBOLS
RTS_LIBFFI_SYMBOLS
RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
@@ -1265,6 +1295,7 @@ RtsSymbolVal const * getRtsSymbols(void) {
RTS_OPENBSD_ONLY_SYMBOLS
RTS_LIBGCC_SYMBOLS
RTS_ARCH_LIBGCC_SYMBOLS
+ RTS_X86_CPU_MODEL_SYMBOLS
RTS_FINI_ARRAY_SYMBOLS
RTS_LIBFFI_SYMBOLS
RTS_ARM_OUTLINE_ATOMIC_SYMBOLS
=====================================
testsuite/tests/driver/Makefile
=====================================
@@ -500,6 +500,15 @@ withRtsOpts:
T3364:
-"$(TEST_HC)" $(TEST_HC_OPTS) -H
+# GHC and the C compiler should detect the same host CPU features.
+.PHONY: march_native_matches_cc
+march_native_matches_cc:
+ "$(TEST_HC)" $(TEST_HC_OPTS) -march=native -E -cpp march_native_matches_cc.hs -o ghc.out
+ "$(TEST_CC)" $(TEST_CC_OPTS) -march=native -E -x c march_native_matches_cc.hs > cc.out
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' ghc.out > ghc.feats
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' cc.out > cc.feats
+ diff -u ghc.feats cc.feats
+
.PHONY: T706
T706:
cp T706a.hs T706.hs
=====================================
testsuite/tests/driver/all.T
=====================================
@@ -223,6 +223,15 @@ test('T9938B', [], makefile_test, [])
test('T9963', exit_code(1), run_command,
['{compiler} --interactive -ignore-dot-ghci --print-libdir'])
+test('march_native_unsupported_arch',
+ [when(arch('x86_64') or arch('i386'), skip)],
+ compile_fail,
+ ['-march=native'])
+
+test('march_native_matches_cc',
+ [unless(arch('x86_64') or arch('i386'), skip), when(config.cross, skip)],
+ makefile_test, [])
+
test('T10219', normal, run_command,
# `-x hspp` in make mode should work.
# Note: need to specify `-x hspp` before the filename.
=====================================
testsuite/tests/driver/march_native_matches_cc.hs
=====================================
@@ -0,0 +1,40 @@
+-- BMI and BMI2 are not listed: GHC defines no macros for them.
+#if defined(__SSE3__)
+feat sse3
+#endif
+#if defined(__SSSE3__)
+feat ssse3
+#endif
+#if defined(__SSE4_1__)
+feat sse4.1
+#endif
+#if defined(__SSE4_2__)
+feat sse4.2
+#endif
+#if defined(__AVX__)
+feat avx
+#endif
+#if defined(__AVX2__)
+feat avx2
+#endif
+#if defined(__AVX512F__)
+feat avx512f
+#endif
+#if defined(__AVX512BW__)
+feat avx512bw
+#endif
+#if defined(__AVX512CD__)
+feat avx512cd
+#endif
+#if defined(__AVX512DQ__)
+feat avx512dq
+#endif
+#if defined(__AVX512VL__)
+feat avx512vl
+#endif
+#if defined(__FMA__)
+feat fma
+#endif
+#if defined(__GFNI__)
+feat gfni
+#endif
=====================================
testsuite/tests/driver/march_native_unsupported_arch.hs
=====================================
@@ -0,0 +1 @@
+module M where
=====================================
testsuite/tests/driver/march_native_unsupported_arch.stderr
=====================================
@@ -0,0 +1,2 @@
+ghc: on the commandline: -march=native is only supported on x86 and x86_64 targets
+Usage: For basic information, try the `--help' option.
=====================================
testsuite/tests/rts/symbols/Main.hs
=====================================
@@ -31,6 +31,13 @@ ignoreSymbols = S.fromList [
"__umoddi3",
"__umodti3",
+ -- Defined in libgcc/compiler-rt. RtsSymbols.c declares them on x86 only
+ -- (+Declared)
+ "__cpu_features2",
+ "__cpu_indicator_init",
+ "__cpu_indicator_init_local",
+ "__cpu_model",
+
-- These may be a CPP mismatch between rts/prim/vectorQuotRem.c and RtsSymbols.c
"hs_quotInt16X8",
"hs_quotInt32X4",
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/3575503310e3411fc82323c705b66dc…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/3575503310e3411fc82323c705b66dc…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/sjakobi/cmm-unreachable-blocks-docs] Correct some comments about unreachable Cmm blocks
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/cmm-unreachable-blocks-docs at Glasgow Haskell Compiler / GHC
Commits:
1338ed88 by Simon Jakobi at 2026-11-23T05:09:21+01:00
Correct some comments about unreachable Cmm blocks
* ContFlowOpt claimed that maybe_concat drops every block that has no
predecessors left. But a block that loses its predecessors to
shortcutting stays in the graph.
* The linear register allocator claimed that the Cmm pipeline keeps
unreachable blocks away from it. But the NCG's own Cmm optimisations
can make more blocks unreachable after the Cmm pipeline has run. It
is sccBlocks that discards unreachable code before register
allocation (#7574).
Also:
* Remove a commented-out trace in the linear allocator that predates
#7574.
* Say in Note [unreachable blocks] that any pass in cpsTop can encounter
unreachable blocks. Rename it to Note [Unreachable blocks in the Cmm
pipeline], so its title no longer differs only in case from an
unrelated Note in GHC.Cmm.Dataflow.
Context: #27368
Assisted-by: Claude Fable 5.2
- - - - -
4 changed files:
- compiler/GHC/Cmm.hs
- compiler/GHC/Cmm/ContFlowOpt.hs
- compiler/GHC/Cmm/Pipeline.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
Changes:
=====================================
compiler/GHC/Cmm.hs
=====================================
@@ -154,7 +154,7 @@ toBlockMap (CmmGraph {g_graph=GMany NothingO body NothingO}) = body
-- | Print the blocks reachable from the entry, in reverse postorder.
--
-- Under @-dppr-debug@ the unreachable blocks stored in the graph are appended
--- too. See Note [unreachable blocks] in "GHC.Cmm.Pipeline".
+-- too. See Note [Unreachable blocks in the Cmm pipeline] in "GHC.Cmm.Pipeline".
pprCmmGraph :: Platform -> CmmGraph -> SDoc
pprCmmGraph platform g
= text "{" <> text "offset"
=====================================
compiler/GHC/Cmm/ContFlowOpt.hs
=====================================
@@ -338,11 +338,9 @@ blockConcat splitting_procs g@CmmGraph { g_entry = entry_id }
-- Functions for incrementing and decrementing number of predecessors. If
-- decrementing would set the predecessor count to 0, we remove entry from the
-- map.
--- Invariant: if a block has no predecessors it should be dropped from the
--- graph because it is unreachable. maybe_concat is constructed to maintain
--- that invariant, but calling replaceLabels may introduce unreachable blocks.
--- We rely on subsequent passes in the Cmm pipeline to remove unreachable
--- blocks.
+-- Shortcutting can leave a block without predecessors. Such a block is
+-- unreachable but stays in the graph.
+-- See Note [Unreachable blocks in the Cmm pipeline] in GHC.Cmm.Pipeline.
incPreds, decPreds :: BlockId -> LabelMap Int -> LabelMap Int
incPreds bid edges = mapInsertWith (+) bid 1 edges
decPreds bid edges = case mapLookup bid edges of
=====================================
compiler/GHC/Cmm/Pipeline.hs
=====================================
@@ -79,6 +79,8 @@ cpsTop logger platform cfg dus proc =
-- later passes by removing lots of empty blocks, so we do it
-- even when optimisation isn't turned on.
--
+ -- NB: It may leave unreachable blocks behind!
+ -- See Note [Unreachable blocks in the Cmm pipeline]
CmmProc h l v g <- {-# SCC "cmmCfgOpts(1)" #-}
return $ cmmCfgOptsProc splitting_proc_points proc
dump Opt_D_dump_cmm_cfg "Post control-flow optimisations (1)" l g
@@ -173,7 +175,7 @@ cpsTop logger platform cfg dus proc =
then map (cmmCfgOptsProc splitting_proc_points) g
else g
g <- return $ map (removeUnreachableBlocksProc platform) g
- -- See Note [unreachable blocks]
+ -- See Note [Unreachable blocks in the Cmm pipeline]
dumps Opt_D_dump_cmm_cfg "Post control-flow optimisations (2)" g
return (dus, Left (cafEnv, g))
@@ -351,13 +353,19 @@ _GLOBAL_OFFSET_TABLE_, regardless of which entry point we arrived via.
-}
-{- Note [unreachable blocks]
- ~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [Unreachable blocks in the Cmm pipeline]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The control-flow optimiser sometimes leaves unreachable blocks behind
containing junk code. These aren't necessarily a problem, but
removing them is good because it might save time in the native code
generator later.
+Passes in cpsTop must not assume that every block is reachable. Stack
+layout and sinking drop unreachable blocks as a side effect of
+rebuilding the graph from revPostorder, but both can be skipped.
+removeUnreachableBlocksProc at the end of cpsTop removes those that
+remain, along with their info tables.
+
To make unreachable blocks visible in -ddump-cmm-* output, add -dppr-debug.
-}
=====================================
compiler/GHC/CmmToAsm/Reg/Linear.hs
=====================================
@@ -311,10 +311,6 @@ process entry_ids block_live =
go [] next_round accum madeProgress
| not madeProgress
- {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming.
- pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out."
- ( text "Unreachable blocks:"
- $$ vcat (map ppr next_round)) -}
= return $ reverse accum
| otherwise
@@ -861,12 +857,9 @@ allocateRegsAndSpill reading keep spills alloc (r@(VirtualRegWithFormat vr vrFmt
| otherwise -> doSpill WriteMem
Nothing | reading ->
pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr vr)
- -- NOTE: if the input to the NCG contains some
- -- unreachable blocks with junk code, this panic
- -- might be triggered. Make sure you only feed
- -- sensible code into the NCG. In GHC.Cmm.Pipeline we
- -- call removeUnreachableBlocks at the end for this
- -- reason.
+ -- NOTE: unreachable blocks with junk code could
+ -- trigger this panic, so sccBlocks in
+ -- GHC.CmmToAsm.Reg.Liveness discards them (#7574).
| otherwise -> doSpill WriteNew
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1338ed88831dff34e893234744533aa…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1338ed88831dff34e893234744533aa…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/sjakobi/cmm-unreachable-blocks-docs] Correct some comments about unreachable Cmm blocks
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/cmm-unreachable-blocks-docs at Glasgow Haskell Compiler / GHC
Commits:
e8cf6c77 by Simon Jakobi at 2026-11-23T04:08:13+01:00
Correct some comments about unreachable Cmm blocks
* ContFlowOpt claimed that maybe_concat drops every block that has no
predecessors left. But a block that loses its predecessors to
shortcutting stays in the graph.
* The linear register allocator claimed that the Cmm pipeline keeps
unreachable blocks away from it. But the NCG's own Cmm optimisations
can make more blocks unreachable after the Cmm pipeline has run. It
is sccBlocks that discards unreachable code before register
allocation (#7574).
Also:
* Remove a commented-out trace in the linear allocator that predates
#7574.
* Say in Note [Unreachable blocks] that the passes between control-flow
optimisation and stack layout can encounter unreachable blocks.
Capitalise the title of the Note.
Context: #27368
Assisted-by: Claude Fable 5.2
- - - - -
4 changed files:
- compiler/GHC/Cmm.hs
- compiler/GHC/Cmm/ContFlowOpt.hs
- compiler/GHC/Cmm/Pipeline.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
Changes:
=====================================
compiler/GHC/Cmm.hs
=====================================
@@ -154,7 +154,7 @@ toBlockMap (CmmGraph {g_graph=GMany NothingO body NothingO}) = body
-- | Print the blocks reachable from the entry, in reverse postorder.
--
-- Under @-dppr-debug@ the unreachable blocks stored in the graph are appended
--- too. See Note [unreachable blocks] in "GHC.Cmm.Pipeline".
+-- too. See Note [Unreachable blocks] in "GHC.Cmm.Pipeline".
pprCmmGraph :: Platform -> CmmGraph -> SDoc
pprCmmGraph platform g
= text "{" <> text "offset"
=====================================
compiler/GHC/Cmm/ContFlowOpt.hs
=====================================
@@ -338,11 +338,9 @@ blockConcat splitting_procs g@CmmGraph { g_entry = entry_id }
-- Functions for incrementing and decrementing number of predecessors. If
-- decrementing would set the predecessor count to 0, we remove entry from the
-- map.
--- Invariant: if a block has no predecessors it should be dropped from the
--- graph because it is unreachable. maybe_concat is constructed to maintain
--- that invariant, but calling replaceLabels may introduce unreachable blocks.
--- We rely on subsequent passes in the Cmm pipeline to remove unreachable
--- blocks.
+-- A block whose predecessor count drops to 0 is unreachable, but stays in the
+-- graph. We rely on subsequent passes in the Cmm pipeline to remove
+-- unreachable blocks.
incPreds, decPreds :: BlockId -> LabelMap Int -> LabelMap Int
incPreds bid edges = mapInsertWith (+) bid 1 edges
decPreds bid edges = case mapLookup bid edges of
=====================================
compiler/GHC/Cmm/Pipeline.hs
=====================================
@@ -173,7 +173,7 @@ cpsTop logger platform cfg dus proc =
then map (cmmCfgOptsProc splitting_proc_points) g
else g
g <- return $ map (removeUnreachableBlocksProc platform) g
- -- See Note [unreachable blocks]
+ -- See Note [Unreachable blocks]
dumps Opt_D_dump_cmm_cfg "Post control-flow optimisations (2)" g
return (dus, Left (cafEnv, g))
@@ -351,13 +351,19 @@ _GLOBAL_OFFSET_TABLE_, regardless of which entry point we arrived via.
-}
-{- Note [unreachable blocks]
+{- Note [Unreachable blocks]
~~~~~~~~~~~~~~~~~~~~~~~~~
The control-flow optimiser sometimes leaves unreachable blocks behind
containing junk code. These aren't necessarily a problem, but
removing them is good because it might save time in the native code
generator later.
+Stack layout drops them as a side effect of rebuilding the graph from
+revPostorder, so the passes between control-flow optimisation and stack
+layout may encounter them. removeUnreachableBlocksProc at the end of
+cpsTop removes the blocks orphaned by the second round of control-flow
+optimisation, along with their info tables.
+
To make unreachable blocks visible in -ddump-cmm-* output, add -dppr-debug.
-}
=====================================
compiler/GHC/CmmToAsm/Reg/Linear.hs
=====================================
@@ -311,10 +311,6 @@ process entry_ids block_live =
go [] next_round accum madeProgress
| not madeProgress
- {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming.
- pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out."
- ( text "Unreachable blocks:"
- $$ vcat (map ppr next_round)) -}
= return $ reverse accum
| otherwise
@@ -861,12 +857,9 @@ allocateRegsAndSpill reading keep spills alloc (r@(VirtualRegWithFormat vr vrFmt
| otherwise -> doSpill WriteMem
Nothing | reading ->
pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr vr)
- -- NOTE: if the input to the NCG contains some
- -- unreachable blocks with junk code, this panic
- -- might be triggered. Make sure you only feed
- -- sensible code into the NCG. In GHC.Cmm.Pipeline we
- -- call removeUnreachableBlocks at the end for this
- -- reason.
+ -- NOTE: unreachable blocks with junk code could
+ -- trigger this panic, so sccBlocks in
+ -- GHC.CmmToAsm.Reg.Liveness discards them (#7574).
| otherwise -> doSpill WriteNew
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/e8cf6c773ed6d1452c54068ad92b4d9…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/e8cf6c773ed6d1452c54068ad92b4d9…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/sjakobi/cmm-unreachable-blocks-docs] 89 commits: Documentation for the Core data constructors
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/cmm-unreachable-blocks-docs at Glasgow Haskell Compiler / GHC
Commits:
56757900 by Sebastian Graf at 2026-11-04T20:36:47+01:00
Documentation for the Core data constructors
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
9f57c265 by Sylvain Henry at 2026-11-06T06:46:15-05:00
ghc-internal: avoid unnecessary allocations in bignum division (#27231)
Avoid unnecessary allocations in bignum division in the Haskell (native)
backend. The long-division loop used to allocate a fresh BigNat for the
partial product on every iteration, plus one more per quotient-digit
correction; it now subtracts the partial product in place and
materializes nothing.
The quotient-digit estimate is also refined against the second-highest
divisor word, so the add-back correction runs at most once per
iteration.
bignat_quotrem_normalized now requires a divisor of at least 2 words, so
bignat_quotrem dispatches 1-word divisors to bignat_quotrem_word.
See Note [Knuth division loop] and Note [Fused multiply-subtract for
long division] in GHC.Internal.Bignum.Backend.Native.
Measured on the new T27231 perf test (10000 native-backend 8192/2048-bit
Integer quotRem calls): bytes allocated drops from 305 MB to 52 MB (-83%).
Improvement on CI (x86-64-linux-deb13-int_native):
space_leak_001(normal) run/alloc 12,492,185,536 9,073,055,928 -27.4% GOOD
Metric Decrease:
space_leak_001
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
c5b80f4e by mangoiv at 2026-11-06T06:46:57-05:00
ci: build and test stage
Split up CI in a build and test stage:
1. in the build stage, just produce a bindist as well as running the
stage1 tests
2. in the test stage, install the bindist, then run the testsuite with
out of tree args
- - - - -
e4b1c892 by mangoiv at 2026-11-06T06:46:57-05:00
ci: reorder packaging and testing stages
- - - - -
19901b41 by mangoiv at 2026-11-06T06:46:57-05:00
ci: out of tree compiler does not imply no hadrian being available
- - - - -
83a860a7 by mangoiv at 2026-11-06T06:46:57-05:00
ci: don't do msys deps check on stage1 compiler
- - - - -
abf5b3af by mangoiv at 2026-11-06T06:46:57-05:00
testsuite: allow metric decreases on windows
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13253-spj
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
9185f1ab by mangoiv at 2026-11-06T06:46:57-05:00
ci: stop using ellipses in testsuite output and output env before invoking hadrian
- - - - -
bf9ece2b by Simon Jakobi at 2026-11-06T06:47:42-05:00
testsuite: Skip the changelog-d test in CI
Full-build validate jobs run the whole testsuite and thus repeated the
changelog validation that the dedicated lint-changelog job had already
reported in the early tool-lint stage.
Skip the test when GITLAB_CI is set, making lint-changelog the only CI
check of changelog.d while keeping the test available in local
testsuite runs.
Fixes #27325.
Assisted-by: Claude Fable 5
- - - - -
ef6adb30 by ARATA Mizuki at 2026-11-06T06:48:31-05:00
testsuite: Mark T367_letnoescape fragile for the optllvm way
It was marked broken, but it is now unexpectedly passing on aarch64-linux-deb13-validate+llvm.
Marking it fragile for now.
See #7292
- - - - -
1db5f9d7 by Rodrigo Mesquita at 2026-11-06T06:49:13-05:00
interp: Make resumeExec and ExecBreak use `Resume` directly
Previously, `Resume` contexts were just put directly in the global
interactive environment state, so they were only accessible through it.
However, in the context of multi-threaded debugging, in that many
threads may hit breakpoints, it no longer suffices to have a global
linear list of breakpoints hit. We need a per-breakpoint Resume context
and need to be able to wield it directly rather than going through a
global context.
The driving changes of this commit are:
- Put the Resume data in ExecBreak
- Make resumeExec receive a Resume as an argument
This also simplifies the interpreter in that we no longer necessarily
rely on the global interactive state to resume a thread. We can do it
directly from the ExecBreak.
The interactive context still maintains a stack of resumes, but
`resumeExec` can no longer pop the resume it resumes off of the
breakpoints stack, since it is no longer guaranteed to be resuming the
first in that list. Hence, callers of `resumeExec` must update ic_resume
on their own.
Fixes #28058
- - - - -
fd00a88c by Rodrigo Mesquita at 2026-11-06T06:49:54-05:00
Per-thread break-on exception (TSO_STOP_ON_EXCEPTION)
The `-fbreak-on-exception` flag allows the interactive interpreter to stop
when a synchronous exception is raised.
However, this is a global toggle backed by a global variable in the RTS
(rts_stop_on_exception) which is not compatible with a multi-threaded
debugger where we may want to stop if some threads raise a synchronous
exception but not other.
This commit makes -break-on-exception similar to step-next and step-out
where there is a per-thread toggle on each TSO (TSO_STOP_ON_EXCEPTION),
and that break-on-exception set in EvalOpts when resuming a statement
only affect the thread being resumed.
Fixes #28068
- - - - -
d735b507 by Andrea Vezzosi at 2026-11-06T06:50:35-05:00
driver: Don't let -dynamic unset -fsplit-sections
`addWay' WayDyn` used to unset Opt_SplitSections, so -fsplit-sections was
ignored if it came before -dynamic, but worked if it came after.
The -fsplit-sections -dynamic combination has legitimate uses, e.g. an
executable can be linked dynamically against libraries and still have dead code
from its own sources to eliminate. Or the same objects could be used for both
static archives and shared objects.
The removal of Opt_SplitSections was also motivated by problems on Darwin.
It is now done in `makeDynFlagsConsistent` instead, see Note [Split sections are not
supported on Mach-O].
For consistency, we also keep Opt_SplitSections when `dynamicNow` is activated.
There is a cost of larger .dyn_o (but not .so) files and slower link times (esp.
with ld.bfd), but does not seem significant enough to warrant special casing.
Fixes #28061
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
10e36bd2 by Alan Zimmerman at 2026-11-06T06:51:18-05:00
EPA: Use AnnList in AnnClassDecl
Capture parser layout
- - - - -
20334e1d by sheaf at 2026-11-06T06:52:06-05:00
Avoid panic in 'solveImplicationsUsingUnsatGiven'
Commit 52a4d1da refactored this code to use 'setWantedDict' which panics
for equality constraints. This commit fixes that by explicitly handling
HoleDest.
Fixes #28081
- - - - -
0423f413 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: add tests for the IO manager lock-up of #21969
T21969a 'closeFdWith' takes every 'EventManager''s 'callbackTableVar'
inside 'uninterruptibleMask_' and only puts them back on the paths
that do not throw, so a throw from 'closeFd_' leaves those MVars
empty for good. Afterwards every 'threadWaitRead' and
'closeFdWith' on an fd in the same bucket blocks forever.
T21969b 'closeFdWith' runs the fd's callbacks while asynchronous exceptions
are uninterruptibly masked, so a callback that blocks makes the
thread calling it permanently unkillable.
T21969c 'closeFd_' drops the registrations before telling the backend to
forget the fd, so when the backend throws the fd is never closed
and the threads waiting on it are never woken.
T21969d the cleanup handler of 'threadWait' calls 'unregisterFd_', which
throws on backend errors. It runs inside the handler for the
asynchronous exception being delivered, so its exception replaces
that one: 'killThread' returns but 'ThreadKilled' never arrives.
T21969e an exception from re-arming an fd escapes the poll loop, and 'loop'
turns it into 'cleanup mgr': the 'EventManager' of that capability
is shut down and every thread using it is left blocked. This is
the lock-up of #21969 itself.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5c197e2e by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Make the IO manager cope with errors from the polling backend (#21969)
Three changes in 'GHC.Internal.Event.Thread': 'closeFdWith' puts every
'callbackTableVar' back on the paths that throw too and no longer skips the
callbacks when 'close' fails, those callbacks now run under the 'mask_' of
'close_loop' rather than uninterruptibly masked, and the cleanup of
'threadWait' ignores a failure from 'unregisterFd_'.
This fixes T21969a, T21969b and T21969d, and clears their expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cb765ded by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let backend errors abandon the close of a file descriptor (#21969)
'closeFd_' and 'closeFd' now ignore errors from telling the backend to forget
the fd: the registration is being torn down and the error says it is already
gone. 'registerFd_' still reports them (!10643), where the caller has to
learn that the registration did not happen. Both also test
'I.elEvent oldEls /= mempty' rather than 'oldEls /= mempty'.
This fixes T21969c, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
9073bc43 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let a backend error take down a capability's IO manager (#21969)
A failure to re-arm an fd in 'selectCallbacks' is now handled the way
'registerFd_' handles one (!10643): the registrations are taken back out of
the callback table and returned, so their callbacks run and the waiting
threads find out for themselves instead of hanging. Checked on aarch64 Linux
(epoll) and aarch64 macOS (kqueue), 10 runs each way.
This fixes T21969e, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cdff4e76 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let the deregistration of threadWaitSTM throw either (#21969)
'threadWaitReadSTM' and 'threadWaitWriteSTM' return the action that gives up
interest in the fd as the second component of their pair, and it was
return (waitAction, unregisterFd_ mgr reg >> return ())
'unregisterFd_' talks to the polling backend, which throws on errors such as
ENOENT and EBADF -- which is how a backend reports an fd it no longer knows,
once that fd has been closed without going through 'closeFdWith'.
That is the same shape as the cleanup of 'threadWait', which the rest of this
series made quiet, and it is the same on both counts. There is nothing to
decide: the registration is being abandoned, and "the backend does not know
this fd" is the state the action is trying to reach. And it does harm: the
action is what a caller uses from the cleanup of a 'bracket', where an
exception out of it replaces whatever was being propagated.
It now goes through 'quietUnregisterFd', as the cleanup of 'threadWait' does,
and that function's comment covers both callers.
T21969f covers it, and is deterministic on both backends: dropping the only
registration changes the event set, so 'unregisterFd_' always reaches the
backend.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
a7ed305b by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: let T21969 run on FreeBSD, and unmark it (#21969, #25512)
T21969 now carries the descriptor from 'createPipe' instead of recovering it
with 'handleToFd', which rejects the 'DuplexHandle' that FreeBSD's
bidirectional pipes become and killed the test in setup there (#25512). The
expect_broken goes with it: with the descriptor problem out of the way the
test times out on master, so it can only be unmarked on top of this series.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
3074ae61 by Sylvain Henry at 2026-11-08T10:21:50-05:00
rts: heap census counts every small pinned object
Blocks of small pinned objects carry BF_LARGE as well as BF_PINNED but
hold many objects. heapCensusChain treated every BF_LARGE block whose
first object is an ARR_WORDS as holding that single object, a workaround
for the slop left by shrinkMutableByteArray# (#11627). So every heap
profile mode under-reported pinned byte arrays, i.e. ByteString payloads.
Shrinking now writes a slop marker that skipSlop understands (#19048,
#27585), so the block walk is safe for large and pinned blocks alike.
The block that a capability fills with small pinned objects stays
attached to the capability until it is full (see allocatePinned), so it
is on no generation list and the census never saw its objects. heapCensus
now walks cap->pinned_object_block too.
A pinned block is kept or freed as a whole (#28005), so dead pinned
objects are counted until their block is freed. T7275 gains one sample in
which its dead small arrays still show. The user guide and changelog
document this.
T7257 retains most of its pinned blocks and takes a census at every GC
(+RTS -i0 -hT), so walking every pinned object made it 7x slower and it
hit the CI timeout. It now runs 1000000 iterations instead of 5000000.
Metric Decrease:
T7257
Fixes #28000
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
16fd075a by Sylvain Henry at 2026-11-08T10:22:39-05:00
rts: fix GC CPU time accounting with idle GC threads (#26169)
stat_endGC summed gc_end_cpu - gc_start_cpu over every GC thread, but
only the threads that take part in a collection set these fields, and
new_gc_thread did not initialise them. With -qn below the capability
count, the first collection after setNumCapabilities added garbage to
the GC CPU time.
Let each participating thread add its own CPU time to an accumulator
in stat_endGCWorker, and let stat_endGC take the total. This removes
the loop over gc_threads, the reset from #21082 and the gc_end_cpu
field. Also drop the unused gc_end_elapsed field.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
0ef732e2 by Sylvain Henry at 2026-11-08T10:23:30-05:00
Serialized: encode numbers with LEB128
serializeWithData used the Binary instances of Data.Binary for the
numbers in a ConstrRep. They have a fixed width: 8 bytes for the
constructor index (an Int) and 5 bytes for a small Integer. Each
element of a [Int] cost 15 bytes.
Now the constructor representation is one unsigned LEB128 number that
also contains the index of an algebraic constructor, and the payloads
(Integer, Rational, Char) are LEB128 encoded. Most constructors take
one byte, and small numbers two. See Note [Serialized encoding].
Sizes measured by the T16841 test:
[1..100] :: [Int] 1509 -> 338 bytes
"helloworld" 119 -> 31 bytes
2^100 :: Integer 24 -> 16 bytes
Just True 18 -> 2 bytes
3.25 :: Double 11 -> 3 bytes
42 :: Int 6 -> 2 bytes
A new test, SerializedRoundTrip, round-trips values at the boundaries
of the encoding (negative numbers, big Integers, Rationals, Chars).
Follow-up to !16841 (#28002).
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
22344fbc by Sylvain Henry at 2026-11-08T10:24:21-05:00
docs: fix duplicate label in qualified_strings.rst
The file started with the label "multiline-strings", copied from
multiline_strings.rst. Sphinx warned about the duplicate label on every
build. Use the label "qualified-strings" instead.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
b7022624 by Alan Zimmerman at 2026-11-08T10:25:02-05:00
EPA: Use LHsLocalBinds instead of HsLocalBinds
This reverses an earlier change, and brings processing of local binds
into alignement with the exact printing principle that the LocatedA
contents provide the location and extent of the enclosed item,
together with any comments or context-specific trailing items like
commas or semi colons.
The internal TTG extension points only carry exact print annotations
related to printing the item within its bounds.
This change brings back the problem of EmptyLocalBinds, which by
definition cannot have a location. These get a noSrcSpan location,
which is ignored in the exact printing process.
- - - - -
bc2fae45 by Rodrigo Mesquita at 2026-11-08T18:37:40-05:00
Build EvalOpts once per exec rather than per breakpoint stop
We were unnecessarily constructing `eval_opts` in `handleRunStatus`
(which is run many times in a loop until we hit a breakpoint we care
about, e.g. when :steplocal), despite the `eval_opts` being constant
across all these runs.
So, construct `eval_opts` outside `handleRunStatus` and share the value
in all loop calls. The loop always uses the same eval_opts, so no point
in constructing them inside `handleRunStatus` from scratch every time.
I found out about the significance of this re-construction of `EvalOpts`
when I added a record update of `eval_opts` *after* the construction
from scratch inside `handleRunStatus` that regressed allocations
significantly.
This improves the performance of `interpreter_steplocal` on my machine:
Baseline
Test Metric value New value Change
-------------------------------------------------------------------------
interpreter_steplocal(ghci) ghc/alloc 459,845,696 449,843,480 -2.2%
Fixes #28068
- - - - -
ba579288 by Rodrigo Mesquita at 2026-11-08T18:38:21-05:00
refactor: move and order helper functions in GHCi.Run
A small refactor to the order of top-level functions in GHCi.Run
- - - - -
24927752 by Luite Stegeman at 2026-11-09T09:21:24-05:00
rts: add missing nonmoving write barrier in out-of-line array copies
The out-of-line entries stg_copyArrayzh/stg_copyMutableArrayzh (taken
whenever the element count of copyArray#/copyMutableArray# is not a
compile-time constant) didn't push the overwritten elements to the
nonmoving collector's remembered set.
Fixes #27376
- - - - -
6dbcca65 by Rodrigo Mesquita at 2026-11-09T09:22:06-05:00
interp: Set per-thread break flags consistently on eval/resume
Currently, the per-thread flags are:
- Single-step: Stop at the immediate next breakpoint in this thread
- Step-out: Stop at the next continuation with a breakpoint this thread
returns to.
- Break-on-exception: Stop the next time a synchronous exception is
raised in this thread.
Originally, these flags were all set globally across all threads. More
recently, these flags are set per-thread when `resume`ing that thread,
but globally when starting the evaluation of a new expression
(`evalStmt`).
With this commit, we now use per-TSO flags in both scenarios evaluating
expressions in the interpreter (`evalStmt` and `resumeStmt`).
- In `resumeStmt` we set the `EvalOpts` specifically in the `ThreadId`
being resumed.
- In `evalStmt`, we set the `EvalOpts` exclusively on the sandbox thread
we fork to evaluate the given expression
- When not using the sandbox thread (i.e. -fno-ghci-sandbox), we
don't support the debugger anyway, so the break flags are
irrelevant.
We do this by consistently calling `setBreakFlags` when starting,
resuming, or killing the evaluation.
See Note [Always setBreakFlags on running thread].
This slightly changes the behavior of evaluating a new expression in
the debugger (resuming a thread behaves the same as before). Namely,
`:step <expr>`, where <expr> forks a thread, will stop at the immediate
next breakpoint in the <expr> main thread, not on a breakpoint of any
forked thread.
NB: the forked thread may still stop at breakpoint, if it is enabled by
index specifically, and then :step-ing from that thread's breakpoint
will toggle per-thread stepping for that forked thread.
We will want to control stepping in "all threads, regardless of whether
we control them or if they were spawned by the debuggee" separately from
the commands which trigger evaluation of just an expression. Namely,
we'll likely want a "break at the next immediate breakpoint hit on ANY
thread" command that the user can execute before launching a debuggee
which is multi-threaded. This may even be the default for GHCi.
Towards #26064
Fixes #28080
- - - - -
19ff36f2 by Simon Jakobi at 2026-11-09T09:22:47-05:00
testsuite: Mark T8209 fragile for the ghci ways on FreeBSD and darwin
A shutdown race in the I/O manager intermittently fails T8209(ghci) on
x86_64-freebsd14-validate and aarch64-darwin-validate, recently killing
several Marge batches. Mark it fragile there until the race is fixed.
See #27948.
Assisted-by: Claude Opus 5.5
- - - - -
212c292f by Rajkumar Natarajan at 2026-11-11T13:54:08-05:00
document what ->>> stands for in heap profile
updates the profiling section of the user's guide to explain how types
are approximated when using -hy. Also adds haddocks to getTyDescription
with the same information.
Fixes #26754
- - - - -
c64fc319 by Jonathan at 2026-11-11T13:54:55-05:00
Fix AArch64 veneer target for relocations with an addend
Fixes #27807
The RTS linker would construct invalid relocation veneers on AArch64 if
the addend was non-zero, which typically caused SIGILL crashes. This
could be triggered by evaluating Template Haskell in a package with a
large number of dependencies using a static build of GHC.
- - - - -
cd4dce19 by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
testsuite: add a test for registerFd_ trusting the callback table (#27821)
registerFd001 shows a 'threadWaitRead' that never finishes after an fd is
closed with 'closeFd' rather than 'closeFdWith'. Darwin is the only platform
this reaches -- one-shot registrations are implemented but not used there
(#7651) -- so the test is expect_broken on Darwin only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5ab442ee by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
registerFd_: always tell the polling backend (#27821)
Where the backend has no one-shot registrations, 'registerFd_' now tells it
about every registration, rather than only when the events differ from the
ones the callback table records: the table alone cannot say whether the
backend still knows the fd. The 'modify' it returns is unchanged. See Note
[Do not trust the callback table].
This fixes registerFd001 and clears its expect_broken.
Changelog wording from Duncan Coutts in review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
ab8b5b06 by Vladislav Zavialov at 2026-11-11T13:56:27-05:00
Curried contexts in prefix GADT constructors (#27424)
Prefix GADT constructor declarations now accept multiple consecutive
contexts, equivalent to a single conjoined context:
data G a where
MkCurried :: C a => (D a, E a) => G a
MkConjoined :: (C a, D a, E a) => G a
This is a step towards GHC Proposal #402 "Stable GADT constructor syntax".
To represent multiple contexts, the `con_mb_cxt` field of `ConDeclGADT` has
been replaced by `con_cxts`, which stores a list instead of a Maybe:
- con_mb_cxt :: Maybe (LHsContext pass)
+ con_cxts :: [LHsContext pass]
The rest of this patch follows from this change.
Note that in ConDeclH98, the optional context is still stored as a Maybe.
To accommodate this difference, a few helper functions were generalised over
a Foldable container `t`:
hsConDeclTheta :: Foldable t => t (LHsContext ...) -> [LHsType ...]
pprLHsContext :: (Foldable t, ...) => t (LHsContext ...) -> SDoc
repContexts :: Foldable t => t (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))
tcHsContext :: Foldable t => t (LHsContext GhcRn) -> TcM [PredType]
In practice, the instantiations of `t` are either `Maybe` or `[]`.
Record-style GADT constructors continue to accept at most one context.
`splitLHsGadtTy` accounts for this by splitting off only the first context
if it detects record syntax, leaving the offending part of the type in the
body for the renamer to reject later on.
Test cases: T12087a T27424a T27424b T27424c T27424d GadtConSigs_th_dump1
- - - - -
d2f135ff by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: cache register usage in liveness annotations
regUsageOfInstr allocates fresh register lists on every call, and on the
linear allocator path it was called three times per instruction: in the
backward liveness pass, in the forward liveness pass and in the allocator
itself. Store the usage computed by the backward pass in the Liveness
annotation and reuse it in the other passes (and in the graph allocator's
spill passes). patchRegsLiveInstr recomputes it for the patched
instruction.
See Note [Cached register usage in liveness annotations].
Part of #28008.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
ff0a5d32 by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: describe register usage with a small DSL
This new register usage DSL (see Note [Register usage DSL] in
GHC.CmmToAsm.RegUsage) reduces allocation compared to the previous
list-based approach.
Fixes #28008.
Metric Decrease:
ManyAlternatives
T12707
T13035
T13379
T13960
T18698b
T19695
T21839c
T3064
T3294
T4801
T5321FD
T5321Fun
T783
T9198
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
51f38f3a by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock-library: fix the build of the spec and fixtures test suites
The documentation pipeline moved from String to Text (commit 202ed264141)
but the two test suites of haddock-library were left behind and no
longer compiled. They are not run by GHC's CI (see #16206), so this went
unnoticed.
The fixtures suite still has four pre-existing failures (list-blocks1,
table1, table4, table5) that are not addressed here.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
394d9d6d by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: parse backtick spans as monospaced text
A backtick span whose content is not a valid Haskell identifier, such as
`foo bar`, was rendered as plain text with literal backticks. It is now
parsed as monospaced text, like @foo bar@. A closed backtick span whose
whole content is one identifier keeps its meaning as a hyperlinked
identifier. A span such as `foldl' f z xs` is code: it is no longer read
as the identifier foldl between a backtick and a single quote. The
TeX-style form `foo' stays an identifier when no backtick closes the
span on the same line.
Code spans follow the CommonMark rules: a span opened by a run of N
backticks ends at the next run of exactly N backticks on the same line,
so ``x `plus` y`` is code "x `plus` y". One space is removed at each end
when both are present, and an unclosed opening run is plain text. The
content is literal: no markup is parsed and backslashes are kept, so
`\x -> x` renders as written.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Fixes #28090
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7ae41c37 by Sylvain Henry at 2026-11-11T13:58:14-05:00
Use 'T' instead of `T' in Haddock comments next to backtick spans
With backtick code spans, a TeX-style quote `T' followed by a backtick on
the same line opens a code span up to that backtick. Use the 'T' form in
the Haddock comments where this happens.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
ce96f0b6 by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: do not parse backtick spans inside @...@
Text between @...@ is already code, so backtick code spans are no longer
parsed there. Thus in
@x <- f -- of type `M Bool`@
the backticks stay as text. Inline markup inside @...@, such as /.../,
passes this context down.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
744b3036 by Sylvain Henry at 2026-11-11T13:58:15-05:00
haddock: keep the backticks of infix identifiers inside @...@
A backticked identifier inside @...@ was always rendered without its
backticks, so @f `elem` xs@ rendered as "f elem xs". Now an identifier
in an infix application or an operator section, such as @f `elem` xs@
or @(`elem` xs)@, is parsed in infix form, as if written ``elem``, and
renders with its backticks and with elem linked. Elsewhere, as in
@`foldlM` :: ...@, the backticks still only mark the link.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
0d8e1f8d by Sylvain Henry at 2026-11-11T13:59:05-05:00
PPC NCG: print non-standard NaN literals in target byte order
The PowerPC NCG printed a non-standard NaN literal byte by byte with
floatToBytes/doubleToBytes, which use the byte order of the host. This
is wrong when the host and the target have a different endianness (e.g.
from x86_64 to big-endian PowerPC). Print the bits with `.long`/`.quad`
instead, so that the assembler uses the target byte order.
Also make `ppr_item` print its argument: some clauses printed the
literal of `pprDataItem` instead.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
5a9db1ed by Sylvain Henry at 2026-11-11T13:59:05-05:00
Print all NaN literals as integer bits (#28101)
The x86 and PowerPC NCGs printed the quiet NaNs 0x7fc00000 and
0x7ff8000000000000 as `.float NaN`/`.double NaN`. GNU as and clang
encode these with all mantissa bits set, so constant-folded bit casts
of these values gave 0x7fffffff/0x7fffffffffffffff. The C backend
printed every NaN as `NAN`, losing its sign and payload.
Now the NCGs print all NaNs with `.long`/`.quad` and the C backend with
hs_bitcastword2float/hs_bitcastword642double.
See Note [Printing NaN literals].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b4ceb6a9 by mangoiv at 2026-11-11T13:59:47-05:00
ci: fix ghcup nightly script misbehaviour
- download all jobs instead of just the first 100
- stop using a canary job to detect whether it's a nightly or release
pipeline
- - - - -
aefa0c1b by Alan Zimmerman at 2026-11-11T14:00:28-05:00
EPA: Use AnnList in HsMultiIf
It introduces layout, capture it
- - - - -
d72505e4 by Simon Jakobi at 2026-11-12T15:26:14-05:00
testsuite: Fix T17088 flakiness and restore bug coverage
T17088 reads and prints a byte from an uninitialized array. Debug RTS
ways fill allocated memory with 0xaa, so the test can fail due to an
output mismatch unrelated to the pointer-tagging bug it covers.
Initialize the byte to zero to make the output deterministic.
The original bug requires the compacting collector and particular
compiler and RTS settings. Run the test only in the compacting_gc way
with -O1 and -A128k. Also disable STG lambda lifting because it removes
the closure shape needed to reproduce the pointer-tagging failure.
This makes the test reliable while ensuring it remains an effective
reproducer for #17088.
Closes #27534.
Assisted-by: gpt-5.6-sol via Codex CLI
- - - - -
5a7591b3 by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: Fix python type errors
These errors appear when using the VSCode python extension which uses
Pylance under the hood.
- - - - -
52f129f8 by David Eichmann at 2026-11-12T15:26:56-05:00
Add test modifier to test over all IO Managers
- - - - -
22e8b92a by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: include custom IO Manager in test name
- - - - -
82c34ccd by Simon Jakobi at 2026-11-12T15:27:40-05:00
Make T2464 actually test #ifdef'd pragmas
The test guarded a LANGUAGE EmptyDataDecls pragma behind #if, but
EmptyDataDecls is on by default since Haskell2010, so the module
compiled even when the guarded pragma was ignored. Guard MagicHash
instead, which is unlikely to be included in a future default language.
The test also checks that warnings from file-header pragmas are emitted
only once, even though the pragmas are parsed both before and after
CPP, using the -fffi deprecation warning as the canary. Use an
unrecognised warning flag instead, so the test no longer depends on a
deprecated flag that is about to be removed.
Context: #27939
Assisted-by: Claude Fable 5.1
- - - - -
419f2a12 by Simon Jakobi at 2026-11-12T15:27:40-05:00
Remove command-line flags deprecated in GHC 8.2 or earlier
Also remove the INCLUDE file-header pragma, which only expanded to
the now-removed -#include.
Closes #27939.
Assisted-by: Claude Fable 5.1
- - - - -
adc294d0 by Erik de Castro Lopo at 2026-11-12T15:28:21-05:00
TimerManager: publish only evaluated timeout queues (#9809)
The issue in #9809 was triggered by many threads registering timeouts
at the same time and those timeouts being stored as unevaluated thunks
in the shared list. When say 100,000 timeouts are registered at the
same time, the program can be slowed down considerably and the memory
usage grow unacceptably large.
The commit that caused the problem was 2d5eccdf1c, a 2013 change that
fixed #7653.
The fix is to add a modifyTimeouts function which applies an edit to a
copy of the list and fully evaluates the result before replacing the
shared list with a CAS operation.
Performance has improved for the threaded case and not regressed for
the single thread case:
Forked registrations of 100k timeouts (median of 5 runs):
-N4: 0.577 s, 428 MB -> 0.078 s, 39 MB
-N12: 1.227 s, 479 MB -> 0.127 s, 80 MB
Forked registrations of 1M timeouts on -N1 (median of 3 and 10 runs):
5.21 s (range 0.67-9.47 s), 1613 MB -> 0.67 s, 250 MB
Single-thread registrations are unchanged or slightly faster, and timer
latency during registration storms improves (p99 lateness of a 1 ms
threadDelay during 100k forked registrations on -N4: 302-394 ms ->
3.5-4.1 ms).
The registration code still runs in constant stack, so #7653 stays fixed;
T7653 and the concurrent, base and ghc-internal testsuites pass.
modifyTimeouts is OPAQUE so that the optimiser cannot expose the edit
function's inspection of the old queue next to the compare-and-swap and
replace the expected pointer with the evaluated queue, which would make the
compare-and-swap keep failing when the MutVar# holds a thunk or indirection.
Regression test T9809.hs included.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b294b82f by Moritz Angermann at 2026-11-12T15:28:21-05:00
testsuite: give pause_resume_via_safe_ffi_concurrent 60s on Darwin CI
The 10s System.Timeout watchdog was a false deadlock: five serialized
1s pauses plus rts_pause waiting on threadDelay/timer-manager traffic
overruns that budget on loaded Mac runners. Keep a watchdog so a real
hang still fails.
- - - - -
1543f834 by Simon Jakobi at 2026-11-12T15:29:03-05:00
testsuite/README: Don't append new tests at the end of all.T
Patches that each add a test at the end of the same all.T conflict
with each other. Tests added elsewhere in the file usually merge cleanly.
Context: #26285
Assisted-by: Claude Opus 5.5
- - - - -
9ad25cb2 by Sven Tennie at 2026-11-14T06:20:13-05:00
hadrian: Add Stage3 cross-compiled target bindist (#26924)
Add a `binary-dist-stage3` Hadrian target that packages target
executables (produced by the stage2 compiler) into a separate
'_build/bindist-stage3/' folder, distinct from the stage2 regular or
cross-compiler bindist in '_build/bindist/'.
This allows a single CI pipeline job to produce both a cross-compiler
bindist (e.g. x86_64 -> RISC-V) and a target-architecture bindist (e.g.
RISC-V -> RISC-V) that can be installed and run natively on the target.
To avoid issues with stale files or race-conditions on them, generate
the `configure` script per stage in `_build/<stage>/distrib`
directories.
- - - - -
ca91017d by Sven Tennie at 2026-11-14T06:20:13-05:00
ci: Build Stage3 and Stage2 bindists for cross targets in one job (#26924)
Building the stage3 target bindist already produces most of the stage2
cross-compiler bindist as a byproduct, so building them in separate jobs
duplicates the build efforts for no benefit. Instead of a separate
CROSS_STAGE=3 job, the stage3 job now also builds and publishes the
stage2 bindist.
The stage3 tarball is named and versioned as if it were built natively
on the target (target triple prefix, non-cross opsys), so its artifact
name stays what downstream consumers already expect and no changes are
needed on their side.
For now, this is only enabled for the RISC-V job. Others can easily
follow.
- - - - -
71b41e09 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: model cross targets as structured TargetPlatform triples (#26924)
Storing the cross target as a raw triple forced ad-hoc parsing at every
use, and broke the single responsibility rule. Modelling it as a
structured `TargetPlatform`` instead, avoids parsing and provides a
clear separation of concerns.
- - - - -
8067c2f9 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: extract the cross smoke tests into a separate smoke_test command (#26924)
This reduces if-nesting and complexity of the main `test_hadrian`
command. The decision how to test is now made by the caller. This is a
fair choice, because most test cases can run under emulation - they are
just very slow then.
The Stage3 smoke test also checks that the target compiler does not report
itself as cross-compiling and, when supported, runs a small GHCi expression.
- - - - -
7ece99a7 by fendor at 2026-11-14T06:20:57-05:00
Add `-dep-json` flag to `ghc -M`
Add an optional flag to `ghc -M` that allows to write the dependency
information in JSON Lines format.
The JSON Lines format enables us to stream the output of the dependency
generation to a consumer.
The output of `-dep-json` is streamed to a temporary file and then
copied to the final destination to avoid partial writes.
Each line contains one of two possible json objects:
1. A Home Unit Dependency
* Contains the name of the home module, its unit, where it is
located, whether a preprocessor is used, and all of its imports.
Importantly, the imports include `-XExplicitLevelImports`
information.
* If requested via `-include-pkg-deps`, includes imports of external
units, e.g. modules from `base`.
* If requested via `-include-cpp-deps`, files included via CPP.
2. External Unit Dependency
* Only if `-include-pkg-deps` is given
* Contains unit-id, its package name and package id.
---
This PR refactors the Makefile generation to use phases appropriately.
We introduce an intermediate data structure that is generated based on
the module graph nodes, and only then generate the Makefile rules.
This allows the dep-json and dep-makefile generation to use the same
dependency processing.
- - - - -
0f6e0146 by fendor at 2026-11-14T06:20:57-05:00
Add multiple home unit support to `ghc -M`
Allows to process the module graph of multiple home units at once using
the same syntax as `--make` and `--interactive`:
ghc -M -unit @unitA -unit @unitB
The semantics are identical to `--make` and `--interactive`.
Each home unit can declare individually to use `-include-cpp-deps` and
`-include-pkg-deps`.
However, there can only be one output file, and `-dep-json` and
`-dep-makefile` can only be provided at the top of the cli invocation.
We introduce a new GHC API `doMkDepend` that allows to use multiple home
units conveniently.
The output of `-dep-json` and `-dep-makefile` does not change, since we
were careful to choose a format that supports multiple home units from
the start.
Single home units are still accepted like before with no changes.
- - - - -
5598e6a0 by fendor at 2026-11-14T06:20:57-05:00
Deprecate `doMkDependHS` in favour of `doMkDepend`
- - - - -
39f2943e by David Eichmann at 2026-11-14T06:21:41-05:00
rts: Expose getRtsSymbols() and store redirect labels and external symbols tag
- - - - -
aa159605 by David Eichmann at 2026-11-14T06:21:41-05:00
hadrian: when running tests, properly set have_gdb and have_readelf
- - - - -
ff826da4 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: add have_ldd() test modifier
- - - - -
b9f0b7e2 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite driver: on windows, ensure PATH correctly contains mingw and ghc-pkg libraries
- - - - -
543c108e by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: driver now sets WAY_FLAGS variable for makefile tests
- - - - -
13408a2b by David Eichmann at 2026-11-14T06:21:41-05:00
Add golden test for rts/RtsSymbols.c
This test compares declared symbols against symbols observed
in the rts DSO (.so file).
- - - - -
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
cbe0a6bf by fendor at 2026-11-17T09:25:55-05:00
Add support for streaming `ghc -M` to stdout
Adds the flags `-dep-json-stdout` and `-dep-makefile-stdout` which
streams dependency information line-by-line to stdout.
Each dependency generation can be redirected to separate outputs.
Providing any extra `-dep-{json,makefile}[-stdout]` disables the default
generation of the `Makefile` file.
Allows consumers to start processing the dependency information as it
comes in and not waiting for the dependency generation to finish.
`DepStream` abstracts over the possible output handles, which is either
a file or the stdout handle.
Writing to a file requires temporary file paths, thus `DepStream` must
provide a way to perform clean up when dependency processing finished or
when an error is thrown for any reason.
We further decouple the rendering and writing of the result from the
dependency generation, localising side effects and making the code
slightly more readable.
The testsuite now also handles `ghc -M` writing to stdout.
We add a test for each combination of writing to stdout and file,
except for writing both makefile and json.
While it probably works, is really undefined behaviour.
Closes #27937
- - - - -
fbd49db2 by Sylvain Henry at 2026-11-17T09:27:09-05:00
Link the on-demand iserv without --gc-sections
GHC links an iserv program each time a session needs the external
interpreter. The link is static, against the ghci library and the boot
libraries. Like all executable links, it passed -Wl,--gc-sections to a
GNU linker. On libraries built with -split-sections (the release
bindists), the section garbage collection of ld.bfd is the largest part
of that link: with binutils 2.45, the link takes 3 times longer with
--gc-sections than without. The program is temporary and its size is
not important. Thus the iserv link does not use --gc-sections. Other
executable links do not change.
In CI, each ext-interp or ghci-ext test takes 12 to 18 times longer in
the x86_64-linux-fedora43-release test job (split sections) than in the
x86_64-linux-deb13-validate test job (no split sections) on the same
runner, while a normal-way test takes the same time in both. This link
is most of that difference.
See Note [No --gc-sections for the on-demand iserv] in
GHC.Runtime.Interpreter.C.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
09c965e2 by mangoiv at 2026-11-17T09:27:51-05:00
ci: make tests-primops run on marge CI
test primops dispatch was disabled on the *full-ci
group label to avoid dispatching for some of its configs
but wasn't reenabled for marge ci runs which it ought to
run
Fixes #27765
- - - - -
83038fbe by David Eichmann at 2026-11-17T09:28:32-05:00
test driver refactor: replace `.format(**locals())` with f-string
- - - - -
01a5b0ac by Sylvain Henry at 2026-11-22T16:35:34-05:00
NCG: List each destination of a jump table once
jumpDestsOfInstr listed a block once per jump table entry that named
it. The linear register allocator makes a fixup block per listed
destination, so such a block got several fixup blocks. The patch of
the jump sends every entry to the first one. The other fixup blocks
were dead code, and the CFG had an edge to each of them.
jumpDestsOfInstr now lists each destination once, in every backend.
joinToTargets asserts it in debug builds.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
e4498112 by Andreas Klebinger at 2026-11-22T16:35:34-05:00
x86 ncg: Track the current block in NatM to keep the CFG in sync
The x86 NCG uses a CFG for code layout. When instruction selection
makes new blocks (word2Float#, cmpxchg loops, 64-bit shifts on i386),
it must add them to the CFG. Some sites did not. The CFG went out of
sync, the layout was bad, and the register allocator panicked when it
added fixup blocks (#27694, #27915).
NatM now keeps the current block in its state. Combinators update the
CFG and the current block together. See Note [Updating the CFG during
CodeGen] in GHC.CmmToAsm.Monad.
Other changes:
* -dasm-lint checks that the jumps in the code and the edges in the
CFG agree in both directions. This found a second desync: the CFG
did not follow the jumps that allocMoreStack retargets. The new
addPreentryBlock fixes it.
* The code must be emitted in generation order, because the CFG
records new blocks in that order. A store now generates the code of
its value before the code of its address, in the order it emits
them. Atomic operations take their address from the new
getNonClobberedAmode, so the code of their other operands cannot
clobber it.
Fixes #27694, #27915
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
f59fb957 by Sylvain Henry at 2026-11-22T16:35:34-05:00
x86 ncg: Maintain the CFG on i386
The i386 NCG now keeps its CFG in sync with the code (see the previous
commit), so backendMaintainsCfg is now True for i386. i386 gets the
CFG based code layout, dead code elimination and the -dasm-lint check,
like x86-64.
The compiler allocates more on i386: the CFG now goes through the
register allocator, branch shortcutting and optimizeCFG, which i386
skipped before. x86-64 already does this work.
Metric Increase:
CoOpt_Read
ManyAlternatives
T10421
T12425
T12707
T13056
T13253
T13253-spj
T13960
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T19695
T20049
T21839c
T24471
T26425
T26989
T5642
T6048
T783
T9233
T9630
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
2091b89a by fendor at 2026-11-22T16:36:17-05:00
`ghc -M`: Add support for link nodes to json output
`LinkNode`s are part of the module graph and indicate that a certain
linking artefact is to be produced from other module graph nodes.
We expose `LinkNode`s in the output of `ghc -M -dep-json`, allowing
consumers to see when a linking artefact is to be produced.
Only the JSON output format of `ghc -M` supports `LinkNode` as it is
unclear how the Makefile output should be retrofitted to express the
dependencies, and whether it would require a feature guard.
Closes #28007
- - - - -
cfd4fb67 by Ryan Scott at 2026-11-22T16:36:59-05:00
GHC.HsToCore.Quote: Quote \cases with the correct type
Previously, `\cases` expressions inside of Template Haskell quotes would
incorrectly use the `Match` type instead of `Clause` for the element type. We
now use `nonEmptyCoreList` when quoting `\cases`, which infers the correct type
automatically. This works because `\cases` has an invariant that the list of
clauses is always non-empty.
Fixes #27826.
- - - - -
06e71ddf by Simon Peyton Jones at 2026-11-22T16:37:40-05:00
Better desugaring for bang patterns
Ticket #27862 showed that we were desugaring bang patterns in a
silly way, which led to bad code. This small fix makes it much
better.
I ended up refactoring `decomposeFirstPat` to be of type
(LPat -> LPat) instead of (Pat -> Pat)
which made it much easier to keep the locations correct.
On the way I also fixed #28137, a missing warning.
See Note [Tidying patterns] which has new (TP1) and (TP2)
and Note [Grouping equations] especially (GE1)
- - - - -
cd6c2a96 by Simon Jakobi at 2026-11-22T16:38:23-05:00
Cmm: drop eliminated blocks from the graph in CBE
Previously, common block elimination only made the eliminated blocks
unreachable. They stayed in the graph until stack layout discarded
them.
Removing these blocks right away reduces the potential for confusion
(e.g. #27368). It does not appear to make any significant difference
to compiler allocations.
Assisted-by: Claude Opus 5.5
- - - - -
c0764c69 by Hannes Siebenhandl at 2026-11-22T16:39:04-05:00
Use Set operations over Foldable operations
Use `O(log n)` operations over `O(n)` for all call-sites of `hsc_all_home_unit_ids`.
- - - - -
242f8daf by Alan Zimmerman at 2026-11-22T16:39:46-05:00
EPA: Use AnnList in DecBrl
Via updating the TTG extension point payload
- - - - -
1e568190 by David Eichmann at 2026-11-22T16:40:28-05:00
Fix race condition in IOManager test
- - - - -
64f821c6 by Simon Peyton Jones at 2026-11-22T16:41:09-05:00
Fix a zonking bug
As #28135 showed, we were failing to zonk some type-variable
binders before doing scoped-sort dependency analysis, resulting
in chaos.
The fix is easy.
- - - - -
ed5124b3 by mangoiv at 2026-11-22T16:41:50-05:00
ci: nightly push can run on any arch
- - - - -
3935e459 by Simon Jakobi at 2026-11-23T04:01:36+01:00
Correct comments about unreachable Cmm blocks
* ContFlowOpt claimed that maybe_concat drops every block that has no
predecessors left. But a block that loses its predecessors to
shortcutting stays in the graph.
* The linear register allocator claimed that the Cmm pipeline keeps
unreachable blocks away from it. But the NCG's own Cmm optimisations
can make more blocks unreachable after the Cmm pipeline has run. It
is sccBlocks that discards unreachable code before register
allocation (#7574).
Also:
* Remove a commented-out trace in the linear allocator that predates
#7574.
* Say in Note [Unreachable blocks] that the passes between control-flow
optimisation and stack layout can encounter unreachable blocks.
Capitalise the title of the Note.
Context: #27368
Assisted-by: Claude Fable 5.2
- - - - -
473 changed files:
- .gitignore
- .gitlab-ci.yml
- .gitlab/ci.sh
- .gitlab/common.sh
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/jobs.yaml
- .gitlab/rel_eng/mk-ghcup-metadata/mk_ghcup_metadata.py
- + changelog.d/21969
- + changelog.d/26169.md
- + changelog.d/27694
- + changelog.d/27821
- + changelog.d/27892
- + changelog.d/28002-leb128
- + changelog.d/28080
- + changelog.d/28081
- + changelog.d/28101
- + changelog.d/T26754
- + changelog.d/T27137
- + changelog.d/T27862
- + changelog.d/T28123
- + changelog.d/T28135
- + changelog.d/T9809-timer-manager-contention
- changelog.d/allow-gadt-prefix-con-parens
- + changelog.d/bignum-quotrem-no-alloc
- + changelog.d/fix-aarch64-veneer-target-16686
- + changelog.d/fix-copyarray-nonmoving-barrier-27376
- + changelog.d/fix-heap-census-pinned-blocks.md
- + changelog.d/gadt-curried-contexts-27424
- + changelog.d/ghc-api-exec-break-resume
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-deprecate-doMkDependHS
- + changelog.d/make-depends-json
- + changelog.d/make-depends-link-nodes
- + changelog.d/make-depends-multiple-home-units
- + changelog.d/make-depends-streaming-output
- + changelog.d/ncg-reg-usage.md
- + changelog.d/remove-long-deprecated-flags.md
- + changelog.d/split-sections-dynamic
- + changelog.d/stage3-cross-bindists
- compiler/GHC/Cmm.hs
- compiler/GHC/Cmm/CommonBlockElim.hs
- compiler/GHC/Cmm/ContFlowOpt.hs
- compiler/GHC/Cmm/Pipeline.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Ppr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- + compiler/GHC/CmmToAsm/RegUsage.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/Core.hs
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/CoreToStg.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Driver/Session/Units.hs
- compiler/GHC/Hs/Binds.hs
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/Dump.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/Type.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore/Arrows.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Expr.hs-boot
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- compiler/GHC/HsToCore/Pmc/Desugar.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Errors/Ppr.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Platform/Ways.hs
- compiler/GHC/Rename/Bind.hs
- compiler/GHC/Rename/Expr.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Utils.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- compiler/GHC/Stg/Make.hs
- compiler/GHC/StgToCmm/Closure.hs
- compiler/GHC/StgToCmm/Prim.hs
- compiler/GHC/Tc/Deriv/Functor.hs
- compiler/GHC/Tc/Deriv/Generate.hs
- compiler/GHC/Tc/Gen/Arrow.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Match.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/PatSyn.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Literal/Floating.hs
- compiler/GHC/Types/Tickish.hs
- compiler/GHC/Utils/Json.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Decls/Foreign.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/Type.hs
- compiler/ghc.cabal.in
- + distrib/configure.ac
- docs/users_guide/codegens.rst
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/exts/control.rst
- docs/users_guide/exts/ffi.rst
- docs/users_guide/exts/gadt_syntax.rst
- docs/users_guide/exts/pragmas.rst
- docs/users_guide/exts/qualified_strings.rst
- docs/users_guide/ghc.rst
- + docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/phases.rst
- docs/users_guide/profiling.rst
- docs/users_guide/separate_compilation.rst
- − docs/users_guide/what_glasgow_exts_does.rst
- ghc/GHCi/UI.hs
- ghc/GHCi/UI/Monad.hs
- ghc/Main.hs
- hadrian/doc/cross-compile.md
- hadrian/src/Base.hs
- hadrian/src/BindistConfig.hs
- hadrian/src/Builder.hs
- hadrian/src/Context.hs
- hadrian/src/Flavour.hs
- hadrian/src/Hadrian/Haskell/Hash.hs
- hadrian/src/Hadrian/Package.hs
- hadrian/src/Oracles/Flag.hs
- hadrian/src/Oracles/Setting.hs
- hadrian/src/Oracles/TestSettings.hs
- hadrian/src/Packages.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Rules/Program.hs
- hadrian/src/Rules/Test.hs
- hadrian/src/Settings/Builders/DeriveConstants.hs
- hadrian/src/Settings/Builders/RunTest.hs
- hadrian/src/Settings/Packages.hs
- libraries/base/src/Data/Foldable.hs
- libraries/base/tests/.gitignore
- + libraries/base/tests/T9809.hs
- libraries/base/tests/all.T
- libraries/ghc-boot/GHC/Serialized.hs
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingDisabled.hsc
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingEnabled.hsc
- libraries/ghc-heap/tests/parse_tso_flags.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Backend/Native.hs
- libraries/ghc-internal/src/GHC/Internal/Conc/IO.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Manager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Thread.hs
- libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs
- libraries/ghc-internal/src/GHC/Internal/Heap/Closures.hs
- libraries/ghci/GHCi/Debugger.hs
- libraries/ghci/GHCi/Run.hs
- rts/Exception.cmm
- rts/Interpreter.c
- rts/Interpreter.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/PrimOps.cmm
- rts/ProfHeap.c
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.c
- rts/Stats.c
- rts/Stats.h
- rts/include/Cmm.h
- rts/include/Rts.h
- rts/include/rts/Constants.h
- + rts/include/rts/RtsSymbols.h
- rts/include/stg/MiscClosures.h
- rts/linker/PEi386.c
- rts/linker/elf_reloc_aarch64.c
- rts/rts.cabal
- rts/sm/GC.c
- rts/sm/GCThread.h
- rts/sm/NonMovingMark.c
- testsuite/README.md
- testsuite/config/ghc
- testsuite/driver/junit.py
- testsuite/driver/my_typing.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/driver/testutil.py
- testsuite/mk/test.mk
- testsuite/tests/ado/T22483.stderr
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.hs
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout-ws-32
- testsuite/tests/annotations/should_run/T16841.stdout
- testsuite/tests/annotations/should_run/all.T
- + testsuite/tests/cmm/should_run/T28101.hs
- + testsuite/tests/cmm/should_run/T28101.stdout
- + testsuite/tests/cmm/should_run/T28101_cmm.cmm
- testsuite/tests/cmm/should_run/all.T
- + testsuite/tests/codeGen/should_compile/T27694.hs
- + testsuite/tests/codeGen/should_compile/T27694c.hs
- + testsuite/tests/codeGen/should_compile/T27694d.hs
- testsuite/tests/codeGen/should_compile/all.T
- testsuite/tests/codeGen/should_gen_asm/all.T
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.hs
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.hs
- + testsuite/tests/codeGen/should_run/T27694b.hs
- + testsuite/tests/codeGen/should_run/T27694b.stdout
- + testsuite/tests/codeGen/should_run/T27915.hs
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-32
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-64
- testsuite/tests/codeGen/should_run/all.T
- testsuite/tests/concurrent/should_run/T21969.hs
- + testsuite/tests/concurrent/should_run/T21969a.hs
- + testsuite/tests/concurrent/should_run/T21969a.stdout
- + testsuite/tests/concurrent/should_run/T21969b.hs
- + testsuite/tests/concurrent/should_run/T21969b.stdout
- + testsuite/tests/concurrent/should_run/T21969c.hs
- + testsuite/tests/concurrent/should_run/T21969c.stdout
- + testsuite/tests/concurrent/should_run/T21969d.hs
- + testsuite/tests/concurrent/should_run/T21969d.stdout
- + testsuite/tests/concurrent/should_run/T21969e.hs
- + testsuite/tests/concurrent/should_run/T21969e.stdout
- + testsuite/tests/concurrent/should_run/T21969f.hs
- + testsuite/tests/concurrent/should_run/T21969f.stdout
- testsuite/tests/concurrent/should_run/all.T
- + testsuite/tests/concurrent/should_run/registerFd001.hs
- + testsuite/tests/concurrent/should_run/registerFd001.stdout
- + testsuite/tests/deSugar/should_compile/T27862.hs
- + testsuite/tests/deSugar/should_compile/T27862.stderr
- + testsuite/tests/deSugar/should_compile/T27862a.hs
- + testsuite/tests/deSugar/should_compile/T27862a.stderr
- + testsuite/tests/deSugar/should_compile/T27862b.hs
- + testsuite/tests/deSugar/should_compile/T27862b.stderr
- + testsuite/tests/deSugar/should_compile/T27862c.hs
- + testsuite/tests/deSugar/should_compile/T27862c.stderr
- + testsuite/tests/deSugar/should_compile/T27862d.hs
- + testsuite/tests/deSugar/should_compile/T27862d.stderr
- + testsuite/tests/deSugar/should_compile/T28137.hs
- + testsuite/tests/deSugar/should_compile/T28137.stderr
- testsuite/tests/deSugar/should_compile/all.T
- testsuite/tests/deSugar/should_run/dsrun008.stderr
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/T2464.hs
- testsuite/tests/driver/T2464.stderr
- + testsuite/tests/driver/mkdepend/Makefile
- + testsuite/tests/driver/mkdepend/README.md
- + testsuite/tests/driver/mkdepend/T24384/A.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/D.hs
- + testsuite/tests/driver/mkdepend/T24384/E.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/DepInternal.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/dep-internal.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep-public/DepPublic.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-public/dep-public.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep/Dep.hs
- + testsuite/tests/driver/mkdepend/T24384/dep/dep.pkg
- + testsuite/tests/driver/mkdepend/T24384/foo.h
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/preproc.sh
- + testsuite/tests/driver/mkdepend/T24384a.stdout
- + testsuite/tests/driver/mkdepend/T24384b.stdout
- + testsuite/tests/driver/mkdepend/T24384c.stdout
- + testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/format_json.sh
- + testsuite/tests/driver/mkdepend/format_makefile.sh
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs-boot
- + testsuite/tests/driver/mkdepend/mhu01/a/A/TH.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Normal.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Splice.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/c/C.hs
- + testsuite/tests/driver/mkdepend/mhu01/unitA
- + testsuite/tests/driver/mkdepend/mhu01/unitB
- + testsuite/tests/driver/mkdepend/mhu01/unitC
- + testsuite/tests/driver/mkdepend/mhu02/A.hs
- + testsuite/tests/driver/mkdepend/mhu02/B.hs
- + testsuite/tests/driver/mkdepend/mhu02/pp.sh
- + testsuite/tests/driver/mkdepend/mhu02/unitA
- + testsuite/tests/driver/mkdepend/mhu02/unitB
- + testsuite/tests/driver/mkdepend/mhu03/pkg/A.hs
- + testsuite/tests/driver/mkdepend/mhu03/pkg/pp.sh
- + testsuite/tests/driver/mkdepend/mhu03/unitA
- + testsuite/tests/driver/mkdepend/mhu04/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu04/app/Utils.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu04/unitApp
- + testsuite/tests/driver/mkdepend/mhu04/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu05/test/Spec.hs
- + testsuite/tests/driver/mkdepend/mhu05/unitApp
- + testsuite/tests/driver/mkdepend/mhu05/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/unitTest
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend01/A.hs
- + testsuite/tests/driver/mkdepend/mkdepend02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend02/Main.hs
- + testsuite/tests/driver/mkdepend/mkdepend_bkp_01/bkp01.bkp
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu03.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-makefile
- testsuite/tests/ffi/should_run/T2594.hs
- testsuite/tests/ffi/should_run/ffi015.hs
- testsuite/tests/ffi/should_run/fptr01.hs
- testsuite/tests/ffi/should_run/fptrfail01.hs
- − testsuite/tests/gadt/T12087.stderr
- + testsuite/tests/gadt/T12087a.hs
- testsuite/tests/gadt/T12087.hs → testsuite/tests/gadt/T12087b.hs
- + testsuite/tests/gadt/T12087b.stderr
- + testsuite/tests/gadt/T27424a.hs
- + testsuite/tests/gadt/T27424b.hs
- + testsuite/tests/gadt/T27424b.stderr
- testsuite/tests/gadt/all.T
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghci.debugger/scripts/all.T
- + testsuite/tests/ghci.debugger/scripts/break037.hs
- + testsuite/tests/ghci.debugger/scripts/break037.script
- + testsuite/tests/ghci.debugger/scripts/break037.stdout
- testsuite/tests/ghci/linking/T25155_iserv_main.c
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/SkolemOccursLoop.hs
- testsuite/tests/linters/all.T
- testsuite/tests/llvm/should_compile/all.T
- + testsuite/tests/llvm/should_compile/split-sections-darwin.hs
- testsuite/tests/module/mod185.stderr
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/DumpTypecheckedAst.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/perf/compiler/hard_hole_fits.stderr
- testsuite/tests/perf/compiler/large-project/all.T
- + testsuite/tests/perf/compiler/large-project/large-project-mhu.sh
- + testsuite/tests/perf/should_run/T27231.hs
- + testsuite/tests/perf/should_run/T27231.stdout
- testsuite/tests/perf/should_run/T7257.hs
- testsuite/tests/perf/should_run/T7257.stdout
- testsuite/tests/perf/should_run/all.T
- testsuite/tests/pmcheck/should_compile/T24234.stderr
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- testsuite/tests/primops/should_run/all.T
- testsuite/tests/printer/Makefile
- testsuite/tests/printer/T18791.stderr
- + testsuite/tests/printer/T27424c.hs
- testsuite/tests/printer/Test20297.hs
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/printer/all.T
- testsuite/tests/profiling/should_run/T7275.stdout
- testsuite/tests/rts/IOManager.hsc
- testsuite/tests/rts/Makefile
- testsuite/tests/rts/T17088.hs
- + testsuite/tests/rts/T26169.hs
- + testsuite/tests/rts/T27376.hs
- + testsuite/tests/rts/T27376.stdout
- testsuite/tests/rts/all.T
- + testsuite/tests/rts/census_pinned.hs
- + testsuite/tests/rts/census_pinned.stdout-ws-32
- + testsuite/tests/rts/census_pinned.stdout-ws-64
- + testsuite/tests/rts/census_pinned.stdout-ws-64-mingw32
- testsuite/tests/rts/linker/Makefile
- + testsuite/tests/rts/linker/T27807.s
- + testsuite/tests/rts/linker/T27807.stdout
- testsuite/tests/rts/linker/all.T
- testsuite/tests/rts/pause-resume/all.T
- testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs
- + testsuite/tests/rts/symbols/Main.hs
- + testsuite/tests/rts/symbols/Makefile
- + testsuite/tests/rts/symbols/all.T
- + testsuite/tests/rts/symbols/dumpDeclaredSymbols.c
- + testsuite/tests/rts/symbols/rts-check-symbols.sh
- + testsuite/tests/rts/symbols/rts-check-symbols.stdout
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- testsuite/tests/simplCore/should_compile/all.T
- testsuite/tests/th/GadtConSigs_th_dump1.hs
- testsuite/tests/th/GadtConSigs_th_dump1.stderr
- + testsuite/tests/th/T27424d.hs
- + testsuite/tests/th/T27424d.stderr
- + testsuite/tests/th/T27826.hs
- testsuite/tests/th/all.T
- + testsuite/tests/typecheck/should_compile/T28135.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_fail/tcfail203a.stderr
- + testsuite/tests/unsatisfiable/T28081.hs
- testsuite/tests/unsatisfiable/all.T
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
- utils/haddock/CHANGES.md
- utils/haddock/doc/markup.rst
- utils/haddock/haddock-api/haddock-api.cabal
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Parser.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/GhcUtils.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-library/CHANGES.md
- utils/haddock/haddock-library/fixtures/Fixtures.hs
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.parsed
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.parsed
- utils/haddock/haddock-library/haddock-library.cabal
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser.hs
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser/Identifier.hs
- utils/haddock/haddock-library/test/Documentation/Haddock/ParserSpec.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/950f5f9a75f14deb7b4c45d5a9767f…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/950f5f9a75f14deb7b4c45d5a9767f…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/sjakobi/ci-cabal-update-retry] 2 commits: ci: Retry cabal update on failure
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/ci-cabal-update-retry at Glasgow Haskell Compiler / GHC
Commits:
c2de416d by Simon Jakobi at 2026-11-23T03:04:47+01:00
ci: Retry cabal update on failure
Make up to three attempts, waiting 60 and then 120 seconds in between.
From 2026-11-06 to 2026-11-19 a failed update killed 15 jobs in 9
Marge batches. The outages looked short: in the three cases I checked,
other jobs of the same pipeline updated successfully within about two
minutes.
Assisted-by: Claude Fable 5.2
- - - - -
e1bef58f by Simon Jakobi at 2026-11-23T03:07:56+01:00
ci: Use the cached Hackage index when cabal update fails
If `cabal update` still fails after the retries, carry on with the
package index from the cabal cache. That index is usually recent enough,
because the index-state is pinned. If it is not, cabal will fail with
Cabal-7159.
Assisted-by: Claude Fable 5.2
- - - - -
1 changed file:
- .gitlab/ci.sh
Changes:
=====================================
.gitlab/ci.sh
=====================================
@@ -236,12 +236,25 @@ function set_toolchain_paths() {
fi
}
-function cabal_update() {
+function cabal_update_once() {
# In principle -w shouldn't be necessary here but with
# cabal-install 3.8.1.0 it is, due to cabal#8447.
run "$CABAL" update -w "$GHC" "hackage.haskell.org,${HACKAGE_INDEX_STATE}"
}
+function cabal_update() {
+ local delay
+ for delay in 60 120; do
+ cabal_update_once && return
+ info "Retrying cabal update in $delay seconds"
+ sleep "$delay"
+ done
+ cabal_update_once && return
+
+ [ -f "$CABAL_DIR/packages/hackage.haskell.org/01-index.tar" ] || return 1
+ warn "cabal update failed, continuing with the existing package index"
+}
+
# Extract GHC toolchain
function setup() {
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/43c92eb051ba1f62e291e1167449aa…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/43c92eb051ba1f62e291e1167449aa…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc] Pushed new branch wip/sjakobi/ci-cabal-update-retry
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed new branch wip/sjakobi/ci-cabal-update-retry at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/sjakobi/ci-cabal-update-retry
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc] Pushed new branch wip/sjakobi/ci-auto-retry-infra-failures
by Simon Jakobi (@sjakobi) 23 Nov '26
by Simon Jakobi (@sjakobi) 23 Nov '26
23 Nov '26
Simon Jakobi pushed new branch wip/sjakobi/ci-auto-retry-infra-failures at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/sjakobi/ci-auto-retry-infra-f…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/case-bndr-unf] 4 commits: Lambda and case binders have vanilla IdInfo (#27965)
by Simon Peyton Jones (@simonpj) 23 Nov '26
by Simon Peyton Jones (@simonpj) 23 Nov '26
23 Nov '26
Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC
Commits:
2c6e2ec1 by Simon Peyton Jones at 2026-11-23T00:18:46+00:00
Lambda and case binders have vanilla IdInfo (#27965)
Lambda binders, case binders, and case-alternative binders should never
have RULES, a (non-default) inline pragma, or a stable unfolding.
See new Note [Core binder IdInfo invariants] in GHC.Core, which
lays out the invariants.
This patch
* Makes Core Lint check the invariant, using the new predicate
GHC.Types.Id.lamBndrInfoOK.
* Fixes the desugarer, which violated it. For a strict binding
let !x = rhs in body
we generate
let x = rhs in case x of x { DEFAULT -> body }
re-using x (shadowed) as the case binder; see Note [Desugar Strict binds].
But the case binder inherited x's IdInfo, including, say, a NOINLINE
pragma (e.g. `res1` in GHC.Internal.Control.Monad.ST.Lazy.Imp). Now
GHC.HsToCore.Utils.seqVar gives the case binder vanilla IdInfo.
This was not just a matter of taste. For example
h fm s = let {-# NOINLINE res1 #-}
!res1 = fm s
!(f, s') = res1
in (f+1, s')
The NOINLINE case binder becomes a NOINLINE alias `let res3 = res2`,
which is never inlined, and survives (as a silly join point) into the
final code.
* Fixes the Simplifier, which could violate it when duplicating a
StrictBind continuation, which makes a join point
let x = <> in b ==> join j x = b in j <>
If x has such IdInfo, we now use a fresh binder for the join point
let x = <> in b ==> join j x' = let x = x' in b in j <>
See (DSB1) in Note [Duplicating StrictBind].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7307c7b4 by Simon Peyton Jones at 2026-11-23T00:18:46+00:00
Add varIsHNF, and use it in move_transit_vars
`varIsHNF v` is the same as `exprIsHNF (Var v)`, but avoids building the
Var only to take it apart. The (Var v) case of exprIsHNFlike now uses
the shared varIsHNFlike, so the two cannot drift apart.
In GHC.Core.Opt.WorkWrap.Utils.move_transit_vars we had the guard
isUnliftedType var_ty || exprIsHNF (Var var)
but exprIsHNF is already True of variables of (definitely) unlifted type,
so the isUnliftedType test was redundant. Now it is just (varIsHNF var).
Also make `exprIsHNFlike` treat an application with no value arguments, such as
`f @Int`, exactly like the bare variable `f`, by going through varIsHNFlike.
Otherwise no change in behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fcbbd6d1 by Simon Peyton Jones at 2026-11-23T00:18:46+00:00
Use SimplClo for the argument of ApplyToVal
This patch renames SimplSR to SimplClo (a "closure"), and uses it not
only as the range of the Simplifier's substitution, but also as the
argument of an ApplyToVal continuation. ApplyToVal used to have three
fields
sc_env :: StaticEnv
sc_arg :: CoreExpr
sc_cast :: MOutCoercion
but now has just
sc_dup :: DupFlag
sc_arg :: SimplClo
An un-simplified argument is (ContEx env arg mco), and an already-simplified
one is (DoneEx arg _). See Note [The argument of ApplyToVal] in
GHC.Core.Opt.Simplify.Utils.
The main payoff is that, since the substitution maps an Id to a SimplClo,
beta-reduction can substitute the argument for the lambda binder without
further ado. Accordingly, preInlineUnconditionally is split into
* preInlineLetUnconditionally, for let-bindings
* preInlineBetaUnconditionally, for beta-redexes, which takes a SimplClo
The latter omits some checks that cannot fire for lambda binders.
Other notes
* The new (ContEx env arg mco) form makes it easy to push a cast into an
argument (mkCloCastMCo), whether or not it has been simplified.
See Note [The MOutCoercion field of ContEx].
* `preInlineUnconditionally` gets split into two variants, one for
let-bindings and one for beta-reduction (which takes a `SimplClo`).
There is a little bit of duplication here, but not much.
* Fixes #27962. The simplifier was previously dropping a cast when dealing
with runRW#. The new `SimplClo` makes that bug much harder to allow.
* Fixes #27963. contOutArgs, which supplies the arguments for Plan (BEFORE)
rule matching, ignored the sc_cast field of ApplyToVal. So in
(f |> co) n ==> f (n |> co1) -- co1 in sc_cast
a rule for `f` saw `f n` rather than `f (n |> co1)`, and failed to match
(the rule matcher checks the types of template variables). If f's
unfolding is active, f may then be inlined, and the rule is lost for
good. Now contOutArgs uses simplCloExpr, which includes the pending cast.
Almost no change in behaviour, except for the #27963 bug-fix.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
3c32b7a5 by Simon Peyton Jones at 2026-11-23T00:18:46+00:00
Add splitThunkCpr
This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form
of "thunk splitting" for strict bindings that have CPR information.
See Note [Thunk splitting] in WorkWrap.hs for the details.
It catches a previously-unrecognised optimisation opportunity
(see #28258) but it only helps in fairly obscure cases, so
I don't expect a big impact in practice.
As usually I did lots of refactoring along the way.
LLM disclosure: lots of interaction with Claude, but I wrote all the
code and comments.
- - - - -
28 changed files:
- + changelog.d/T27962
- + changelog.d/T27963
- compiler/GHC/Core.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Opt/CprAnal.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/WorkWrap.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Core/Ppr.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/CoreToStg/Prep.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Id.hs
- compiler/GHC/Utils/Monad.hs
- testsuite/tests/simplCore/should_compile/T15445.stderr
- + testsuite/tests/simplCore/should_compile/T27962.hs
- + testsuite/tests/simplCore/should_compile/T27963.hs
- + testsuite/tests/simplCore/should_compile/T27963.stderr
- + testsuite/tests/simplCore/should_compile/T27965.hs
- + testsuite/tests/simplCore/should_compile/T27965a.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
changelog.d/T27962
=====================================
@@ -0,0 +1,7 @@
+section: compiler
+issues: #27962
+mrs: !16869
+synopsis:
+ Fix a Lint error when using `runRW#` and `coerce` together
+description:
+ Just an internal compiler bug, of long standing.
=====================================
changelog.d/T27963
=====================================
@@ -0,0 +1,7 @@
+section: compiler
+issues: #27963
+mrs: !16869
+synopsis:
+ Fix a rather obscure interaction of `coerce` and RULES
+description:
+ A `coerce` could prevent a RULE firing.
=====================================
compiler/GHC/Core.hs
=====================================
@@ -1494,6 +1494,157 @@ same way as above, otherwise the analysis would not be conservative wrt. the
lenient semantics (which includes the strict one). It is also much harder to
explain and maintain, as it turned out.
+Note [Core binder IdInfo invariants]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+We allow the following IdInfo on different sorts of Core binders.
+See the fields in GHC.Types.Id.Info.IdInfo:
+
+We classify binders into
+ * let-binders let x=rhs in body
+ * lambda binders (\x. e)
+ * case binders case e of x { ... }
+ * case-alternative binders case e of _ { K x y -> ... }
+
+ Let Lambda Case/case-alt
+ ---------------------------------------------
+ Occurrence Yes Yes Yes
+
+ InlinePrag Yes No No
+ Strictness (DmdSig) Yes No No
+ CPR info (CprSig) Yes No No
+ CAF Yes No No
+ Arity Yes No No
+ Call-arity Yes No No
+ Rules (RuleInfo) Yes No No
+ Unfolding Yes No(CBI1) evaldUnfolding only (CBI2)
+ Demand info Yes Yes Yes
+ One-shot No Yes No
+ ------------------------------------------------
+
+The predicate `GHC.Types.Id.lamBndrInfoOK` checks the Lambda and Case columns
+of this table (except one-shot info), and Core Lint applies it to every
+non-let binder (`lintIdBndr`).
+
+Generally, lambda binders have only IdInfo that describes their /use/
+(e.g. occ-info, demand info) not their /definition/. See esp (CBI1).
+
+Case and case-alternative binders are similar because again they lack a definition,
+and because they can /become/ a lambda binder when `mkDupableAlt` abstracts over them.
+
+Places that must take care to maintain these invariants (#27965):
+
+* Places that turn a let into a case, do so by calling `GHC.Core.Utils.mkCaseFromLet`,
+ which in turn calls `GHC.Types.Id.mkCaseBndrFromLetBndr`, or by calling the latter
+ directly:
+
+ - The desugarer, when desugaring a strict binding let !x = rhs in body,
+ generates case x of x { DEFAULT -> body }; the case binder must not inherit
+ x's IdInfo. See `GHC.HsToCore.Utils.seqVar`.
+
+ - `GHC.Core.Utils.bindNonRec` (used by `mkCoreLet`, and hence by the
+ Simplifier's `wrapFloats`), which turns let x = rhs in body into
+ case rhs of x { DEFAULT -> body } when `rhs` is unlifted and not
+ ok-for-speculation. Here `x` may well have a let-unfolding,
+ e.g. one made by `makeTrivial`.
+
+ - `GHC.Core.Opt.SpecConstr.mkSeqs`, which builds
+ case arg of arg' { DEFAULT -> rhs }
+ where `arg` may be an imported Id with an unfolding.
+
+ - `GHC.CoreToStg.Prep.wrapBinds` turns a let-binding into a case-binding.
+
+* The Simplifier, when it uses a StrictBind continuation for a strict
+ let-binding let x = rhs in body. When duplicating `StrictBind`,
+ `mkDupableContWithDmds` may turn `x` into the lambda binder of a join
+ point, so it uses `mkLamBndrFromLetBndr` to do so.
+ See (SB3) in Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration.
+
+
+(CBI1) Based on #17530 and #21496 we never attach unfoldings of any kind to lambda
+ binders, not even `evaldUnfolding`.
+
+ It's just too easy for the call site to change and invalidate the unfolding.
+ E.g. the caller of the lambda drops a seq (e.g. because the lambda is strict
+ in its binder) which in turn makes the OtherCon[] unfolding a lie. So
+ unfoldings on lambda binders can never really be trusted when on lambda
+ binders if there is the chance of the call site to change. So it's easiest to
+ just never attach any to lambda binders to begin with, as well as stripping
+ them off if we e.g. float out an expression while abstracting over some
+ arguments.
+
+(CBI2) See Note [Evaluated-ness on case binders]
+
+(CBI3) Note that /occurrences/ may have IdInfo that is not present on the binder.
+ Notably, consider case e of r { Just x -> ..r...; Nothing -> ...r... }
+ The occurrence of `r` in the (Just x) branch will have an unfolding `Just x`,
+ and similarly in the `Nothing` branch. But the /binder/ of `r` has only
+ `evaldUnfolding` See Note [Evaluated-ness on case binders]
+
+Note [Evaluated-ness on case binders]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The binding site of an Id in a case expression (case-binder or case alternative) may
+carry an `OtherCon []` (aka `evaldUnfolding`). meaning "this variable is certainly
+evaluated". Specifically:
+
+* Case binders are always evaluated. `GHC.Core.Opt.Simplify.Iteration.simplAlts` and
+ CorePrep add `evaldUnfolding` to every case binder.
+
+* Case-alternative binders for strict constructor fields
+ data T = MkT !Int Int
+ case x of MkT y z -> ...
+ `y` gets an evaldUnfolding.
+
+ This is done by `GHC.Core.Utils.dataConRepFSInstPat` (used by the interface-file loader,
+ among others), `GHC.Core.SimpleOpt`, the Simplifier (`adjustFieldsIdInfo`), and
+ worker/wrapper (for the argument and CPR result binders it makes;
+ see Note [Record evaluated-ness in worker/wrapper] in GHC.Core.Opt.WorkWrap.Utils).
+
+Why is this information on the /binder/? Within the Simplifier it is not
+needed: in each case alternative the Simplifier adds a more precise unfolding
+for the case binder (and evaluated-ness for strict-field binders) to its
+in-scope set, and refreshes every occurrence from that. But many other passes
+rebuild variable occurrences /from the binder/: substitution-based passes
+(SimpleOpt, Specialise, SpecConstr, CSE), SetLevels/FloatOut, the binder swap in
+the occurrence analyser, CoreTidy, and CorePrep. After such a pass, an
+occurrence knows that the variable is evaluated only if the binder does.
+
+That knowledge is used, mainly via `exprIsHNF`/`varIsHNF` (not by
+`exprOkForSpeculation`; see Note [exprOkForSpeculation and evaluated variables]
+in GHC.Core.Utils), by:
+
+* CorePrep: deciding whether a let-binding is a value (allocate directly) or
+ a thunk, e.g. `let x = Box y` where `y` is a strict field.
+ See Note [Pin evaluatedness on floats] in GHC.CoreToStg.Prep. CorePrep runs
+ just after CoreTidy, which propagates binder IdInfo to occurrences.
+
+* SetLevels/FloatOut: floating single-alternative cases out of loops, when the
+ scrutinee is evaluated; see Note [Floating single-alternative cases] in
+ GHC.Core.Opt.SetLevels. Also the call-by-value marks given to abstracted
+ variables (`GHC.Types.Id.transferPolyIdInfo`).
+
+* Worker/wrapper: `move_transit_vars` avoids an unboxed 1-tuple for a single
+ evaluated transit variable (test T18109); and the CPR result binders of the
+ wrapper remain evaluated (tests T13077a, #13027). The latter matters because
+ unboxed-tuple alternatives take a fast path in the Simplifier's
+ `adjustFieldsIdInfo`, and so get evaluated-ness only from the binder.
+
+* SimpleOpt: eliminating a case on an evaluated variable, and `mkFieldSeqFloats`.
+
+* Minor heuristic uses: FloatIn (the late FloatIn runs after FloatOut and CSE
+ with no Simplifier in between) and occurrences created by CSE or the binder
+ swap, until the next Simplifier run.
+
+Core Lint does /not/ depend on this information. Nor does anything in STG or
+tag inference.
+
+Removing the information from the binders would require these passes to track
+evaluated-ness in an environment instead (as SpecConstr already does with its
+ValueEnv), which they currently don't. So we allow an OtherCon unfolding (and
+only that) on case binders and case-alternative binders:
+see the table in Note [Core binder IdInfo invariants]
+
+
+
************************************************************************
* *
In/Out type synonyms
@@ -1843,16 +1994,6 @@ floatBinders (FloatTick {}) = []
The @Unfolding@ type is declared here to avoid numerous loops
-Note [Never put `OtherCon` unfoldings on lambda binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Based on #21496 we never attach unfoldings of any kind to lambda binders.
-It's just too easy for the call site to change and invalidate the unfolding.
-E.g. the caller of the lambda drops a seq (e.g. because the lambda is strict in it's binder)
-which in turn makes the OtherCon[] unfolding a lie.
-So unfoldings on lambda binders can never really be trusted when on lambda binders if there
-is the chance of the call site to change. So it's easiest to just never attach any
-to lambda binders to begin with, as well as stripping them off if we e.g. float out
-and expression while abstracting over some arguments.
-}
-- | Records the /unfolding/ of an identifier, which is approximately the form the
=====================================
compiler/GHC/Core/Lint.hs
=====================================
@@ -1858,6 +1858,15 @@ lintIdBndr top_lvl bind_site id thing_inside
hang (text "Lambda binder" <+> quotes (ppr id) <+> text "has an unfolding")
2 (ppr unf)
+ -- Check that lambda, case, and case-alternative binders have
+ -- only the IdInfo permitted by the table in
+ -- Note [Core binder IdInfo invariants] in GHC.Core
+ ; checkL (is_let_bind || lamBndrInfoOK id) $
+ hang (text "Non-let binder" <+> quotes (ppr id)
+ <+> text "has IdInfo that only a let-binder may have")
+ 2 (vcat [ text "Binding site:" <+> text (show_site bind_site)
+ , text "IdInfo:" <+> ppr (idInfo id) ])
+
; addLoc (IdTy id) (lintValueType id_ty)
; addInScopeId id thing_inside }
@@ -1869,6 +1878,12 @@ lintIdBndr top_lvl bind_site id thing_inside
LetBind -> True
_ -> False
+ show_site :: BindingSite -> String
+ show_site LambdaBind = "lambda"
+ show_site CaseBind = "case binder"
+ show_site CasePatBind = "case alternative"
+ show_site LetBind = "let"
+
{-
%************************************************************************
%* *
=====================================
compiler/GHC/Core/Opt/CprAnal.hs
=====================================
@@ -343,7 +343,7 @@ cprTransform env id args
-- Any local binding, except for data structure bindings
-- See Note [Efficient Top sigs in SigEnv]
| Just sig <- lookupSigEnv env id
- = applyCprTy (getCprSig sig) (length args)
+ = applyCprTy (cprSigType sig) (length args)
-- See Note [CPR for data structures]
| Just rhs <- cprDataStructureUnfolding_maybe id
= fst $ cprAnal env rhs
@@ -362,7 +362,7 @@ cprTransform env id args
= cprTransformDataConWork env con args
-- Imported function
| otherwise
- = applyCprTy (getCprSig (idCprSig id)) (length args)
+ = applyCprTy (cprSigType (idCprSig id)) (length args)
-- | Precise, hand-written CPR transformers for select Ids
cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType
@@ -870,27 +870,42 @@ Does f have the CPR property? Well, no.
However, if the strictness analyser has figured out (in a previous
iteration) that it's strict, then we DON'T need to forget the CPR info.
Instead we can retain the CPR info and do the thunk-splitting transform
-(see WorkWrap.splitThunk).
+(see Note [Thunk splitting] esp (B) CPR-led thunk splitting).
This made a big difference to PrelBase.modInt, which had something like
modInt = \ x -> let r = ... -> I# v in
...body strict in r...
-r's RHS isn't a value yet; but modInt returns r in various branches, so
-if r doesn't have the CPR property then neither does modInt
+r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so
+if `r` doesn't have the CPR property then neither does `modInt`
+
Another case I found in practice (in Complex.magnitude), looks like this:
- let k = if ... then I# a else I# b
- in ... body strict in k ....
+ let k* = if ... then I# a else I# b
+ in ... body strict in k ....
(For this example, it doesn't matter whether k is returned as part of
the overall result; but it does matter that k's RHS has the CPR property.)
+
Left to itself, the simplifier will make a join point thus:
- let $j k = ...body strict in k...
- if ... then $j (I# a) else $j (I# b)
+ let $j k = ...body strict in k...
+ if ... then $j (I# a) else $j (I# b)
+
With thunk-splitting, we get instead
- let $j x = let k = I#x in ...body strict in k...
- in if ... then $j a else $j b
+ let k* = case (if ... then I# a else I# b) of I# z -> I# z
+ in ... body strict in k ....
+Now the simplifier should pull out the `case` to give
+ case (if ... then I# a else I# b) of I# z ->
+ let k = I# z in ... body strict in k ...
+Now case-of-if will give
+ let $j z = let k = I# z in ...body strict in k... in
+ if ... then $j a else $j b
This is much better; there's a good chance the I# won't get allocated.
+TL'DR: During CPR analysis we want to give `k` the CPR property in `body`.
+
+What if the type involved has more than one constructor? E.g.
+ let k* = if ... then Just a else Just b
+ in ... body strict in k ....
+That is good too: see (TS5) in Note [Thunk splitting]
-But what about botCpr? Consider
+Finally, what about botCpr? Consider
lvl = error "boom"
fac -1 = lvl
fac 0 = 1
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -28,7 +28,7 @@ module GHC.Core.Opt.Simplify.Env (
SimplEnvIS, checkSimplEnvIS, pprBadSimplEnvIS,
-- * Substitution results
- SimplSR(..), substId, lookupRecBndr,
+ SimplClo(..), simplCloExpr, substId, lookupRecBndr,
-- * Simplifying 'Id' binders
simplNonRecBndr, simplNonRecJoinBndr, simplRecBndrs, simplRecJoinBndrs,
@@ -61,7 +61,7 @@ import GHC.Core.Opt.Simplify.Monad
import GHC.Core.Rules.Config ( RuleOpts(..) )
import GHC.Core
import GHC.Core.Utils
-import GHC.Core.Subst( substExprSC )
+import GHC.Core.Subst( substExpr )
import GHC.Core.Unfold
import GHC.Core.TyCo.Subst (emptyIdSubstEnv, mkSubst)
import GHC.Core.Multiplicity( Scaled(..), mkMultMul )
@@ -470,18 +470,26 @@ pprSimplEnv env
ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
| otherwise = ppr v
-type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
+type SimplIdSubst = IdEnv SimplClo -- IdId |--> OutExpr
-- See Note [Extending the IdSubstEnv] in GHC.Core.Subst
--- | A substitution result.
-data SimplSR
+-- | A "closure" used in the Simplifier. It is used
+-- * as the range of the substitution, 'SimplIdSubst'
+-- * as the argument in an 'ApplyToVal' continuation
+-- Roughly: either an (InExpr, StaticEnv) pair for an
+-- as-yet-unsimplified expression
+-- or an OutExpr, for an already-simplified one
+-- It's a bit like thunk: we may "evaluate" the SimplClo in a ApplyToVal
+-- and thereby transform it from `ContEx` to `DoneEx`
+-- This happens in the `ApplyToVal` case of `mkDupableContWithDmds`
+-- See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils
+data SimplClo
= DoneEx OutExpr JoinPointHood
-- If x :-> DoneEx e ja is in the SimplIdSubst
-- then replace occurrences of x by e
-- and ja = Just a <=> x is a join-point of arity a
-- See Note [Join arity in SimplIdSubst]
-
| DoneId OutId
-- If x :-> DoneId v is in the SimplIdSubst
-- then replace occurrences of x by v
@@ -490,11 +498,11 @@ data SimplSR
| ContEx SimplEnv
InExpr
- MOutCoercion -- See Note [The sc_cast field of ApplyToVal]
+ MOutCoercion -- See Note [The MOutCoercion field of ContEx]
-- If x :-> ContEx static_env e mco is in the SimplISubst
-- then replace occurrences of x by (subst static_env e) |> mco
-instance Outputable SimplSR where
+instance Outputable SimplClo where
ppr (DoneId v) = text "DoneId" <+> ppr v
ppr (DoneEx e mj) = text "DoneEx" <> pp_mj <+> ppr e
where
@@ -637,7 +645,7 @@ reSimplifying :: SimplEnv -> Bool
reSimplifying (SimplEnv { seInlineDepth = n }) = n>0
---------------------
-extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
+extendIdSubst :: SimplEnv -> Id -> SimplClo -> SimplEnv
extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
= assertPpr (isId var && not (isCoVar var)) (ppr var) $
env { seIdSubst = extendVarEnv subst var res }
@@ -1032,7 +1040,7 @@ So we want to look up the inner X.g_34 in the substitution, where we'll
find that it has been substituted by b. (Or conceivably cloned.)
-}
-substId :: SimplEnv -> InId -> SimplSR
+substId :: SimplEnv -> InId -> SimplClo
-- Returns DoneEx only on a non-Var expression
substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
= case lookupVarEnv ids v of -- Note [Global Ids in the substitution]
@@ -1364,15 +1372,18 @@ getTCvSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv
getFullSubst :: InScopeSet -> SimplEnv -> Subst
getFullSubst in_scope (SimplEnv { seIdSubst = id_env, seTvSubst = tv_env, seCvSubst = cv_env })
- = mkSubst in_scope (mapVarEnv to_expr id_env) tv_env cv_env
+ = mkSubst in_scope (mapVarEnv (simplCloExpr in_scope) id_env) tv_env cv_env
+
+simplCloExpr :: InScopeSet -> SimplClo -> OutExpr
+-- Turn a SimplClo into an OutExpr, by applying the substitution
+-- (if any) and the pending cast (if any)
+simplCloExpr _ (DoneEx e _) = e
+simplCloExpr _ (DoneId v) = Var v
+simplCloExpr in_scope (ContEx env e mco) = mkCastMCo e' mco
where
- to_expr :: SimplSR -> CoreExpr
- -- A tiresome impedence-matcher
- to_expr (DoneEx e _) = e
- to_expr (DoneId v) = Var v
- to_expr (ContEx env e mco) = mkCastMCo e' mco
- where
- e' = GHC.Core.Subst.substExprSC (getFullSubst in_scope env) e
+ e' = GHC.Core.Subst.substExpr (getFullSubst in_scope env) e
+ -- NB: we use substExpr, not substExprSC: we want to get the benefit of
+ -- knowing what is evaluated etc, via the in-scope set
substTy :: HasDebugCallStack => SimplEnv -> Type -> Type
substTy env ty = Type.substTy (getTCvSubst env) ty
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -285,8 +285,8 @@ simplRecOrTopPair :: SimplEnv
-> SimplM (SimplFloats, SimplEnv)
simplRecOrTopPair env bind_cxt old_bndr new_bndr rhs
- | Just env' <- preInlineUnconditionally env (bindContextLevel bind_cxt)
- old_bndr (UnSimplified env) rhs MRefl
+ | Just env' <- preInlineLetUnconditionally env (bindContextLevel bind_cxt)
+ old_bndr rhs env
= {-#SCC "simplRecOrTopPair-pre-inline-uncond" #-}
simplTrace "SimplBindr:inline-uncond1" (ppr old_bndr) $
do { tick (PreInlineUnconditionally old_bndr)
@@ -1226,17 +1226,8 @@ simplExprF1 env (Tick t expr) cont = {-#SCC "simplTick" #-} simplTick env t exp
simplExprF1 env (Coercion co) cont = {-#SCC "simplCoercionF" #-} simplCoercionF env co cont
simplExprF1 env (Cast body co) cont
- = do { co1 <- {-#SCC "simplCast-simplCoercion" #-}
- simplCoercion env co
-
- ; let cont1 = {-#SCC "simplCast-addCoerce" #-}
- if isReflCo co1
- then cont -- See Note [Optimising reflexivity]
- else pushCast env co1 cont
- -- True <=> co1 is optimised
-
- ; {-#SCC "simplCast-simplExprF" #-}
- simplExprF env body cont1 }
+ = do { co1 <- simplCoercion env co
+ ; simplExprF env body (pushCast env co1 cont) }
simplExprF1 env (App fun arg) cont
= {-#SCC "simplExprF1-App" #-} case arg of
@@ -1264,9 +1255,9 @@ simplExprF1 env (App fun arg) cont
-- observed the quadratic behavior, so this extra entanglement
-- seems not worthwhile.
simplExprF env fun $
- ApplyToVal { sc_arg = arg, sc_env = UnSimplified env
+ ApplyToVal { sc_arg = ContEx env arg MRefl, sc_dup = NoDup
, sc_hole_ty = substTy env (exprType fun)
- , sc_cast = MRefl, sc_cont = cont }
+ , sc_cont = cont }
simplExprF1 env expr@(Lam {}) cont
= {-#SCC "simplExprF1-Lam" #-}
@@ -1301,7 +1292,7 @@ simplExprF1 env (Let (NonRec bndr rhs) body) cont
do { ty' <- simplType env ty
; simplExprF (extendTvSubst env bndr ty') body cont }
- | Just env' <- preInlineUnconditionally env NotTopLevel bndr (UnSimplified env) rhs MRefl
+ | Just env' <- preInlineLetUnconditionally env NotTopLevel bndr rhs env
-- Because of the let-can-float invariant, it's ok to
-- inline freely, or to drop the binding if it is dead.
= do { simplTrace "SimplBindr:inline-uncond2" (ppr bndr) $
@@ -1637,9 +1628,8 @@ rebuild_go env expr cont
ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
-> rebuild_go env (App expr (Type ty)) cont
- ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_cont = cont, sc_hole_ty = fun_ty }
- -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = fun_ty }
+ -> do { arg' <- simplArg env Nothing fun_ty arg
; rebuild_go env (App expr arg') cont }
completeBindX :: SimplEnv
@@ -1653,6 +1643,7 @@ completeBindX env from_what bndr rhs body cont
| FromBeta arg_levity <- from_what
, needsCaseBindingL arg_levity rhs -- Enforcing the let-can-float-invariant
= do { (env1, bndr1) <- simplNonRecBndr env bndr -- Lambda binders don't have rules
+ -- See Note [Core binder IdInfo invariants] in GHC.Core
; (floats, expr') <- simplNonRecBody env1 from_what body cont
-- Do not float floats past the Case binder below
; let expr'' = wrapFloats floats expr'
@@ -1686,69 +1677,12 @@ completeBindX env from_what bndr rhs body cont
; let all_floats = rhs_floats `addFloats` bind_float `addFloats` body_floats
; return ( all_floats, body' ) }
-{-
-************************************************************************
+
+{- *********************************************************************
* *
-\subsection{Lambdas}
+ Arguments
* *
-************************************************************************
--}
-
-{- Note [Optimising reflexivity]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-It's important (for compiler performance) to get rid of reflexivity as soon
-as it appears. See #11735, #14737, and #15019.
-
-In particular, we want to behave well on
-
- * e |> co1 |> co2
- where the two happen to cancel out entirely. That is quite common;
- e.g. a newtype wrapping and unwrapping cancel.
-
-
- * (f |> co) @t1 @t2 ... @tn x1 .. xm
- Here we will use pushCoTyArg and pushCoValArg successively, which
- build up SelCo stacks. Silly to do that if co is reflexive.
-
-However, we don't want to call isReflexiveCo too much, because it uses
-type equality which is expensive on big types (#14737 comment:7).
-
-A good compromise (determined experimentally) seems to be to call
-isReflexiveCo
- * when composing casts, and
- * at the end
-
-In investigating this I saw missed opportunities for on-the-fly
-coercion shrinkage. See #15090.
-
-Note [Avoid re-simplifying coercions]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-In some benchmarks (with deeply nested cases) we successively push
-casts onto the SimplCont. We don't want to call the coercion optimiser
-on each successive composition -- that's at least quadratic. So:
-
-* The CastIt constructor in SimplCont has a `sc_opt :: Bool` flag to
- record whether the coercion optimiser has been applied to the coercion.
-
-* In `simplCast`, when we see (Cast e co), we simplify `co` to get
- an OutCoercion, and built a CastIt with sc_opt=True.
-
- Actually not quite: if we are simplifying the result of inlining an
- unfolding (seInlineDepth > 0), then instead of /optimising/ it again,
- just /substitute/ which is cheaper. See `simplCoercion`.
-
-* In `pushCast` if we combine this new coercion with an existing one,
- we build a CastIt for (co1 ; co2) with sc_opt=False.
-
-* When unpacking a CastIt, in `rebuild`, we optimise the (presumably
- composed) coercion if sc_opt=False; this is done by `optOutCoercion`.
-
-* When duplicating a continuation in `mkDupableContWithDmds`, before
- duplicating a CastIt, optimise the coercion. Otherwise we'll end up
- optimising it separately in the duplicate copies.
-
-* See also Note [The sc_cast field of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
--}
+********************************************************************* -}
simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
-> Maybe ArgInfo -- ^ Just <=> This arg `ai` occurs in an app
@@ -1756,15 +1690,12 @@ simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
-- how `f` uses `ai`, affecting the Stop
-- continuation passed to 'simplExprC'
-> OutType -- ^ Type of the function applied to this arg
- -> StaticEnv -> CoreExpr -- ^ Expression with its static envt
- -> MOutCoercion -- Wrap this around the result
+ -> SimplClo -- ^ The argument
-> SimplM OutExpr
-simplArg _ _ _ (Simplified {}) arg mco
- = -- See Note [Avoid repeated simplification]
- case mco of
- MRefl -> return arg -- Vastly common case
- MCo co -> return (mkCast arg co)
-simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
+-- See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils
+simplArg _ _ _ (DoneEx arg _) = return arg -- See Note [Avoid repeated simplification]
+simplArg _ _ _ (DoneId v) = return (Var v)
+simplArg env mb_arg_info fun_ty (ContEx arg_se arg mco)
= do { let arg_env' = arg_se `setInScopeFromE` env
arg_ty = funArgTy fun_ty
stop = case mb_arg_info of
@@ -1773,13 +1704,12 @@ simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
cont = addCastMCo mco stop
; simplExprC arg_env' arg cont }
-{-
-************************************************************************
+
+{- *********************************************************************
* *
-\subsection{Lambdas}
+ Lambdas
* *
-************************************************************************
--}
+********************************************************************* -}
simplNonRecBody :: SimplEnv -> FromWhat
-> InExpr -> SimplCont
@@ -1806,13 +1736,9 @@ simpl_lam env bndr body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
-- Value beta-reduction
-- This works for /coercion/ lambdas too
-simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
- , sc_cast = arg_mco, sc_cont = cont
+simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_cont = cont
, sc_hole_ty = fun_ty})
- | Just env' <- preInlineUnconditionally env NotTopLevel bndr arg_se arg arg_mco
- , not (needsCaseBindingL arg_levity arg)
- -- Ok to test arg::InExpr in needsCaseBinding because
- -- exprOkForSpeculation is stable under simplification
+ | Just env' <- preInlineBetaUnconditionally env arg_levity bndr arg
= simplTrace "SimplBindr:inline-uncond3"
(ppr bndr <+> text ":=" <+> ppr arg) $
do { tick (BetaReduction bndr)
@@ -1823,14 +1749,14 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
= do { tick (BetaReduction bndr)
; let from_what = FromBeta arg_levity
- ; case (arg_se, arg_mco) of
- (UnSimplified arg_env, MRefl)
+ ; case arg of
+ ContEx arg_env arg_expr MRefl
-- Optimisation: when there is no wrapping coercion use simplNonRecE
-- so that the clever floating out of let-bindings can take place
-- in this round of the Simplifier
- -> simplNonRecE env from_what bndr (arg, arg_env) body cont
+ -> simplNonRecE env from_what bndr (arg_expr, arg_env) body cont
- _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ _ -> do { arg' <- simplArg env Nothing fun_ty arg
; completeBindX env from_what bndr arg' body cont }
}
where
@@ -1869,7 +1795,7 @@ simplLamBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
-- could have a stable unfolding;
-- see Historical Note [Case binders and join points]
-- But now it is much simpler! We now only remove unfoldings.
--- See Note [Never put `OtherCon` unfoldings on lambda binders]
+-- See (CBI1) in Note [Core binder IdInfo invariants]
simplLamBndr env bndr = simplBinder env (zapIdUnfolding bndr)
simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
@@ -1902,8 +1828,8 @@ simplNonRecE :: HasDebugCallStack
-- Otherwise it may or may not satisfy it.
simplNonRecE env from_what bndr (rhs, rhs_se) body cont
- | assert (isId bndr && not (isJoinId bndr) ) $
- is_strict_bind
+ | assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True
+ , useStrictBind env from_what bndr rhs
= -- Evaluate RHS strictly
simplExprF (rhs_se `setInScopeFromE` env) rhs
(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
@@ -1917,17 +1843,6 @@ simplNonRecE env from_what bndr (rhs, rhs_se) body cont
; (floats2, expr') <- simplNonRecBody env3 from_what body cont
; return (floats1 `addFloats` floats2, expr') }
- where
- is_strict_bind = case from_what of
- FromBeta Unlifted -> True
- -- If we are coming from a beta-reduction (FromBeta) we must
- -- establish the let-can-float invariant, so go via StrictBind
- -- If not, the invariant holds already, and it's optional.
-
- -- (FromBeta Lifted) or FromLet: look at the demand info
- _ -> seCaseCase env && isStrUsedDmd (idDemandInfo bndr)
-
-
------------------
simplRecE :: SimplEnv
-> [(InId, InExpr)]
@@ -1948,6 +1863,48 @@ simplRecE env pairs body cont
; (floats2, expr') <- simplExprF env2 body cont
; return (floats1 `addFloats` floats2, expr') }
+
+useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool
+-- Can we use a StrictBind continuation for this let-binding?
+-- See (SB3) in Note [StrictBind]
+useStrictBind env from_what bndr rhs
+ -- If we are coming from a beta-reduction (FromBeta) we must
+ -- establish the let-can-float invariant, so we must go via StrictBind
+ -- If not, the invariant holds already, and it's optional.
+ | FromBeta Unlifted <- from_what
+ = True
+
+ -- Not if the demand is non-strict
+ | not (isStrUsedDmd dmd_info)
+ = False
+
+ -- Not if the RHS is ok-for-spec; no benefit
+ | exprOkForSpeculation rhs
+ = False
+
+ -- Not if case-of-case is off
+ -- See (SB1) in Note [StrictBind]
+ | not (seCaseCase env)
+ = False
+
+ | FromBeta Lifted <- from_what
+ = True
+
+ -- Not for things with RULES or INLINE or NOINLINE
+ -- or with a strictnes or CPR signature -- all things we might lose
+ -- See (SB3) in Note [StrictBind]
+ | isStableUnfolding (unfoldingInfo info)
+ || not (isEmptyRuleInfo (ruleInfo info))
+ || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
+ = False
+
+ | otherwise
+ = True
+
+ where
+ info = idInfo bndr
+ dmd_info = demandInfo info
+
{- Note [Dark corner with representation polymorphism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In `simplNonRecE`, the call to `needsCaseBinding` or to `isStrictId` will fail
@@ -2262,11 +2219,14 @@ simplOutId env fun cont
| fun `hasKey` runRWKey
, ApplyToTy { sc_cont = cont1 } <- cont
, ApplyToTy { sc_cont = cont2, sc_arg_ty = hole_ty } <- cont1
- , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_cast = arg_mco
- , sc_env = arg_se, sc_hole_ty = fun_ty } <- cont2
+ , ApplyToVal { sc_cont = cont3, sc_arg = arg_clo, sc_hole_ty = fun_ty } <- cont2
-- Do this even if (contIsStop cont), or if seCaseCase is off.
-- See Note [No eta-expansion in runRW#]
- = do { let (_saf,arg_env) = mkAltEnv env arg_se
+ = do { let (arg_env, arg, arg_mco)
+ = case arg_clo of
+ ContEx se e mco -> (se `setInScopeFromE` env, e, mco)
+ DoneEx e _ -> (env, e, MRefl)
+ DoneId v -> (env, Var v, MRefl)
overall_res_ty = contResultType cont3
-- hole_ty is the type of the current runRW# application
@@ -2281,23 +2241,32 @@ simplOutId env fun cont
-- * If we don't do this we get a beta-redex every time, so the
-- simplifier keeps doing more iterations.
-- * Even more important: see Note [No eta-expansion in runRW#]
+ --
+ -- But only if there is no pending cast on the argument (#27962);
+ -- if there is, the general case below deals with it properly
; arg' <- case arg of
- Lam s body -> do { (env', s') <- simplBinder arg_env s
- ; body' <- simplExprC env' body inner_cont
- ; return (Lam s' body') }
- -- Important: do not try to eta-expand this lambda
- -- See Note [No eta-expansion in runRW#]
+ Lam s body
+ | MRefl <- arg_mco
+ -> do { (env', s') <- simplBinder arg_env s
+ ; body' <- simplExprC env' body inner_cont
+ ; return (Lam s' body') }
+ -- Important: do not try to eta-expand this lambda
+ -- See Note [No eta-expansion in runRW#]
_ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
; let (m,_,_) = splitFunTy fun_ty
env' = arg_env `addNewInScopeIds` [s']
hole_ty = mkVisFunTy m realWorldStatePrimTy new_runrw_res_ty
cont' = pushCastMCo env' arg_mco $
- ApplyToVal { sc_arg = Var s', sc_cast = MRefl
- , sc_env = Simplified OkDup
+ ApplyToVal { sc_arg = DoneId s'
+ , sc_dup = dup
, sc_cont = inner_cont
, sc_hole_ty = hole_ty }
-- cont' applies to s', then K
+ -- The argument (Var s') is small, but inner_cont may not be
+ -- dupable; see (AV2) in Note [The argument of ApplyToVal]
+ dup | contIsDupable inner_cont = OkDup
+ | otherwise = NoDup
; body' <- simplExprC env' arg cont'
; return (Lam s' body') }
@@ -2364,13 +2333,12 @@ rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_c
---------- Simplify value arguments --------------------
rebuildCall env fun_info
- (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_hole_ty = fun_ty, sc_cont = cont })
- | UnSimplified arg_env <- arg_se
+ (ApplyToVal { sc_arg = arg, sc_hole_ty = fun_ty, sc_cont = cont })
+ | ContEx arg_env arg_expr arg_mco <- arg
, isStrictArgInfo fun_info -- Strict arguments
, seCaseCase env -- But only when case-of-case is on.
-- See Note [Case-of-case and full laziness]
- = simplExprF (arg_env `setInScopeFromE` env) arg $
+ = simplExprF (arg_env `setInScopeFromE` env) arg_expr $
addCastMCo arg_mco $
StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
, sc_dup = NoDup
@@ -2382,7 +2350,7 @@ rebuildCall env fun_info
-- There is no benefit (unlike in a let-binding), and we'd
-- have to be very careful about bogus strictness through
-- floating a demanded let.
- = do { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
+ = do { arg' <- simplArg env (Just fun_info) fun_ty arg
; rebuildCall env (addValArgTo fun_info arg' fun_ty) cont }
---------- No further useful info, revert to generic rebuild ------------
@@ -2530,11 +2498,11 @@ Then
* We simplify BIG before trying the rule; but the rule does not fire
(forcing this simplification is why we have the RULE in this example)
* We inline f = \x. g x, in `simpl_lam`
- * So if `simpl_lam` did preInlineUnconditionally we get (g BIG)
+ * So if `simpl_lam` did preInlineBetaUnconditionally we get (g BIG)
* Now if g has a RULE we'll simplify BIG again, and this whole thing can
iterate.
* However, if `f` did not have a RULE, so that BIG has /not/ already been
- simplified, we /want/ to do preInlineUnconditionally in simpl_lam.
+ simplified, we /want/ to do preInlineBetaUnconditionally in simpl_lam.
So we go to some effort to avoid repeatedly simplifying the same thing.
Suppose we are in the Plan (AFTER) case of rule application, for a rule
@@ -2543,8 +2511,9 @@ and a call
f (e1,e2)
Then:
-* The (sc_env :: StaticEnv) field of ApplyToVal records if the argument
- has been evaluated. See Note [StaticEnv] in GHC.Core.Opt.Simplify.Utils.
+* The (sc_arg :: SimplClo) field of ApplyToVal records if the argument
+ has been simplified: it is a DoneEx if so, and a ContEx if not.
+ See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
* The rule fires returning
RuleMatch { rm_rhs = (\x y. ...x..), rm_args = [ e1, e2 ] }
@@ -2557,17 +2526,17 @@ Then:
is the reason that `RuleMatch` separates the two.
* `fireRuleAFTER` uses `pushOutArgs` to push [ e1, e2 ] back onto the
- continuation with sc_env=Simplified NoDup.
+ continuation as (DoneEx e1) and (DoneEx e2).
* Beta-reduction fires (in `simpl_lam`) for the \x.
* Suppose `x` occurs many times. Then we want to behave like `let x=e1 in ..`,
- but we use `simplArg`, which in turn uses that `sc_env` flag to avoid
+ but we use `simplArg`, which in turn uses the DoneEx to avoid
re-simplifying `e1`.
* Suppose `x` occurs just once or not at all; then the call to
- `preInlineUnconditionally` in `simpl_lam` will fire, and extend the
- substitution with
+ `preInlineBetaUnconditionally` in `simpl_lam` will fire, and extend the
+ substitution with the very same SimplClo
x :-> DoneEx e1
* At the /occurrence/ of `x`, the function `simplInId` calls `simplOutExpr`
@@ -2774,8 +2743,7 @@ trySeqRules in_env scrut rhs cont
, ValArg { as_arg = no_cast_scrut
, as_dmd = seqDmd
, as_hole_ty = res3_ty } ]
- rule_cont = ApplyToVal { sc_env = UnSimplified in_env, sc_arg = rhs
- , sc_cast = MRefl
+ rule_cont = ApplyToVal { sc_arg = ContEx in_env rhs MRefl, sc_dup = NoDup
, sc_cont = cont, sc_hole_ty = res4_ty }
out_args = [Type rhs_rep, Type scrut_ty, Type rhs_ty, no_cast_scrut]
@@ -3420,6 +3388,7 @@ simplAlts (saf,env0) scrut case_bndr alts cont'
; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
env2 = modifyInScope env1 case_bndr2
-- See Note [Case binder evaluated-ness]
+ -- and Note [Evaluated-ness on case binders] in GHC.Core
fam_envs = seFamEnvs env0
; (alt_env', scrut', case_bndr') <- improveSeq fam_envs (saf,env2) scrut
@@ -3879,8 +3848,8 @@ knownCon env scrut dc dc_args case_bndr alt_bndrs rhs cont
return ( emptyFloats env
, extendIdSubst env case_bndr (DoneEx scrut NotJoinPoint))
- | Just env' <- preInlineUnconditionally env NotTopLevel case_bndr
- (UnSimplified env) con_app MRefl
+ | Just env' <- preInlineLetUnconditionally env NotTopLevel case_bndr
+ con_app env
= return (emptyFloats env', env')
| otherwise
@@ -4043,7 +4012,7 @@ mkDupableContWithDmds env dmds (TickIt t cont)
mkDupableContWithDmds env _
cont1@(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
, sc_env = se, sc_cont = cont})
--- See Note [Duplicating StrictBind]
+-- See (SB2) in Note [StrictBind]
-- K[ let x = <> in b ] --> join j x = K[ b ]
-- j <>
= do { let sb_env = case se of
@@ -4052,7 +4021,10 @@ mkDupableContWithDmds env _
-- The contIsDupable caught the OkDup case, and
-- we never build a StrictBind with a NoDup in it.
- ; (sb_env1, bndr') <- simplBinder sb_env bndr
+ -- A lambda binder may have only occurrence and demand info;
+ -- see (SB3) in Note [StrictBind]
+ ; let lam_bndr = mkLamBndrFromLetBndr bndr
+ ; (sb_env1, bndr') <- simplBinder sb_env lam_bndr
; (floats1, join_inner) <- simplNonRecBody sb_env1 from_what body cont
-- No need to use mkDupableCont before simplNonRecBody; we
-- use cont once here, and then share the result if necessary
@@ -4060,7 +4032,10 @@ mkDupableContWithDmds env _
; let join_body = wrapFloats floats1 join_inner
res_ty = contResultType cont
- ; mkDupableStrictBind env bndr' join_body res_ty }
+ -- bndr' is about to become a lambda binder, so it must have suitable
+ -- IdInfo; simplNonRecE ensures this. See Note [Core binder IdInfo invariants]
+ ; assertPpr (lamBndrInfoOK bndr') (ppr bndr' $$ ppr (idInfo bndr')) $
+ mkDupableStrictBind env bndr' join_body res_ty }
mkDupableContWithDmds env _
(StrictArg { sc_fun = fun, sc_cont = cont
@@ -4111,8 +4086,7 @@ mkDupableContWithDmds env dmds
, sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) }
mkDupableContWithDmds env dmds
- (ApplyToVal { sc_arg = arg, sc_env = se, sc_cast = arg_mco
- , sc_cont = cont, sc_hole_ty = hole_ty })
+ (ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = hole_ty })
= -- e.g. [...hole...] (...arg...)
-- ==>
-- let a = ...arg...
@@ -4124,12 +4098,12 @@ mkDupableContWithDmds env dmds
expectNonEmpty dmds
; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
; let env' = env `setInScopeFromF` floats1
- ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
+ ; arg' <- simplArg env' Nothing hole_ty arg
; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
; let all_floats = floats1 `addLetFloats` let_floats2
; return ( all_floats
- , ApplyToVal { sc_arg = triv_arg, sc_env = Simplified OkDup
- , sc_cast = MRefl, sc_cont = cont', sc_hole_ty = hole_ty }) }
+ , ApplyToVal { sc_arg = DoneEx triv_arg NotJoinPoint, sc_dup = OkDup
+ , sc_cont = cont', sc_hole_ty = hole_ty }) }
mkDupableContWithDmds env _
(Select { sc_bndr = case_bndr, sc_alts = alts, sc_env = se, sc_cont = cont })
@@ -4253,7 +4227,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
| otherwise = v
-- No lambda binder has an unfolding, but (currently) case binders can,
- -- so we must zap them here.
+ -- so we must zap them here. But case binders never have a pragma,
+ -- stable unfolding or RULES, so there is no need to zap those.
+ -- See Note [Core binder IdInfo invariants] in GHC.Core
join_rhs = mkLams (map zapIdUnfolding final_bndrs) rhs_with_seqs
; join_bndr <- newJoinId filtered_binders rhs_ty'
@@ -4267,9 +4243,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
, alt') }
-- See Note [Duplicated env]
-{-
-Note [Do not add unfoldings to join points at birth]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [Do not add unfoldings to join points at birth]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15360)
case (case (case (case ...))) of
@@ -4340,7 +4315,7 @@ The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
- StrictBind body Stop
+ StrictBind body Stop))
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
@@ -4479,7 +4454,7 @@ hack and bit us in multiple small and not-so-small ways
Consider this
case (case .. ) of c {
- I# c# -> ....c....
+ I# c# -> ....c.... }
If we make a join point with c but not c# we get
$j = \c -> ....c....
@@ -4569,7 +4544,7 @@ There are two ways to make it duplicable.
; False -> jump $j r2 }
Notice that Plan B is very like the way we handle strict bindings;
- see Note [Duplicating StrictBind]. And Plan B is exactly what we'd
+ see Note [StrictBind]. And Plan B is exactly what we'd
get if we turned use a case expression to evaluate the strict arg:
case (case x of { True -> r1; False -> r2 }) of
@@ -4642,23 +4617,80 @@ Note [Inline small things to avoid creating a thunk] in
Simplify.Utils. But if we do inline them, the entire process will
repeat -- back to exponential behaviour.
-So we are careful to keep the demand-info on a2 and a3. Then they'll
-be /strict/ let-bindings, which will be dealt with by StrictBind.
-That's why contIsDupableWithDmds is careful to propagage demand
-info to the auxiliary bindings it creates. See the Demand argument
-to makeTrivial.
-
-Note [Duplicating StrictBind]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We make a StrictBind duplicable in a very similar way to
-that for case expressions. After all,
- let x* = e in b is similar to case e of x -> b
-
-So we potentially make a join-point for the body, thus:
- let x = <> in b ==> join j x = b
- in j <>
-
-Just like StrictArg in fact -- and indeed they share code.
+So we are careful to keep the demand-info on a2 and a3. Then they'll be
+/strict/ let-bindings, which will be dealt with by `StrictBind` (see
+Note [StrictBind]). That's why `contIsDupableWithDmds` is careful to
+propagate demand info to the auxiliary bindings it creates. See the
+`Demand` argument to `makeTrivial`.
+
+Note [StrictBind]
+~~~~~~~~~~~~~~~~~
+We use StrictBind when we find
+ let x! = rhs in body
+where the `x` is definitely demanded in body. When this happens we can
+float out case-expressions etc from inside `rhs`; e.g.
+ let { x! = case a of (p,q) -> rhs } in b
+-->
+ case a of (p,q) -> let x! = rhs in b
+
+We simplify `rhs` with a StrictBind continuation that continues with
+`body`
+
+(SB1) We only use StrictBind when case-of-case is on:
+ see Note [Case-of-case and full laziness]
+
+(SB2) We make a StrictBind /duplicable/ in a very similar way to
+ that for case expressions. After all,
+ let x! = e in b is similar to case e of x -> b
+
+ So we potentially make a join-point for the body, thus:
+ let x = <> in b ==> join j x = b
+ in j <>
+
+ Just like StrictArg in fact -- and indeed they share code.
+
+(SB3) When we duplicate a StrictBind (SB2), the binder `x` becomes a lambda
+ binder, and so must satisfy `lamBndrInfoOK`; see Note [Core binder IdInfo
+ invariants] in GHC.Core. But a let-binder `x` usually has IdInfo that a
+ lambda binder may not have (an unfolding, arity, a demand signature...).
+
+ So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use
+ `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence
+ info and the demand info.
+
+ However, if the let-binder has
+ * RULES
+ * a stable unfolding
+ * a non-default inlining activation
+ we'd permanently lose these things if we lambda-bind it. For example:
+ let {-# NOINLINE x #-}
+ x! = case y of { ... }
+ in blah
+ If we make a join point j x = blah, we have nowhere convenient to put that
+ NOINLINE. Ditto INLINE or RULES. It's unusual. But it happens; one example
+ is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp
+ {-# NOINLINE res1 #-}
+ !res1 = unST fm s
+
+ So in these cases we simply don't use StrictBind -- see `useStrictBind`. We
+ could imagine instead imposing these conditions only when we /duplicate/ the
+ StrictBind, rather than when we /create/ it, but that would require a bigger
+ refactor.
+
+ What if a thunk has a strictness signature, or CPR information? We
+ could make `useStrictBind` say False in these cases too, but that turns
+ out to be a net loss: keeping a thunk is worse than losing the strictness
+ information. Example, where f1,f2 are both strict:
+ let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 }
+ in body
+ Keeping it as-is would use CBV for calls of `f` in `body`. But
+ allowing StrictBind would give us
+ join j f* = body
+ in case x of { True -> j f1; False -> j f2 }
+ which avoids the thunk. It's a trade-off.
+
+ For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap,
+ especially (B) CPR-led thunk splitting.
Note [Join point abstraction] Historical note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -12,7 +12,8 @@ module GHC.Core.Opt.Simplify.Utils (
tryEtaExpandRhs, wantEtaExpansion,
-- Inlining,
- preInlineUnconditionally, postInlineUnconditionally,
+ preInlineLetUnconditionally, preInlineBetaUnconditionally,
+ postInlineUnconditionally,
activeRule,
getUnfoldingInRuleMatch,
updModeForStableUnfoldings, updModeForRuleLHS, updModeForRuleRHS,
@@ -174,16 +175,14 @@ data SimplCont
-- Invariant: never an identity coercion
, sc_opt :: Bool -- True <=> sc_co has had optCoercion applied to it
-- See Note [Avoid re-simplifying coercions]
- -- in GHC.Core.Opt.Simplify.Iteration
, sc_cont :: SimplCont }
| ApplyToVal -- (ApplyToVal arg K)[e] = K[ e arg ]
{ sc_hole_ty :: OutType -- Type of the function, presumably (forall a. blah)
-- See Note [The hole type in ApplyToTy]
- , sc_env :: StaticEnv -- See Note [StaticEnv]
- , sc_arg :: CoreExpr -- The argument
- , sc_cast :: MOutCoercion -- Wrap this OutCoercion around the (simplified) argument
- -- See Note [The sc_cast field of ApplyToVal]
+ , sc_dup :: DupFlag -- See Note [The argument of ApplyToVal]
+ , sc_arg :: SimplClo -- The argument
+ -- Invariant: if sc_arg is a ContEx, then sc_dup = NoDup
, sc_cont :: SimplCont }
| ApplyToTy -- (ApplyToTy ty K)[e] = K[ e ty ]
@@ -201,10 +200,11 @@ data SimplCont
-- The two strict forms have no DupFlag, because we never duplicate them
| StrictBind -- (StrictBind x b K)[e] = let x = e in K[b]
-- or, equivalently, = K[ (\x.b) e ]
+ -- See Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration
{ sc_from :: FromWhat
, sc_env :: StaticEnv -- See Note [StaticEnv]
-- The sc_env in StrictBind is never (Simplified NoDup)
- , sc_bndr :: Id
+ , sc_bndr :: Id -- See (SB3) in Note [StrictBind]
, sc_body :: CoreExpr
, sc_cont :: SimplCont }
@@ -252,49 +252,85 @@ perhapsSubstTy (UnSimplified env) ty = substTy env ty
{- Note [StaticEnv]
~~~~~~~~~~~~~~~~~~~
-Consider ApplyToVal, which has
- sc_env :: StaticEnv
- sc_arg :: CoreExpr
-Initially, `sc_arg` is an un-simplified InExpr, and `sc_env` is (UnSimplified env),
-where `env` gives meaning to the free variables of `sc_arg`; in particular, `env`
-may have substitutions that must apply to the argument.
-
-But sometimes we simplify the argument, and in that case, `sc_arg` is an OutExpr,
-the simplified argument, and `sc_env` is (Simplified NoDup) or (Simplified OkDup).
-The former is the safe, conservative option, but in `mkDupableCont` we want to make
-the continuation duplicable, so we make the argument small and tag it with
-(Simplified OkDup).
-
-We later simplify the argument, e.g. in `simplArg`. Then
- * If sc_env is Simplified, it's a no-op
- * If sc_env is (UnSimplified arg_env) we simplify `sc_arg` with
- - Its captured envt `arg_env`
+Consider Select, which has
+ sc_env :: StaticEnv
+ sc_bndr :: Id
+ sc_alts :: [CoreAlt]
+Initially, `sc_bndr` and `sc_alts` are un-simplified InThings, and `sc_env` is
+(UnSimplified env), where `env` gives meaning to their free variables; in
+particular, `env` may have substitutions that must apply to them.
+
+But sometimes (notably in `mkDupableCont`) we simplify them, and in that case
+`sc_bndr` and `sc_alts` are OutThings, and `sc_env` is (Simplified dup).
+
+When we finally simplify the alternatives (see `mkAltEnv`)
+ * If sc_env is Simplified, there is nothing to do
+ * If sc_env is (UnSimplified alt_env) we simplify them with
+ - Their captured envt `alt_env`
- but overriding its InScopeSet with the larger one at the
simplification point.
Why override the InScopeSet? Example:
- (let y = ey in f) ex
- By the time we simplify ex, 'y' will be in scope.
- All this is done in `simplArg`.
+ case (let y = ey in f) of alts
+ By the time we simplify alts, 'y' will be in scope.
Note that:
* In the Simplified case there is no environment, because the substitution has
already been applied.
-* We say sc_arg :: CoreExpr, rather than sc_arg :: InExpr or sc_arg :: OutExpr,
- because whether it is InExpr or OutExpr depends on `sc_env`
+* We say sc_alts :: [CoreAlt], rather than [InAlt] or [OutAlt],
+ because whether they are InAlts or OutAlts depends on `sc_env`
+
+* Same deal for StrictBind, where the StaticEnv scopes over sc_bndr and sc_body.
-* Same deal for Select, and StrictBind, but the StaticEnv scopes over
- * sc_bndr and sc_alts (for Select)
- * sc_bndr and sc_body (for StrictBind)
+* ApplyToVal is similar, but simpler: it uses a SimplClo instead.
+ See Note [The argument of ApplyToVal].
-* Even though the InScopeSet of an (UnSimplified se) is overridden in `simplArg`,
- that InScopeSet is not irrelevant: it should include all the free vars of
- applying the substitution to the InExpr. Reason: contHoleType uses perhapsSubstTy
- to apply the substitution to the expression, and that (rightly) gives ASSERT
- failures if the InScopeSet isn't big enough.
+* Even though the InScopeSet of an (UnSimplified se) is overridden, that
+ InScopeSet is not irrelevant: it should include all the free vars of
+ applying the substitution to the InThing. Reason: contHoleType uses
+ perhapsSubstTy to apply the substitution to the binder, and that
+ (rightly) gives ASSERT failures if the InScopeSet isn't big enough.
(SE1) If dup = OkToDup, then continuation k is also ok-to-dup
+
+Note [The argument of ApplyToVal]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ApplyToVal has
+ sc_dup :: DupFlag
+ sc_arg :: SimplClo
+
+Initially, `sc_arg` is (ContEx env arg MRefl), where `arg` is the un-simplified
+InExpr, and `env` gives meaning to the free variables of `arg`; in particular,
+`env` may have substitutions that must apply to the argument.
+
+But sometimes we simplify the argument, and in that case, `sc_arg` is
+(DoneEx arg' NotJoinPoint), where `arg'` is the simplified argument.
+
+The `sc_dup` flag says whether the continuation can be duplicated. NoDup is
+the safe, conservative option, but in `mkDupableCont` we want to make the
+continuation duplicable, so we make the argument small (and hence a DoneEx)
+and set `sc_dup` to OkDup. Invariants:
+
+ (AV1) If `sc_arg` is a ContEx, then `sc_dup` is NoDup.
+
+ (AV2) If `sc_dup` is OkDup then `sc_cont` is also ok-to-dup; see (SE1)
+ in Note [StaticEnv].
+
+We later simplify the argument, in `simplArg`. Then
+ * If `sc_arg` is a DoneEx (or DoneId), it's a no-op
+ * If `sc_arg` is (ContEx arg_env arg mco) we simplify `arg` with
+ - Its captured envt `arg_env`
+ - but overriding its InScopeSet with the larger one at the
+ simplification point.
+ Why override the InScopeSet? Example:
+ (let y = ey in f) ex
+ By the time we simplify ex, 'y' will be in scope.
+ Then we wrap the cast `mco` around the result.
+ See Note [The MOutCoercion field of ContEx].
+
+Using a SimplClo for the argument means that it can be substituted for a lambda
+binder, in `preInlineBetaUnconditionally`, without further ado.
-}
instance Outputable DupFlag where
@@ -312,9 +348,9 @@ instance Outputable SimplCont where
= (text "TickIt" <+> ppr t) $$ ppr cont
ppr (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
= (text "ApplyToTy" <+> pprParendType ty) $$ ppr cont
- ppr (ApplyToVal { sc_arg = arg, sc_env = env, sc_cont = cont, sc_hole_ty = hole_ty })
- = (hang (text "ApplyToVal" <> braces (ppr env) <+> text "hole-ty:" <+> pprParendType hole_ty)
- 2 (pprParendExpr arg))
+ ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont, sc_hole_ty = hole_ty })
+ = (hang (text "ApplyToVal" <> braces (ppr dup) <+> text "hole-ty:" <+> pprParendType hole_ty)
+ 2 (ppr arg))
$$ ppr cont
ppr (StrictBind { sc_bndr = b, sc_cont = cont })
= (text "StrictBind" <+> ppr b) $$ ppr cont
@@ -433,8 +469,8 @@ pushOutArgs fun_ty (arg:args) cont
= ApplyToTy { sc_hole_ty = fun_ty, sc_arg_ty = ty
, sc_cont = pushOutArgs (piResultTy fun_ty ty) args cont }
| otherwise
- = ApplyToVal { sc_hole_ty = fun_ty, sc_cast = MRefl
- , sc_arg = arg, sc_env = Simplified NoDup
+ = ApplyToVal { sc_hole_ty = fun_ty
+ , sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
, sc_cont = pushOutArgs (funResultTy fun_ty) args cont}
pushArgSpecs :: [ArgSpec] -- In normal, forward order
@@ -445,7 +481,7 @@ pushArgSpec :: ArgSpec -> SimplCont -> SimplCont
pushArgSpec (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }) cont
= ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont }
pushArgSpec (ValArg { as_arg = arg, as_hole_ty = hole_ty }) cont
- = ApplyToVal { sc_arg = arg, sc_env = Simplified NoDup, sc_cast = MRefl
+ = ApplyToVal { sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
, sc_hole_ty = hole_ty, sc_cont = cont }
argSpecArg :: ArgSpec -> OutExpr
@@ -496,7 +532,12 @@ contIsStop _ = False
contIsDupable :: SimplCont -> Bool
contIsDupable (Stop {}) = True
contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k
-contIsDupable (ApplyToVal { sc_env = se }) = okToDupSE se -- See (SE1) in Note [StaticEnv]
+contIsDupable (ApplyToVal { sc_dup = dup, sc_arg = arg })
+ = assertPpr (not (okToDup dup && is_cont_ex arg)) (ppr arg) $
+ okToDup dup -- See (AV1,AV2) in Note [The argument of ApplyToVal]
+ where
+ is_cont_ex (ContEx {}) = True
+ is_cont_ex _ = False
contIsDupable (Select { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictBind { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictArg { sc_dup = dup }) = okToDup dup -- ...ditto...
@@ -605,8 +646,8 @@ contArgs env cont
lone (CastIt {}) = False -- stops it being "lone"
lone _ = True
- go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k })
- = go (interestingArg env se arg : args) k
+ go args (ApplyToVal { sc_arg = arg, sc_cont = k })
+ = go (interestingArg env arg : args) k
go args (ApplyToTy { sc_cont = k }) = go args k
go args (CastIt { sc_cont = k }) = go args k
go args k = (False, reverse args, k)
@@ -621,15 +662,13 @@ contOutArgs env cont
go (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
= Type ty : go cont
- go (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = cont })
- = case se of
- Simplified {} -> arg : go cont
- UnSimplified env -> GHC.Core.Subst.substExpr (getFullSubst in_scope env) arg : go cont
- -- Make sure we apply the static environment `sc_env` as a substitution
+ go (ApplyToVal { sc_arg = arg, sc_cont = cont })
+ = simplCloExpr in_scope arg : go cont
+ -- Make sure we apply the static environment of a ContEx as a substitution
-- to get an OutExpr. See (BF1) in Note [tryRules: plan (BEFORE)]
-- in GHC.Core.Opt.Simplify.Iteration
- -- NB: we use substExpr, not substExprSC: we want to get the benefit of
- -- knowing what is evaluated etc, via the in-scope set
+ -- simplCloExpr also wraps the pending cast (if any) around the argument;
+ -- omitting it can make a rule fail to match (#27963)
-- No more arguments
go _ = []
@@ -826,23 +865,86 @@ make use of the strictness info for the function.
* *
********************************************************************* -}
-{- Note [The sc_cast field of ApplyToVal]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [The MOutCoercion field of ContEx]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the `ApplyToVal` case of `pushCast` we want to push an `OutCoercion` into the
-argument. But the argument may or may not have been simplified (see Note [StaticEnv])
-so we definitely can't just wrap the cast around the argument. Instead we store it
-in the `sc_cast` field -- this is the whole reason for the `sc_cast` field.
+argument. But the argument may or may not have been simplified (see Note [The
+argument of ApplyToVal]):
+
+* If it has been simplified, it is (DoneEx arg' _), and we can simply wrap the
+ cast around `arg'`.
+
+* If it has not, it is (ContEx env arg mco), and we definitely can't just wrap
+ the (Out)cast around the InExpr `arg`. Instead we compose it with `mco` --
+ this is the whole reason for the MOutCoercion field of `ContEx`.
+
+All this is done by `mkCloCastMCo`.
We deal with that pending cast mainly in `simplArg`.
But we /also/ sometimes want to substitute that argument for a lambda-binder, in
-`preInlineUnconditionally`. So we also have to put that pending cast into
-`ContEx`; hence the MOutCoercion field of `ContEx`. Then we deal with it
-appropriately when /applying/ the substitution in `simplInId`.
+`preInlineBetaUnconditionally`; and since the substitution maps an Id to a SimplClo,
+the pending cast comes along for free. Then we deal with it appropriately when
+/applying/ the substitution in `simplInId`.
+
+Note [Optimising reflexivity]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+It's important (for compiler performance) to get rid of reflexivity as soon
+as it appears. See #11735, #14737, and #15019.
+
+In particular, we want to behave well on
+
+ * e |> co1 |> co2
+ where the two happen to cancel out entirely. That is quite common;
+ e.g. a newtype wrapping and unwrapping cancel.
+
+
+ * (f |> co) @t1 @t2 ... @tn x1 .. xm
+ Here we will use pushCoTyArg and pushCoValArg successively, which
+ build up SelCo stacks. Silly to do that if co is reflexive.
+
+However, we don't want to call isReflexiveCo too much, because it uses
+type equality which is expensive on big types (#14737 comment:7).
+
+A good compromise (determined experimentally) seems to be to call
+isReflexiveCo
+ * when composing casts, and
+ * at the end
+
+In investigating this I saw missed opportunities for on-the-fly
+coercion shrinkage. See #15090.
+
+Note [Avoid re-simplifying coercions]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+In some benchmarks (with deeply nested cases) we successively push
+casts onto the SimplCont. We don't want to call the coercion optimiser
+on each successive composition -- that's at least quadratic. So:
+
+* The CastIt constructor in SimplCont has a `sc_opt :: Bool` flag to
+ record whether the coercion optimiser has been applied to the coercion.
+
+* In `simplCast`, when we see (Cast e co), we simplify `co` to get
+ an OutCoercion, and built a CastIt with sc_opt=True.
+
+ Actually not quite: if we are simplifying the result of inlining an
+ unfolding (seInlineDepth > 0), then instead of /optimising/ it again,
+ just /substitute/ which is cheaper. See `simplCoercion`.
+
+* In `pushCast` if we combine this new coercion with an existing one,
+ we build a CastIt for (co1 ; co2) with sc_opt=False.
+
+* When unpacking a CastIt, in `rebuild`, we optimise the (presumably
+ composed) coercion if sc_opt=False; this is done by `optOutCoercion`.
+
+* When duplicating a continuation in `mkDupableContWithDmds`, before
+ duplicating a CastIt, optimise the coercion. Otherwise we'll end up
+ optimising it separately in the duplicate copies.
+
+* See also Note [The MOutCoercion field of ContEx]
-}
optOutCoercion :: SimplEnvIS -> OutCoercion -> Bool -> OutCoercion
--- See Note [Avoid re-simplifying coercions] in GHC.Core.Opt.Simplify.Iteration
+-- See Note [Avoid re-simplifying coercions]
optOutCoercion env co already_optimised
| already_optimised = co -- Ditto
| otherwise = optCoercion opts empty_subst co
@@ -862,16 +964,17 @@ pushCastMCo env (MCo co) cont = pushCast env co cont
pushCast :: SimplEnv -> OutCoercion -> SimplCont -> SimplCont
pushCast env co cont
- = go co True cont
+ | isReflCo co = cont -- See Note [Optimising reflexivity]
+ | otherwise = go co True cont
where
-- ToDo: pushCast Refl (ApplylToVal arg1 (ApplyToVal arg2 ...))
-- will do lots of unnecessary work.
go :: OutCoercion -> Bool -> SimplCont -> SimplCont
- go co1 _ (CastIt { sc_co = co2, sc_cont = cont }) -- See Note [Optimising reflexivity] in GHC.Core.Opt.Simplify.Iteration
+ go co1 _ (CastIt { sc_co = co2, sc_cont = cont }) -- See Note [Optimising reflexivity]
= go (mkTransCo co1 co2) False cont
-- False: (mkTransCo co1 co2) is not fully optimised
- -- See Note [Avoid re-simplifying coercions] in GHC.Core.Opt.Simplify.Iteration
+ -- See Note [Avoid re-simplifying coercions]
go co co_is_opt (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail })
| Just (tyL, arg_ty', m_co') <- pushCoTyArg co arg_ty
@@ -886,26 +989,22 @@ pushCast env co cont
-- where co :: (s1->s2) ~ (t1->t2)
-- co1 :: t1 ~ s1
-- co2 :: s2 ~ t2
- go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_env = arg_se
- , sc_cast = arg_mco, sc_cont = tail })
+ go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_cont = tail })
| not co_is_opt
= -- pushCoValArg duplicates the coercion, so optimise first
go (optOutCoercion (zapSubstEnv env) co co_is_opt) True cont
| Just (tyL, m_co1, m_co2) <- pushCoValArg co
= {-#SCC "addCoerce-pushCoValArg" #-}
- -- Dealing with m_co1 is the entire reason for the sc_cast field
- -- of ApplyToVal; see Note [The sc_cast field of ApplyToVal]
- ApplyToVal { sc_arg = arg
- , sc_env = arg_se
- , sc_cast = arg_mco `mkTransMCo` m_co1
- , sc_cont = go_mco m_co2 True tail
- , sc_hole_ty = tyL }
+ -- See Note [The MOutCoercion field of ContEx]
+ cont { sc_arg = mkCloCastMCo arg m_co1
+ , sc_cont = go_mco m_co2 True tail
+ , sc_hole_ty = tyL }
go co co_is_opt cont
| isReflCo co = cont -- Having this at the end makes a huge
-- difference in T12227, for some reason
- -- See Note [Optimising reflexivity] in GHC.Core.Opt.Simplify.Iteration
+ -- See Note [Optimising reflexivity]
| otherwise = CastIt { sc_co = co, sc_opt = co_is_opt, sc_cont = cont }
-- If the first parameter is MRefl, then simplifying revealed a
@@ -914,6 +1013,13 @@ pushCast env co cont
go_mco MRefl _ cont = cont
go_mco (MCo co) opt cont = go co opt cont
+mkCloCastMCo :: SimplClo -> MOutCoercion -> SimplClo
+-- See Note [The MOutCoercion field of ContEx]
+mkCloCastMCo clo MRefl = clo
+mkCloCastMCo (DoneId v) (MCo co) = DoneEx (mkCast (Var v) co) NotJoinPoint
+mkCloCastMCo (DoneEx e _) (MCo co) = DoneEx (mkCast e co) NotJoinPoint
+mkCloCastMCo (ContEx se e mco) (MCo co) = ContEx se e (mco `mkTransMCo` MCo co)
+
{-
************************************************************************
@@ -1227,19 +1333,17 @@ Wrinkles:
-}
-interestingArg :: SimplEnv -> StaticEnv -> CoreExpr -> ArgSummary
+interestingArg :: SimplEnv -> SimplClo -> ArgSummary
-- See Note [Interesting arguments]
-interestingArg env se e
- = case se of
- Simplified {} -> go env 0 e
- UnSimplified static_env -> go (static_env `setInScopeFromE` env) 0 e
+interestingArg env clo
+ = go_clo env 0 clo
where
+ go_clo _ n (DoneId v) = go_var n v
+ go_clo env n (DoneEx e _) = go (zapSubstEnv env) n e
+ go_clo env n (ContEx se e _) = go (se `setInScopeFromE` env) n e
+
-- n is # value args to which the expression is applied
- go env n (Var v)
- = case substId env v of
- DoneId v' -> go_var n v'
- DoneEx e _ -> go (zapSubstEnv env) n e
- ContEx se e _mco -> go (se `setInScopeFromE` env) n e
+ go env n (Var v) = go_clo env n (substId env v)
go _ _ (Lit l)
| isLitRubbish l = NonTrivArg -- See (IA3) in Note [Interesting arguments]
@@ -1738,15 +1842,15 @@ is a term (not a coercion) so we can't necessarily inline the latter in
the former.
-}
-preInlineUnconditionally
+preInlineLetUnconditionally
:: SimplEnv -> TopLevelFlag -> InId
- -> StaticEnv -> CoreExpr -> MOutCoercion -- The argument
+ -> InExpr -> SimplEnv -- These two go together
-> Maybe SimplEnv -- Returned env has extended substitution
-- Precondition: rhs satisfies the let-can-float invariant
-- See Note [Core let-can-float invariant] in GHC.Core
-- Reason: we don't want to inline single uses, or discard dead bindings,
-- for unlifted, side-effect-ful bindings
-preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
+preInlineLetUnconditionally env top_lvl bndr rhs rhs_env
| not pre_inline_unconditionally = Nothing
| not active = Nothing
| isTopLevel top_lvl && isDeadEndId bndr = Nothing -- Note [Top-level bottoming Ids]
@@ -1758,26 +1862,15 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- See Note [Stable unfoldings and preInlineUnconditionally]
| not (isInlinePragma inline_prag)
- , Just inl <- maybeUnfoldingTemplate unf = assertPpr (isReflMCo rhs_mco) (ppr bndr) $
- Just $! (extend_subst_with inl)
+ , Just inl <- maybeUnfoldingTemplate unf = Just $! (extend_subst_with inl)
| otherwise = Nothing
where
unf = idUnfolding bndr
- -- If the rhs is /not/ already simplified, extend the envt with ContEx, which captures
- -- the the lexical environment for us to restore in `simplInId`.
- -- If the rhs /is/ already simplified, then extend the envt with DoneEx;
- -- That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
- -- the RHS.
- -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
- extend_subst_with inl_rhs
- = extendIdSubst env bndr $!
- case rhs_se of
- Simplified _ -> case rhs_mco of
- MRefl -> DoneEx inl_rhs NotJoinPoint -- Common case
- MCo co -> DoneEx (mkCast inl_rhs co) NotJoinPoint
- UnSimplified rhs_env -> ContEx rhs_env inl_rhs rhs_mco
+ -- The rhs is not yet simplified, so extend the envt with ContEx, which
+ -- captures the lexical environment for us to restore in `simplInId`.
+ extend_subst_with inl_rhs = extendIdSubst env bndr $! ContEx rhs_env inl_rhs MRefl
one_occ IAmDead = True -- Happens in ((\x.1) v)
one_occ OneOcc{ occ_n_br = 1
@@ -1793,39 +1886,6 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- See Note [pre/postInlineUnconditionally in gentle mode]
inline_prag = idInlinePragma bndr
--- Be very careful before inlining inside a lambda, because (a) we must not
--- invalidate occurrence information, and (b) we want to avoid pushing a
--- single allocation (here) into multiple allocations (inside lambda).
--- Inlining a *function* with a single *saturated* call would be ok, mind you.
--- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
--- where
--- is_cheap = exprIsCheap rhs
--- ok = is_cheap && int_cxt
-
- -- int_cxt The context isn't totally boring
- -- E.g. let f = \ab.BIG in \y. map f xs
- -- Don't want to substitute for f, because then we allocate
- -- its closure every time the \y is called
- -- But: let f = \ab.BIG in \y. map (f y) xs
- -- Now we do want to substitute for f, even though it's not
- -- saturated, because we're going to allocate a closure for
- -- (f y) every time round the loop anyhow.
-
- -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
- -- so substituting rhs inside a lambda doesn't change the occ info.
- -- Sadly, not quite the same as exprIsHNF.
- canInlineInLam (Lit _) = True
- canInlineInLam (Cast e _) = canInlineInLam e
- canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
- canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
- canInlineInLam (Var v) = case idOccInfo v of
- OneOcc { occ_in_lam = IsInsideLam } -> True
- ManyOccs {} -> True
- _ -> False
- canInlineInLam _ = False
- -- not ticks. Counting ticks cannot be duplicated, and non-counting
- -- ticks around a Lam will disappear anyway.
-
early_phase =
case sePhase env of
SimplPhase p -> p /= FinalPhase
@@ -1856,6 +1916,97 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- (Nor can we check for `exprIsExpandable rhs`, because that needs to look
-- at the non-existent unfolding for the `I# 2#` which is also floated out.)
+preInlineBetaUnconditionally
+ :: SimplEnv -> Levity -> InId
+ -> SimplClo -- The argument
+ -> Maybe SimplEnv -- Returned env has extended substitution
+-- Like preInlineLetUnconditionally, but for a beta-redex (\bndr. body) arg
+-- The argument may or may not be already simplified (DoneEx or ContEx)
+--
+-- The binder is a lambda binder and so lacks most IdInfo;
+-- see Note [Core binder IdInfo invariants]
+--
+-- Compared to preInlineLetUnconditionally we omit some checks:
+-- * The binder is never top-level, so no need for the
+-- Note [Top-level bottoming Ids] check, nor for `early_phase`
+-- * A lambda binder is never a join point, so no need for the
+-- Note [Do not inline exit join points] check
+-- * A lambda binder never has an inline pragma, a stable unfolding, or RULES
+-- (see `lamBndrInfoOK`), so no need to check activation, nor for
+-- Note [Stable unfoldings and preInlineUnconditionally]
+--
+-- And we add one extra one
+-- * Check the let-can-float invariant, and don't inline if not
+
+preInlineBetaUnconditionally env levity bndr arg
+ | assertPpr (lamBndrInfoOK bndr) (ppr bndr) $
+ not pre_inline_unconditionally = Nothing
+ | isCoVar bndr = Nothing -- Note [Do not inline CoVars unconditionally]
+ | not (one_occ (idOccInfo bndr)) = Nothing
+ | needs_case_binding = Nothing -- Enforce the let-can-float invariant
+ | otherwise = Just $! extendIdSubst env bndr arg
+ -- If the arg is not yet simplified, it is a ContEx, which captures the
+ -- lexical environment for us to restore in `simplInId`.
+ -- If the arg is already simplified, then it is a DoneEx;
+ -- That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
+ -- the arg.
+ -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
+ where
+ pre_inline_unconditionally = sePreInline env
+
+ needs_case_binding = needsCaseBindingL levity rhs
+ -- Ok to test an InExpr or OutExpr in needsCaseBindingL because
+ -- exprOkForSpeculation is stable under simplification
+
+ rhs :: CoreExpr -- Can be InExpr or OutExpr, but here it does not matter
+ rhs = case arg of
+ ContEx _ e _ -> e -- InExpr
+ DoneEx e _ -> e -- OutExpr
+ DoneId v -> Var v -- OutExpr
+
+ one_occ IAmDead = True -- Happens in ((\x.1) v)
+ one_occ OneOcc{ occ_n_br = 1
+ , occ_in_lam = NotInsideLam } = True
+ one_occ OneOcc{ occ_n_br = 1
+ , occ_in_lam = IsInsideLam
+ , occ_int_cxt = IsInteresting } = canInlineInLam rhs
+ one_occ _ = False
+
+
+canInlineInLam :: CoreExpr -> Bool
+-- Be very careful before inlining inside a lambda, because (a) we must not
+-- invalidate occurrence information, and (b) we want to avoid pushing a
+-- single allocation (here) into multiple allocations (inside lambda).
+-- Inlining a *function* with a single *saturated* call would be ok, mind you.
+-- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
+-- where
+-- is_cheap = exprIsCheap rhs
+-- ok = is_cheap && int_cxt
+
+ -- int_cxt The context isn't totally boring
+ -- E.g. let f = \ab.BIG in \y. map f xs
+ -- Don't want to substitute for f, because then we allocate
+ -- its closure every time the \y is called
+ -- But: let f = \ab.BIG in \y. map (f y) xs
+ -- Now we do want to substitute for f, even though it's not
+ -- saturated, because we're going to allocate a closure for
+ -- (f y) every time round the loop anyhow.
+
+ -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
+ -- so substituting rhs inside a lambda doesn't change the occ info.
+ -- Sadly, not quite the same as exprIsHNF.
+canInlineInLam (Lit _) = True
+canInlineInLam (Cast e _) = canInlineInLam e
+canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
+canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
+canInlineInLam (Var v) = case idOccInfo v of
+ OneOcc { occ_in_lam = IsInsideLam } -> True
+ ManyOccs {} -> True
+ _ -> False
+canInlineInLam _ = False
+ -- not ticks. Counting ticks cannot be duplicated, and non-counting
+ -- ticks around a Lam will disappear anyway.
+
{-
************************************************************************
* *
=====================================
compiler/GHC/Core/Opt/SpecConstr.hs
=====================================
@@ -2068,7 +2068,12 @@ mkSeqs seqees res_ty rhs =
-- Argument representing strict field and it's worth passing via cbv
| wantCbvForId arg_id
= Case (Var arg_id)
- (localiseId arg_id) -- See (SCF1) in Note [SpecConstr and strict fields]
+ (mkCaseBndrFromLetBndr arg_id)
+ -- mkCaseBndrFromLetBndr: arg_id may have IdInfo (e.g. an unfolding,
+ -- if it is a global) that a case binder must not have;
+ -- see Note [Core binder IdInfo invariants] in GHC.Core
+ -- Note that mkCaseBndrFromLetBndr also does localiseId:
+ -- see (SCF1) in Note [SpecConstr and strict fields]
res_ty
([Alt DEFAULT [] rhs])
=====================================
compiler/GHC/Core/Opt/WorkWrap.hs
=====================================
@@ -598,13 +598,19 @@ tryWW ww_opts is_rec fn_id rhs
= splitFun ww_opts new_fn_id rhs
-- See Note [Thunk splitting]
- | isNonRec is_rec, is_thunk
- = splitThunk ww_opts is_rec new_fn_id rhs
+ | isNonRec is_rec -- See (TS4)
+ , is_thunk -- All join points go via splitFun
+ = do { -- Try strictness then CPR; see (TS5)
+ rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM`
+ splitThunkCpr ww_opts new_fn_id rhs `orElseM`
+ return rhs
+ ; return [ (new_fn_id, rhs') ] }
| otherwise
= return [ (new_fn_id, rhs) ]
where
+ is_join = isJoinId fn_id
fn_info = idInfo fn_id
(wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info)
new_fn_id = zap_join_cpr $ zap_usage fn_id
@@ -613,14 +619,13 @@ tryWW ww_opts is_rec fn_id rhs
-- See Note [Zapping DmdEnv after Demand Analyzer] and
-- See Note [Zapping Used Once info in WorkWrap]
- zap_join_cpr id
- | isJoinId id = id `setIdCprSig` topCprSig
- | otherwise = id
+ zap_join_cpr id | is_join = id `setIdCprSig` topCprSig
+ | otherwise = id
-- See Note [Don't w/w join points for CPR]
- is_fun = notNull wrap_dmds || isJoinId fn_id
- is_thunk = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id)
- && not (isUnliftedType (idType fn_id))
+ is_fun = notNull wrap_dmds || is_join
+ is_thunk = not (exprIsHNF rhs)
+ && not (isUnliftedType (idType fn_id))
{-
Note [Zapping DmdEnv after Demand Analyzer]
@@ -806,7 +811,7 @@ splitFun ww_opts fn_id rhs
(wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info)
- cpr_ty = getCprSig (cprSigInfo fn_info)
+ cpr_ty = cprSigType (cprSigInfo fn_info)
-- Arity of the CPR sig should match idArity when it's not a join point.
-- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal
cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info)
@@ -957,114 +962,165 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>]
Note [Thunk splitting]
~~~~~~~~~~~~~~~~~~~~~~
-Suppose x is used strictly; never mind whether it has the CPR
-property. I'll use a '*' to mean "x* is demanded strictly".
-
- let
- x* = x-rhs
+The worker/wrapper split mainly affects let-bound /functions/. But we can also use
+demand and CPR information to improve let-bound /thunks/. Specifically:
+
+* (A) Demand-led thunk splitting:
+ If a thunk is demanded strictly, perhaps nestedly, we can turn it into a
+ case, perhaps nestedly. For example
+ let x :: (Int, Int)
+ {- Dmd = SP(S,L) -}
+ x = rhs
+ in body
+ We would ultimately like to get
+ case rhs of x { (a,b) ->
+ case a of { I# a# ->
+ body
+
+ This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x`
+ and `a` inside `body`.
+
+* (B) CPR-led thunk splitting:
+ If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly
+ at top level, we can again generate a case
+ let x :: (Int, Int)
+ {- Dmd = S, Cpr = (_, I# _) -}
+ x = rhs
+ in body
+ The CPR info says that if `x` is evaluated (which it is), it'll return a pair,
+ whose second component can very cheaply be evaluated to a (I# b#). We would
+ like to end up with
+ case rhs of x { (a,b) ->
+ case b of { I# b# ->
+ body
+ which is good for the same reasons as before. See (TS3) for an example.
+
+Implementation
+~~~~~~~~~~~~~~
+The worker/wrapper pass does not generate these nested case expressions directly.
+Instead it generates a regular let-binding but, since the binder is marked as
+strict, any `case` expressions in the RHS will float out. Specifically:
+
+(TS1) For (A), `splitThunkStr` generates the binding
+ let x* = case rhs of { (a,b) ->
+ case a of { I# a# ->
+ (I# a, b)
+ Now when the Simplifier floats the `case` expressions out, we get
+ case rhs of { (a,b) ->
+ case a of { I# a# ->
+ let x = (I# a, b)
in body
+ which is equivalent to the expression in (A) above.
-splitThunk transforms like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> I# a }
- in body
+ `splitThunkStr` also works on /absent/ thunks: see (TS6).
-This is a little strange: we are re-using the same `x` in the RHS; and
-the RHS takes `x` apart and reboxes it. But because the outer 'let' is
-strict, and the inner let mentions `x` only once, the simplifier
-transform it to
- case x-rhs of
- I# a -> let x* = I# a
- in body
-
-That is good: in `body` we know the form of `x`, which
- * gives the CPR property, and
- * allows case-of-case to happen on x
-
-Notes
-* I tried transforming like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> x }
- in body
- where I return `x` itself, rather than reboxing it. But this
- turned out to cause some regressions, which I never fully
- investigated.
-
-* Suppose x-rhs is itself a case:
- x-rhs = case e of { T -> I# e1; F -> I# e2 }
- Then we'll get
- join j a = let x* = I# a in body
- in case e of { T -> j e1; F -> j e2 }
- which is good (no boxing). But in the original, unsplit program
- we would transform
- let x* = case e of ... in body
- ==> join j2 x = body
- in case e of { T -> j2 (I# e1); F -> j (I# e2) }
+ Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function
+ argument w/w splitting function, to do the unpacking. This automatically
+ deals with nested strictness.
+
+(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again
+ using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks.
+
+Wrinkles:
+
+(TS3) Here's an example of (B), thunk-splitting based on CPR information, in action.
+ Suppose we have
+ let x* = case e of { T -> Just e1; F -> Just e2 }
+ in body
+ If the Simplifier floats the `case` out, we get
+ join j2 x = body
+ in case e of { T -> j2 (Just e1); F -> j2 (Just e2) }
which is not good (boxing).
-* In fact, splitThunk uses the function argument w/w splitting
- function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L))
- then the splitting will go deeper too.
+ If we first do the thunk-splitting transformation, we get
+ let x* = case (case e of { T -> Just e1; F -> Just e2 }) of
+ Just a -> Just a
+ in body
-* For recursive thunks, the Simplifier is unable to float `x-rhs` out of
- `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
- back to the original definition, so we just split non-recursive thunks.
+ Now when the Simplifier floats we will get:
+ join j a = let x* = Just a in body
+ in case e of { T -> j e1; F -> j e2 }
+ which is much better (no boxing).
-Note [Thunk splitting for top-level binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Top-level bindings are never strict. Yet they can be absent, as T14270 shows:
-
- module T14270 (mkTrApp) where
- mkTrApp x y
- | Just ... <- ... typeRepKind x ...
- = undefined
- | otherwise
- = undefined
- typeRepKind = Tick scc undefined
-
-(T19180 is a profiling-free test case for this)
-Note that `typeRepKind` is not exported and its only use site in
-`mkTrApp` guards a bottoming expression. Thus, demand analysis
-figures out that `typeRepKind` is absent and splits the thunk to
-
- typeRepKind =
- let typeRepKind = Tick scc undefined in
- let typeRepKind = absentError in
- typeRepKind
-
-But now we have a local binding with an External Name
-(See Note [About the NameSorts]). That will trigger a CoreLint error, which we
-get around by localising the Id for the auxiliary bindings in 'splitThunk'.
+(TS4) We only do thunk-splitting for thunks that are non-recursive
+ For recursive thunks, the Simplifier is unable to float `x-rhs` out of
+ `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
+ back to the original definition.
+
+(TS5) Notice that (B) CPR-led thunk splitting can be useful:
+ * when multi-constructor data types are involved, so that the argument-unboxing
+ mechanism (A) is impotent. See the example in (TS3), which uses `Maybe`.
+ * when the binder is only demanded head-strictly, but CPR has nested information.
+
+ So (A) and (B) have complementary benefits. We might do even better by
+ /combining/ (A) and (B), but at the moment we try (A) first, and then try (B)
+ if (A) is impotent. Combining them would be more work.
+
+(TS6) We can also exploit /absence/. Consider
+ let x {-# Dmd = A #-} = rhs
+ in body
+ Generally speaking `x` will be absent becuase it is passed to functions that
+ don't use it, in which case worker/wrapper on those calls will make `x` unused.
+ But suppose `x` is absent inside a /lazy/ argument:
+ let f p = (fst p, 99) in
+ let x = rhs in
+ f (True, x)
+ Here f's argument is lazy, but `x` is definitely absent, and we could replace
+ `x` with an absent filler. Using (TS1) would give us
+ let x = absentError "urk" in ...
+ which is great.
+
+ So `splitThunkStr` works /regardless/ of the demand on `x`; whether it fires is
+ determined only by the `useful` flag returned by `mkWWstr_one`.
+
+(TS7) Adopting (TS6) leads to one other complication: a top-level binder with
+ an External Name (see Note [About the NameSorts]) can be Absent. If so,
+ it must not be used as a local binder in the `Let` created by `splitThunkStr`.
+ T19180 is a test case for this rather obscure situation.
+
+ Solution: use `localiseId` to localise the binder for the `Let`.
-}
--- | See Note [Thunk splitting].
---
--- splitThunk converts the *non-recursive* binding
+-- | splitThunkStr converts the *non-recursive* binding
-- x = e
-- into
--- x = let x' = e in
--- case x' of I# y -> let x' = I# y in x'
--- See comments above. Is it not beautifully short?
--- Moreover, it works just as well when there are
--- several binders, and if the binders are lifted
--- E.g. x = e
--- --> x = let x' = e in
--- case x' of (a,b) -> let x' = (a,b) in x'
--- Here, x' is a localised version of x, in case x is a
--- top-level Id with an External Name, because Lint rejects local binders with
--- External Names; see Note [About the NameSorts] in GHC.Types.Name.
---
--- How can we do thunk-splitting on a top-level binder? See
--- Note [Thunk splitting for top-level binders].
-splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)]
-splitThunk ww_opts is_rec x rhs
- = assert (not (isJoinId x)) $
- do { let x' = localiseId x -- See comment above
- ; (useful,_args, wrap_fn, fn_arg)
- <- mkWWstr_one ww_opts x' NotMarkedStrict
- ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ]
- ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive
- return res
- else return [(x, rhs)] }
+-- x = let x = e in
+-- case x of I# y -> I# y
+-- See Note [Thunk splitting].
+splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+splitThunkStr ww_opts x rhs
+ = do { let x' = localiseId x -- See (TS7)
+ ; (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts x' NotMarkedStrict
+ -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting]
+
+ ; if useful
+ then return (Just (Let (NonRec x' rhs) $
+ wrap_fn fn_arg))
+ else return Nothing }
+
+splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+-- See Note [Thunk splitting]
+-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR
+-- property, say Just (Just _), return this new RHS:
+-- let x' = rhs in
+-- case x' of { Just p -> case p of { Just q -> -- Unpacking code
+-- Just (Just q) }} -- Repacking code
+-- Works for multi-constructor data types, where splitThunkStr will fail
+splitThunkCpr ww_opts x rhs
+ | isStrUsedDmd (idDemandInfo x) -- See (TS2)
+ = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $ -- It's a thunk
+ do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr
+ -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting]
+ ; if useful
+ then return (Just (Let (NonRec x rhs) $
+ unpacker rebuild_result))
+ else return Nothing }
+
+ | otherwise
+ = return Nothing
+ where
+ cpr_type :: CprType
+ cpr_type = cprSigType (idCprSig x)
+ cpr :: Cpr
+ cpr = cprTypeCpr cpr_type
+
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser
{-# LANGUAGE ViewPatterns #-}
module GHC.Core.Opt.WorkWrap.Utils
- ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one
+ ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one
, needsVoidWorkerArg
, DataConPatContext(..)
, UnboxingDecision(..), canUnboxArg
@@ -230,8 +230,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
; let (work_args, work_marks) = unzip work_args_str
-- Do CPR w/w. See Note [Always do CPR w/w]
- ; (useful2, wrap_fn_cpr, work_fn_cpr)
- <- mkWWcpr_entry opts res_ty' res_cpr
+ ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr
; let (work_lam_args, work_call_args, work_call_str)
| needsVoidWorkerArg fun_id arg_vars work_args
@@ -985,6 +984,12 @@ mkWWstr opts args str_marks
-- * wrap_arg assumes work_args are in scope, and builds a ConApp that
-- reconstructs the RHS of wrap_var that we pass to the original RHS
-- See Note [Worker/wrapper for Strictness and Absence]
+--
+-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int
+-- = ( True -- useful
+-- , [p,q#], -- work_args
+-- , \e -> case x of (p,q) -> case q of I# q# -> e -- wrap_fn
+-- , (p, I# q) ) -- wrap_arg
mkWWstr_one :: WwOpts
-> Var
-> StrictnessMark
@@ -1041,7 +1046,7 @@ unbox_one_arg opts arg_var
-- Apply str info to new args. Also remove OtherCon unfoldings so they
-- don't end up in lambda binders of the worker.
- -- See Note [Never put `OtherCon` unfoldings on lambda binders]
+ -- See (CBI1) in Note [Core binder IdInfo invariants]
arg_ids' = map zapIdUnfolding $
zipWithEqual setIdDemandInfo arg_ids ds
@@ -1637,7 +1642,9 @@ mk_res_bndr body_ty = do
-- 1. A 'WwUse' capturing whether the split does anything useful.
-- 2. The list of transit variables (see the Note).
-- 3. The result builder expression for the wrapper. The original case binder if not useful.
--- 4. The result unpacking expression for the worker. 'nop_fn' if not useful.
+-- Assumes that the transit vars are in scope
+-- 4. The result unpacking expression for the worker. 'nop_fn' if not useful
+-- Brings the transit vars into scope
type CprWwResultOne = (WwUse, OrdList Var, CoreExpr , CoreExpr -> CoreExpr)
type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr)
@@ -1711,8 +1718,7 @@ unbox_one_result opts res_bndr
move_transit_vars :: [Id] -> (CoreExpr -> CoreExpr -> CoreExpr, CoreExpr)
move_transit_vars vars
| [var] <- vars
- , let var_ty = idType var
- , isUnliftedType var_ty || exprIsHNF (Var var)
+ , varIsHNF var -- NB: True of variables of unlifted type
-- See Note [No unboxed tuple for single, unlifted transit var]
-- * Wrapper: `unbox scrut alt = (case <scrut> of a -> <alt>)`
-- * Worker: `tup = a`
@@ -1769,7 +1775,7 @@ To achieve said transformation, 'mkWWcpr_entry'
what belongs in the case scrutinee of the unpacker through the communicated
Id `r`: The unpacking expression will be free in that variable.
(This is a similar contract as that of 'mkWWstr_one' for strict args.)
- 3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables
+ 3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables
that have to be transferred from the worker to the wrapper, where the
constructed result can be rebuilt, `a` and `b` above. Part (3) is
responsible for tupling them up in the worker and taking the tuple apart
@@ -1816,7 +1822,7 @@ return unboxed instead of in an unboxed singleton tuple:
We want `$wh :: Int# -> [Int]`.
We'd get `$wh :: Int# -> (# [Int] #)`.
-By considering vars as unlifted that satisfy 'exprIsHNF', we catch (3).
+By considering vars as unlifted that satisfy 'varIsHNF', we catch (3).
Why not check for 'exprOkForSpeculation'? Quite perplexingly, evaluated vars
are not ok-for-spec, see Note [exprOkForSpeculation and evaluated variables].
For (1) and (2) we would have to look at the term. WW only looks at the
=====================================
compiler/GHC/Core/Ppr.hs
=====================================
@@ -637,6 +637,7 @@ instance Outputable IdInfo where
[ (has_prag, text "InlPrag=" <> pprInlineDebug prag_info)
, (has_occ, text "Occ=" <> ppr occ_info)
, (has_dmd, text "Dmd=" <> ppr dmd_info)
+ , (has_cpr, text "Cpr=" <> ppr cpr_info)
, (has_lbv , text "OS=" <> ppr lbv_info)
, (has_arity, text "Arity=" <> int arity)
, (has_called_arity, text "CallArity=" <> int called_arity)
@@ -658,6 +659,9 @@ instance Outputable IdInfo where
lbv_info = oneShotInfo info
has_lbv = not (hasNoOneShotInfo lbv_info)
+ cpr_info = cprSigInfo info
+ has_cpr = not $ isTopCprSig cpr_info
+
arity = arityInfo info
has_arity = arity /= 0
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -13,7 +13,7 @@ module GHC.Core.Utils (
mkTick, mkTicks, mkTickNoHNF, tickHNFArgs,
mkTickCpe,
bindNonRec, needsCaseBinding, needsCaseBindingL,
- mkAltExpr, mkDefaultCase, mkSingleAltCase,
+ mkAltExpr, mkDefaultCase, mkSingleAltCase, mkCaseFromLet,
-- * Taking expressions apart
findDefault, addDefault, findAlt, isDefaultAlt,
@@ -29,7 +29,7 @@ module GHC.Core.Utils (
exprIsTrivial, getIdFromTrivialExpr, getIdFromTrivialExpr_maybe,
trivial_expr_fold,
exprIsDupable, exprIsCheap, exprIsExpandable, exprIsCheapX, CheapAppFun,
- exprIsHNF, exprOkForSpeculation, exprOkToDiscard, exprOkForSpecEval,
+ exprIsHNF, varIsHNF, exprOkForSpeculation, exprOkToDiscard, exprOkForSpecEval,
exprIsWorkFree, exprIsConLike,
isCheapApp, isExpandableApp, isSaturatedConApp,
exprIsTickedString, exprIsTickedString_maybe,
@@ -756,8 +756,17 @@ bindNonRec bndr rhs body
| needsCaseBinding (idType bndr) rhs = case_bind
| otherwise = let_bind
where
- case_bind = mkDefaultCase rhs bndr body
let_bind = Let (NonRec bndr rhs) body
+ case_bind = mkCaseFromLet bndr rhs body
+
+mkCaseFromLet :: Id -> CoreExpr -> CoreExpr -> CoreExpr
+-- Given x=rhs in body, return
+-- case rhs of x { DEFAULT -> body }
+mkCaseFromLet bndr rhs body
+ = mkDefaultCase rhs (mkCaseBndrFromLetBndr bndr) body
+ -- mkCaseBndrFromLetBndr: bndr may have IdInfo suitable for a
+ -- let-binder; see Note [Core binder IdInfo invariants]
+ -- in GHC.Core
-- | `needsCaseBinding` tests whether we have to use a @case@ rather than @let@
-- binding for this expression as per the invariants of 'CoreExpr': see
@@ -2630,12 +2639,37 @@ it doesn't have the trickiness of the let-can-float invariant to worry about.
exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
exprIsHNF = exprIsHNFlike isDataConWorkId isEvaldUnfolding True
+-- | @varIsHNF v@ is the same as @exprIsHNF (Var v)@, but avoids building
+-- the @Var@ only to take it apart again
+varIsHNF :: Var -> Bool
+varIsHNF = varIsHNFlike isDataConWorkId isEvaldUnfolding
+
-- | Similar to 'exprIsHNF' but includes CONLIKE functions as well as
-- data constructors. Conlike arguments are considered interesting by the
-- inliner.
exprIsConLike :: CoreExpr -> Bool -- True => lambda, conlike, PAP
exprIsConLike = exprIsHNFlike isConLikeId isConLikeUnfolding False
+varIsHNFlike :: (Var -> Bool) -> (Unfolding -> Bool) -> Var -> Bool
+-- The (Var v) case of exprIsHNFlike
+{-# INLINE varIsHNFlike #-}
+varIsHNFlike is_con is_con_unf v
+ = idArity v > 0 || is_con v
+ -- A PAP is a value, as is a nullary constructor, so that [] and ()
+ -- are values, for example; and (e.g.) primops that don't have unfoldings.
+ -- This is (id_app_is_value v []) in exprIsHNFlike
+
+ || is_con_unf (idUnfolding v)
+ -- Check the thing's unfolding; it might be bound to a value
+ -- or to a guaranteed-evaluated variable (isEvaldUnfolding)
+ -- Contrast with Note [exprOkForSpeculation and evaluated variables]
+ -- We don't look through loop breakers here, which is a bit conservative
+ -- but otherwise I worry that if an Id's unfolding is just itself,
+ -- we could get an infinite loop
+
+ || definitelyUnliftedType (idType v)
+ -- Unlifted binders are always evaluated (#20140)
+
-- | Returns true for values or value-like expressions. These are lambdas,
-- constructors / CONLIKE functions (as determined by the function argument)
-- or PAPs.
@@ -2649,20 +2683,8 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
= -- pprTraceWith "hnf" (\r -> ppr r <+> ppr e) $
is_hnf_like e
where
- is_hnf_like (Var v) -- NB: There are no value args at this point
- = id_app_is_value v [] -- Catches nullary constructors,
- -- so that [] and () are values, for example
- -- and (e.g.) primops that don't have unfoldings
- || is_con_unf (idUnfolding v)
- -- Check the thing's unfolding; it might be bound to a value
- -- or to a guaranteed-evaluated variable (isEvaldUnfolding)
- -- Contrast with Note [exprOkForSpeculation and evaluated variables]
- -- We don't look through loop breakers here, which is a bit conservative
- -- but otherwise I worry that if an Id's unfolding is just itself,
- -- we could get an infinite loop
-
- || definitelyUnliftedType (idType v)
- -- Unlifted binders are always evaluated (#20140)
+ is_hnf_like (Var v) = varIsHNFlike is_con is_con_unf v
+ -- NB: There are no value args at this point
is_hnf_like (Lit lit)
| isLitRubbish lit = rubbish_lit_result
@@ -2697,6 +2719,8 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
app_is_value _ _ = False
id_app_is_value id val_args
+ | null val_args -- We can get here via (f @Int), say
+ = varIsHNFlike is_con is_con_unf id
| Just dc <- isDataConWorkId_maybe id
, isUnaryClassDataCon dc
= all is_hnf_like val_args -- Look through unary class data cons
=====================================
compiler/GHC/CoreToStg/Prep.hs
=====================================
@@ -2366,7 +2366,7 @@ wrapBinds floats body
-- See Note [BindInfo and FloatInfo] on whether we pick Case or Let here
mk_bind f@(Float bind CaseBound _) body
| NonRec bndr rhs <- bind
- = mkDefaultCase rhs bndr body
+ = mkCaseFromLet bndr rhs body
| otherwise
= pprPanic "wrapBinds" (ppr f)
mk_bind (Float bind _ _) body
=====================================
compiler/GHC/HsToCore/Match.hs
=====================================
@@ -324,7 +324,7 @@ matchBangs :: NonEmpty MatchId -> Type -> NonEmpty EquationInfoNE -> DsM (MatchR
matchBangs (var :| vars) ty eqns
= do { match_result <- match (var:vars) ty $ NE.toList $
decomposeFirstPat getBangPat <$> eqns
- ; return (mkEvalMatchResult (matchId var) ty match_result) }
+ ; return (mkEvalMatchResult (matchId var) match_result) }
matchCoercion :: NonEmpty MatchId -> Type -> NonEmpty EquationInfoNE -> DsM (MatchResult CoreExpr)
-- Match against a coercion pattern (CoPat)
=====================================
compiler/GHC/HsToCore/Utils.hs
=====================================
@@ -131,19 +131,20 @@ selectMatchVars ps = mapM (uncurry selectMatchVar) ps
selectMatchVar :: Mult -> Pat GhcTc -> DsM Id
-- Postcondition: the returned Id has an Internal Name
-selectMatchVar w (BangPat _ pat) = selectMatchVar w (unLoc pat)
-selectMatchVar w (LazyPat _ pat) = selectMatchVar w (unLoc pat)
-selectMatchVar w (ParPat _ pat) = selectMatchVar w (unLoc pat)
-selectMatchVar _w (VarPat _ var) = return (localiseId (unLoc var))
- -- Note [Localise pattern binders]
- --
- -- Remark: when the pattern is a variable (or
- -- an @-pattern), then w is the same as the
- -- multiplicity stored within the variable
- -- itself. It's easier to pull it from the
- -- variable, so we ignore the multiplicity.
-selectMatchVar _w (AsPat _ var _) = assert (isManyTy _w ) (return (localiseId (unLoc var)))
-selectMatchVar w other_pat = newSysLocalDs (Scaled w (hsPatType other_pat))
+selectMatchVar w (BangPat _ pat) = selectMatchVar w (unLoc pat)
+selectMatchVar w (LazyPat _ pat) = selectMatchVar w (unLoc pat)
+selectMatchVar w (ParPat _ pat) = selectMatchVar w (unLoc pat)
+
+selectMatchVar _w (VarPat _ var) = return (mkLamBndrFromLetBndr (unLoc var))
+selectMatchVar _w (AsPat _ var _) = assert (isManyTy _w ) $
+ return (mkLamBndrFromLetBndr (unLoc var))
+ -- mkLamBndrFromLetBndr: see Note [Localise pattern binders]
+ --
+ -- Remark: when the pattern is a variable (or an @-pattern), then w is
+ -- the same as the multiplicity stored within the variable
+ -- itself. It's easier to pull it from the variable, so we ignore _w here
+
+selectMatchVar w other_pat = newSysLocalDs (Scaled w (hsPatType other_pat))
{- Note [Localise pattern binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -167,9 +168,15 @@ It's quite rare for this to actually *happen* -- the only case I know
of is tc003 compiled with the 'hpc' way -- but that only makes it
all the more annoying.
-To avoid this, we craftily call 'localiseId' in the desugarer, which
-simply turns the External Name for the Id into an Internal one, but
-doesn't change the unique. So the desugarer produces this:
+Very similarly, we might have
+ {-# NOINLINE a #-}
+ [Just a] = e
+and we don't allow a NOINLINE on case-alternative binders.
+
+To avoid these problems, we craftily call `mkLamBndrFromLetBndr` in the
+desugarer, which simply turns the External Name for the Id into an Internal one,
+and expunges bad IdInfo, but doesn't change the unique. So the desugarer produces
+this:
M.a{r8} = case e of (v:_) ->
case v of Just a{r8} -> M.a{r8}
The unique is still 'r8', but the binding site in the pattern
@@ -265,8 +272,14 @@ bindMatchId new mid body
-- Used to force variables when desugaring strict binders. It's crucial that the
-- variable is shadowed by the case binder. See Wrinkle 1 in
-- Note [Desugar Strict binds] in GHC.HsToCore.Binds.
+--
seqVar :: Var -> CoreExpr -> CoreExpr
-seqVar var body = mkDefaultCase (Var var) var body
+seqVar var body = mkCaseFromLet var (Var var) body
+ -- mkCaseFromLet: the case binder has the same Name (and hence Unique), type
+ -- and multiplicity as `var`, but not its IdInfo: `var` may have, say, a
+ -- NOINLINE pragma, but a case binder must not; see Note [Core binder IdInfo
+ -- invariants] in GHC.Core, and #27965. E.g. `res1` in
+ -- GHC.Internal.Control.Monad.ST.Lazy.Imp has a NOINLINE pragma.
mkCoLetMatchResult :: HasDebugCallStack => CoreBind -> MatchResult CoreExpr -> MatchResult CoreExpr
mkCoLetMatchResult bind = fmap (mkCoreLet bind)
@@ -276,9 +289,8 @@ mkCoLetMatchResult bind = fmap (mkCoreLet bind)
mkViewMatchResult :: HasDebugCallStack => Id -> CoreExpr -> MatchResult CoreExpr -> MatchResult CoreExpr
mkViewMatchResult var' viewExpr = fmap $ mkCoreLet $ NonRec var' viewExpr
-mkEvalMatchResult :: Id -> Type -> MatchResult CoreExpr -> MatchResult CoreExpr
-mkEvalMatchResult var ty = fmap $ \e ->
- Case (Var var) var ty [Alt DEFAULT [] e]
+mkEvalMatchResult :: Id -> MatchResult CoreExpr -> MatchResult CoreExpr
+mkEvalMatchResult var = fmap $ \e -> mkCaseFromLet var (Var var) e
mkGuardedMatchResult :: CoreExpr -> MatchResult CoreExpr -> MatchResult CoreExpr
mkGuardedMatchResult pred_expr mr = MR_Fallible $ \fail -> do
@@ -684,7 +696,7 @@ mkSelectorBinds ticks pat ctx val_expr
binders = collectPatBinders CollNoDictBinders pat'
ticks' = ticks ++ repeat []
- local_binders = map localiseId binders -- See Note [Localise pattern binders]
+ local_binders = map mkLamBndrFromLetBndr binders -- See Note [Localise pattern binders]
strip_bangs :: LPat (GhcPass p) -> LPat (GhcPass p)
-- Remove outermost bangs and parens
=====================================
compiler/GHC/Types/Cpr.hs
=====================================
@@ -8,6 +8,7 @@
module GHC.Types.Cpr (
Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr,
CprType (..), topCprType, botCprType, flatConCprType,
+ cprTypeArity, cprTypeCpr,
lubCprType, applyCprTy, abstractCprTy, trimCprTy,
UnpackConFieldsResult (..), unpackConFieldsCpr,
CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig,
@@ -106,6 +107,12 @@ data CprType
-- 'ct_arty' arguments
}
+cprTypeArity :: CprType -> Arity
+cprTypeArity = ct_arty
+
+cprTypeCpr :: CprType -> Cpr
+cprTypeCpr = ct_cpr
+
instance Eq CprType where
a == b = ct_cpr a == ct_cpr b
&& (ct_arty a == ct_arty b || ct_cpr a == topCpr)
@@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr
-- | The arity of the wrapped 'CprType' is the arity at which it is safe
-- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand"
-newtype CprSig = CprSig { getCprSig :: CprType }
+newtype CprSig = CprSig { cprSigType :: CprType }
deriving (Eq, Binary)
-- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig'
=====================================
compiler/GHC/Types/Id.hs
=====================================
@@ -94,6 +94,7 @@ module GHC.Types.Id (
idArity,
idCallArity, idFunRepArity,
idSpecialisation, idCoreRules, idHasRules,
+ lamBndrInfoOK,
idCafInfo, idLFInfo_maybe,
idOneShotInfo,
idOccInfo,
@@ -103,6 +104,7 @@ module GHC.Types.Id (
-- ** Writing 'IdInfo' fields
setIdUnfolding, zapIdUnfolding, setCaseBndrEvald,
+ mkCaseBndrFromLetBndr, mkLamBndrFromLetBndr,
setIdArity,
setIdCallArity,
@@ -881,10 +883,33 @@ setCaseBndrEvald :: StrictnessMark -> Id -> Id
-- itself, and any pattern-bound variables that are argument of a
-- strict constructor. It just marks the variable as already-evaluated,
-- so that (for example) a subsequent 'seq' can be dropped
+-- See Note [Evaluated-ness on case binders] in GHC.Core
setCaseBndrEvald str id
| isMarkedStrict str = id `setIdUnfolding` evaldUnfolding
| otherwise = id
+-- | Just like `mkLamBndrFromLetBndr` but in addition
+-- record that it is evaluated.
+-- See Note [Core binder IdInfo invariants] in GHC.Core
+mkCaseBndrFromLetBndr :: Id -> Id
+mkCaseBndrFromLetBndr id
+ = mkLamBndrFromLetBndr id `setIdUnfolding` evaldUnfolding
+
+-- | Make a lambda binder from a binder that might have been let-bound, e.g.
+-- let x = rhs in body ==> (\x. body) rhs
+-- The let-binder may have IdInfo (an unfolding, an inline pragma, RULES)
+-- that a case binder must not have, so we keep its Name, type, multiplicity
+-- and IdDetails, plus OccInfo and DemandInfo, but reset its other IdInfo.
+-- See Note [Core binder IdInfo invariants] in GHC.Core
+mkLamBndrFromLetBndr :: Id -> Id
+mkLamBndrFromLetBndr id
+ = localiseId id `setIdInfo` zapped_info
+ where
+ info = idInfo id
+ zapped_info = vanillaIdInfo `setOccInfo` occInfo info
+ `setDemandInfo` (demandInfo info)
+
+
-- | Similar to trimUnfolding, but also removes evaldness info.
zapIdUnfolding :: Id -> Id
zapIdUnfolding v
@@ -905,6 +930,32 @@ idCoreRules id = ruleInfoRules (idSpecialisation id)
idHasRules :: Id -> Bool
idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
+-- | True <=> the Id has only the IdInfo permitted on a lambda, case, or
+-- case-alternative binder. See the table in Note [Core binder IdInfo invariants]
+-- in GHC.Core; Core Lint checks this invariant.
+--
+-- We allow occurrence info, demand info, and one-shot info (which the table
+-- permits only on lambda binders, but a case binder may be about to become one).
+-- We also allow an `OtherCon []` unfolding; lambda binders must have no unfolding
+-- at all, but Lint checks that separately.
+lamBndrInfoOK :: Id -> Bool
+lamBndrInfoOK id
+ = isDefaultInlinePragma (inlinePragInfo info)
+ && isNopSig (dmdSigInfo info)
+ && isTopCprSig (cprSigInfo info)
+ && mayHaveCafRefs (cafInfo info)
+ && arityInfo info == unknownArity
+ && callArityInfo info == unknownArity
+ && isEmptyRuleInfo (ruleInfo info)
+ && unf_ok (realUnfoldingInfo info)
+ where
+ info = idInfo id
+
+ -- See Note [Evaluated-ness on case binders] in GHC.Core
+ unf_ok NoUnfolding = True
+ unf_ok (OtherCon []) = True
+ unf_ok _ = False
+
setIdSpecialisation :: Id -> RuleInfo -> Id
setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
=====================================
compiler/GHC/Utils/Monad.hs
=====================================
@@ -16,7 +16,7 @@ module GHC.Utils.Monad
, mapAccumLM
, mapSndM
, concatMapM
- , mapMaybeM
+ , mapMaybeM, orElseM
, anyM, allM, orM
, foldlM, foldlM_, foldrM, foldMapM
, whenM, unlessM
@@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = do { cond <- condM
; unless cond acc }
+-- | Monadic version of @orElse@
+infixr 4 `orElseM`
+orElseM :: Monad m => m (Maybe a) -> m a -> m a
+orElseM ma def = do { mb_r <- ma
+ ; case mb_r of
+ Just x -> return x
+ Nothing -> def }
+
-- | Like 'filterM', only it reverses the sense of the test.
filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterOutM p =
=====================================
testsuite/tests/simplCore/should_compile/T15445.stderr
=====================================
@@ -4,6 +4,7 @@ Rule fired: Int# -> Integer -> Int# (GHC.Internal.Bignum.Integer)
Rule fired: USPEC plusTwoRec @Int (T15445a)
Rule fired: USPEC $fShowList @Int (GHC.Internal.Show)
Rule fired: Class op >> (BUILTIN)
+Rule fired: Class op show (BUILTIN)
Rule fired: USPEC plusTwoRec @Int (T15445a)
Rule fired: Class op enumFromTo (BUILTIN)
Rule fired: eftInt (GHC.Internal.Enum)
@@ -11,7 +12,6 @@ Rule fired: Class op show (BUILTIN)
Rule fired: USPEC plusTwoRec @Int (T15445a)
Rule fired: Class op enumFromTo (BUILTIN)
Rule fired: eftInt (GHC.Internal.Enum)
-Rule fired: Class op show (BUILTIN)
Rule fired: eftIntList (GHC.Internal.Enum)
Rule fired: ># (BUILTIN)
Rule fired: ==# (BUILTIN)
=====================================
testsuite/tests/simplCore/should_compile/T27962.hs
=====================================
@@ -0,0 +1,16 @@
+{-# LANGUAGE MagicHash #-}
+
+module T27962 where
+
+import GHC.Exts
+
+newtype N = MkN Int
+
+-- After inlining myRun, we get (runRW# @LiftedRep @Int |> co) (\_ -> ...)
+-- and the simplifier pushes co into the argument of runRW#.
+-- #27962: the simplifier dropped that cast, yielding ill-typed Core
+myRun :: (State# RealWorld -> N) -> N
+myRun = coerce (runRW# :: (State# RealWorld -> Int) -> Int)
+{-# INLINE myRun #-}
+
+foo x = myRun (\_ -> MkN (x+1))
=====================================
testsuite/tests/simplCore/should_compile/T27963.hs
=====================================
@@ -0,0 +1,23 @@
+{-# OPTIONS_GHC -Wno-inline-rule-shadowing #-}
+
+module T27963 where
+
+-- This test is pretty delicate because it relies on a function
+-- that has BOTH a rule AND an INLINE pragma
+--
+-- See #27963 for some discussion
+--
+-- Still, it should (just) work
+
+import GHC.Exts
+
+newtype N = MkN Int
+
+f x = x
+{-# INLINE f #-}
+{-# RULES "f/42" forall x. f x = 42::Int #-}
+
+-- The rule "f/42" should fire in both h1 and h2
+h1,h2 :: N -> Int
+h1 n = f (coerce n) + 0
+h2 n = (coerce f) n + 0 -- #27963: the rule did not fire here
=====================================
testsuite/tests/simplCore/should_compile/T27963.stderr
=====================================
@@ -0,0 +1,2 @@
+Rule fired: f/42 (T27963)
+Rule fired: f/42 (T27963)
=====================================
testsuite/tests/simplCore/should_compile/T27965.hs
=====================================
@@ -0,0 +1,9 @@
+-- Lint checks that we don't produce a lambda-binder
+-- with a NOINLINE pragma on it (#27965)
+
+module T27965 where
+
+h fm s = let {-# NOINLINE res1 #-}
+ !res1 = fm s
+ !(f, s') = res1
+ in (f+1::Int, s')
=====================================
testsuite/tests/simplCore/should_compile/T27965a.hs
=====================================
@@ -0,0 +1,7 @@
+{-# LANGUAGE MonoLocalBinds #-}
+module M where
+
+f :: (Int, Int) -> Int
+f p = let {-# NOINLINE a #-}
+ (a, b) = p
+ in a + b
=====================================
testsuite/tests/simplCore/should_compile/T28158.hs
=====================================
@@ -0,0 +1,18 @@
+module T28158 where
+
+-- Here we miss CPR on y
+-- It's a bit of an obscure example, but still; see #28158
+f :: a -> a -> a -> [Int] -> [Int]
+f a b c xs = let y = case xs of
+ [0] -> Just a
+ [1] -> Just b
+ _ -> Just c
+ in h y (case y of
+ Just z -> reverse (reverse (reverse (
+ reverse (reverse (reverse (
+ reverse (reverse xs)))))))
+ Nothing -> xs++xs)
+
+h :: Maybe a -> b -> b
+h (Just y) e = h Nothing e
+h Nothing e = e
=====================================
testsuite/tests/simplCore/should_compile/T28158.stderr
=====================================
@@ -0,0 +1,47 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 72, types: 76, coercions: 0, joins: 1/1}
+
+Rec {
+h = \ @a @b ds e ->
+ case ds of {
+ Nothing -> e;
+ Just y -> h Nothing e
+ }
+end Rec }
+
+f = \ @a a1 b c xs ->
+ join {
+ $j ww
+ = h (Just ww)
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1 (reverse1 (reverse1 (reverse xs) []) []) []) [])
+ [])
+ [])
+ []) } in
+ case xs of {
+ [] -> jump $j c;
+ : ds ds1 ->
+ case ds of { I# ds2 ->
+ case ds2 of {
+ __DEFAULT -> jump $j c;
+ 0# ->
+ case ds1 of {
+ [] -> jump $j a1;
+ : ipv ipv1 -> jump $j c
+ };
+ 1# ->
+ case ds1 of {
+ [] -> jump $j b;
+ : ipv ipv1 -> jump $j c
+ }
+ }
+ }
+ }
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,9 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+test('T27962', normal, compile, [''])
+test('T27962a', [extra_files(['T27962.hs'])], multimod_compile, ['T27962', '-v0 -O'])
+test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
+test('T27965', normal, compile, ['-O'])
+test('T27965a', normal, compile, ['-O'])
+test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/70923afbf36c0bb025f34a2c684c98…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/70923afbf36c0bb025f34a2c684c98…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0