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/38e61025830a37d55972a4017db2d037... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/38e61025830a37d55972a4017db2d037... 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
participants (1)
-
Simon Jakobi (@sjakobi)