[Git][ghc/ghc][wip/jeltsch/haddock-without-pit-use] Make Haddock avoid the PIT
by Wolfgang Jeltsch (@jeltsch) 16 Nov '26
by Wolfgang Jeltsch (@jeltsch) 16 Nov '26
16 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/haddock-without-pit-use at Glasgow Haskell Compiler / GHC
Commits:
eb4871bd by Wolfgang Jeltsch at 2026-11-16T23:35:58+02:00
Make Haddock avoid the PIT
To this end, Haddock has been using `loadSysInterface` to fetch module
interfaces. The `loadSysInterface` operation is very complex, containing
many bits that do not seem to be needed by Haddock. In particular,
storing interface data in and potentially retrieving it from the PIT
seems to be superfluous. This interaction with the PIT limits how much
we can statically shrink the amount of information that is stored in the
PIT. Therefore, we drop the use of `loadSysInterface` and implement the
necessary bits of interface fetching directly in `loadHiFile`, where
`loadSysInterface` used to be invoked.
- - - - -
1 changed file:
- utils/haddock/haddock-api/src/Haddock/Interface.hs
Changes:
=====================================
utils/haddock/haddock-api/src/Haddock/Interface.hs
=====================================
@@ -56,21 +56,25 @@ import GHC.Driver.Monad
import GHC.Driver.Make
import GHC.Driver.Main
import GHC.Core.InstEnv
+import GHC.Core.FamInstEnv
import qualified GHC.Driver.DynFlags as DynFlags
import qualified GHC.Utils.Outputable as Outputable
import GHC.Driver.Session hiding (verbosity)
import GHC.Driver.Phases
import GHC.Driver.Pipeline (compileFile)
import GHC.HsToCore.Docs (getMainDeclBinder)
-import GHC.Iface.Load (loadSysInterface)
-import GHC.IfaceToCore (tcIfaceInst, tcIfaceFamInst)
-import GHC.Tc.Utils.Monad (initIfaceLoad, initIfaceLcl)
+import GHC.Iface.Load (findAndReadIface)
+import GHC.IfaceToCore (tcIfaceDecls, tcIfaceInst, tcIfaceFamInst)
+import GHC.Tc.Utils.Monad (goptM, updateEps_, initIfaceLoad, initIfaceLcl)
import GHC.Tc.Utils.Env (lookupGlobal_maybe)
import GHC.Types.Error (mkUnknownDiagnostic)
import GHC.Types.Name.Occurrence (emptyOccEnv)
+import GHC.Types.Name.Env (extendNameEnvList)
import GHC.Unit.Finder (findImportedModule, runFinderM, ModuleLookupScope(..), FindResult(Found))
import GHC.Unit.Home.ModInfo
import GHC.Unit.Home.PackageTable
+import GHC.Unit.External (eps_PTE, eps_inst_env, eps_fam_inst_env)
+import GHC.Unit.Module (getModuleInstantiation)
import GHC.Unit.Module.Graph (ModuleGraphNode (..), ModuleNodeInfo(..))
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface (mi_semantic_module, mi_boot)
@@ -254,19 +258,29 @@ dropErr :: MaybeErr e a -> Maybe a
dropErr (Succeeded a) = Just a
dropErr (Failed _) = Nothing
-loadHiFile :: HscEnv -> Outputable.SDoc -> Module -> IO (ModIface, ([ClsInst], [FamInst]))
-loadHiFile hsc_env doc theModule = initIfaceLoad hsc_env $ do
-
- mod_iface <- loadSysInterface doc theModule
-
- insts <- initIfaceLcl (mi_semantic_module mod_iface) doc (mi_boot mod_iface) $ do
-
- new_eps_insts <- mapM tcIfaceInst (mi_insts mod_iface)
- new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts mod_iface)
-
- pure (new_eps_insts, new_eps_fam_insts)
-
- pure (mod_iface, insts)
+loadHiFile :: Verbosity -> HscEnv -> Outputable.SDoc -> Module -> IO (ModIface, ([ClsInst], [FamInst]))
+loadHiFile verbosity hsc_env doc requested = initIfaceLoad hsc_env $ do
+ let installed = fst (getModuleInstantiation requested)
+ iface_fetch_result <- liftIO $ findAndReadIface hsc_env doc installed requested NotBoot
+ case iface_fetch_result of
+ Failed _ -> do
+ out verbosity normal $ "Loading interface for " ++
+ moduleNameString (moduleName requested) ++
+ " failed"
+ liftIO exitFailure
+ Succeeded (mod_iface, _) -> do
+ all_insts <- initIfaceLcl (mi_semantic_module mod_iface) doc (mi_boot mod_iface) $ do
+ ignore_iface_pragmas <- goptM Opt_IgnoreInterfacePragmas
+ decls <- tcIfaceDecls ignore_iface_pragmas (mi_decls mod_iface)
+ insts <- mapM tcIfaceInst (mi_insts mod_iface)
+ fam_insts <- mapM tcIfaceFamInst (mi_fam_insts mod_iface)
+ updateEps_ $ \ eps -> eps {
+ eps_PTE = extendNameEnvList (eps_PTE eps) decls,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps) insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps) fam_insts
+ }
+ pure (insts, fam_insts)
+ pure (mod_iface, all_insts)
processModule :: Verbosity -> ModSummary -> [Flag] -> IfaceMap -> InstIfaceMap -> WarningMap -> Ghc (Maybe Interface)
processModule verbosity modSummary flags ifaceMap instIfaceMap warningMap = do
@@ -279,7 +293,7 @@ processModule verbosity modSummary flags ifaceMap instIfaceMap warningMap = do
unit_state = hsc_units hsc_env
(mod_iface, insts) <- if Flag_NoCompilation `elem` flags
- then liftIO $ loadHiFile hsc_env doc $ ms_mod modSummary
+ then liftIO $ loadHiFile verbosity hsc_env doc $ ms_mod modSummary
else do
hmi <- liftIO $ lookupHpt (hsc_HPT hsc_env) (moduleName $ ms_mod modSummary) >>= \case
Nothing -> error "processModule: All modules should be loaded into the HPT by this point"
@@ -376,7 +390,7 @@ createOneShotIface verbosity flags instIfaceMap moduleNameStr = do
let oneShotUnit = stringToUnit (unitIdString (homeUnitId_ dflags))
- (iface, insts) <- liftIO $ loadHiFile hsc_env doc $ mkModule oneShotUnit moduleNm
+ (iface, insts) <- liftIO $ loadHiFile verbosity hsc_env doc $ mkModule oneShotUnit moduleNm
-- Update the DynFlags with the extensions from the source file (as stored in the interface file)
-- This is instead of ms_hspp_opts from ModSummary, which is not available in one-shot mode.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/eb4871bdd107776659a070f781be9d9…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/eb4871bdd107776659a070f781be9d9…
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/marge_bot_batch_merge_job] 7 commits: CoreMap: look up a non-recursive let with the key order of the store
by Marge Bot (@marge-bot) 16 Nov '26
by Marge Bot (@marge-bot) 16 Nov '26
16 Nov '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
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.
- - - - -
e53383b7 by fendor at 2026-11-16T16:35:03-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
- - - - -
0843ea56 by Sylvain Henry at 2026-11-16T16:35:08-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>
- - - - -
355d9474 by mangoiv at 2026-11-16T16:35:09-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
- - - - -
14d34c7c by David Eichmann at 2026-11-16T16:35:10-05:00
test driver refactor: replace `.format(**locals())` with f-string
- - - - -
35 changed files:
- .gitlab-ci.yml
- + changelog.d/27892
- + changelog.d/T28123
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-streaming-output
- 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/Driver/DynFlags.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- docs/users_guide/separate_compilation.rst
- testsuite/driver/my_typing.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/tests/driver/mkdepend/all.T
- testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-json → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-makefile → 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/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- + 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/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3aebf0de64f8bea14942934be9b86a…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3aebf0de64f8bea14942934be9b86a…
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
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
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.
- - - - -
5 changed files:
- + changelog.d/T28123
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/TyCo/Make.hs
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
Changes:
=====================================
changelog.d/T28123
=====================================
@@ -0,0 +1,8 @@
+section: compiler
+issues: #28123
+mrs: !16992
+synopsis:
+ Fix a forall-visibility bug in eta expansion
+description:
+ This bug made GHC generate a coercion on a forall-type whose visibility
+ was back-to-front, leading to a Core Lint error.
=====================================
compiler/GHC/Core/Opt/Arity.hs
=====================================
@@ -2063,7 +2063,10 @@ eta_expand in_scope one_shots orig_expr
| otherwise = go (in_scope `extendInScopeSet` v) oss1 (v:vs) body
go in_scope oss rev_vs expr
- = -- pprTrace "ee" (vcat [ppr in_scope', ppr top_bndrs, ppr eis]) $
+ = -- pprTrace "ee" (
+ -- vcat [ text "top_bndrs:" <+> ppr top_bndrs
+ -- , text "top-eis:" <+> ppr top_eis
+ -- , text "eis:" <+> ppr eis]) $
retick $
etaInfoAbs top_eis $
etaInfoApp in_scope' sexpr eis
@@ -2282,6 +2285,11 @@ etaInfoAbs (EI bs mco) expr = (mkLams bs expr) `mkCastMCo` mkSymMCo mco
-- Note that this function is entirely unconcerned about cost centres and other
-- semantically-irrelevant source annotations, so call sites must take care to
-- preserve that info. See Note [Eta expansion and SCCs].
+--
+-- If mkEtaWW ty = EI [b1,..,bn] co
+-- then co :: ty ~ (b1_ty -> .. -> bn_ty -> body_ty)
+-- That is, the RHS type has all arrows visible, and is the type
+-- of a core lambda (\b1...\bn. body)
mkEtaWW
:: [OneShotInfo]
-- ^ How many value arguments to eta-expand
@@ -2370,7 +2378,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco
| otherwise -> mk_fco (mkRepReflCo ty)
MCo co -> mk_fco co
where
- mk_fco co = MCo (mkForAllCo tcv coreTyLamForAllTyFlag vis MRefl co)
+ mk_fco co = MCo (mkForAllCo tcv vis coreTyLamForAllTyFlag MRefl co)
-- coreTyLamForAllTyFlag: See Note [The EtaInfo mechanism], particularly
-- the (EtaInfo Invariant). (sym co) wraps a lambda that always has
-- a ForAllTyFlag of coreTyLamForAllTyFlag; see Note [Required foralls in Core]
=====================================
compiler/GHC/Core/TyCo/Make.hs
=====================================
@@ -994,9 +994,14 @@ mkSymCo :: Coercion -> Coercion
mkSymCo co | isReflCo co = co
mkSymCo (SymCo co) = co
mkSymCo (SubCo (SymCo co)) = SubCo co
-mkSymCo co@(ForAllCo { fco_kind = kco, fco_body = body_co })
- | isReflMCo kco = co { fco_body = mkSymCo body_co }
-mkSymCo co = SymCo co
+mkSymCo (ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR
+ , fco_kind = kco, fco_body = body_co })
+ | isReflMCo kco = ForAllCo { fco_tcv = tcv -- Binder can stay unchanged
+ , fco_kind = kco -- since kco=Refl
+ , fco_visL = visR -- Swap visibilities!
+ , fco_visR = visL -- See #28123, #27557
+ , fco_body = mkSymCo body_co } -- Swap body
+mkSymCo co = SymCo co
-- | mkTransCo creates a new 'Coercion' by composing the two
-- given 'Coercion's transitively: (co1 ; co2)
=====================================
testsuite/tests/vdq-rta/should_compile/T28123.hs
=====================================
@@ -0,0 +1,26 @@
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE RequiredTypeArguments #-}
+module T28123 where
+import GHC.TypeNats
+import Data.Kind
+
+f1 :: Int -> forall (n :: Natural) -> Int -> Int
+f1 x n y = x
+{-# INLINE f1 #-}
+
+f2 :: forall a . Int -> forall (b :: Type) -> a -> a
+f2 x t y = y
+{-# INLINE f2 #-}
+
+f3 :: forall a . forall (b :: Type) -> a -> a
+f3 t = id
+{-# INLINE f3 #-}
+
+f4 :: forall a . forall (b :: Type) -> a -> a
+f4 t y = y
+{-# INLINE f4 #-}
+
+f5 :: Int -> forall (n :: Natural) -> KnownNat n => Int
+f5 x _ = x
+{-# INLINE f5 #-}
+
=====================================
testsuite/tests/vdq-rta/should_compile/all.T
=====================================
@@ -46,3 +46,4 @@ test('T27583c', normal, compile, [''])
test('T27583d', normal, compile, [''])
test('T27583e', normal, compile, [''])
test('T27583g', normal, compile, [''])
+test('T28123', normal, compile, [''])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fa6b8c9e44aec8c89b79a68ccd9e2e4…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fa6b8c9e44aec8c89b79a68ccd9e2e4…
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][master] 2 commits: CoreMap: look up a non-recursive let with the key order of the store
by Marge Bot (@marge-bot) 16 Nov '26
by Marge Bot (@marge-bot) 16 Nov '26
16 Nov '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
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>
- - - - -
11 changed files:
- + changelog.d/27892
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- + 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
Changes:
=====================================
changelog.d/27892
=====================================
@@ -0,0 +1,12 @@
+section: compiler
+synopsis: Fix lookups of non-recursive lets in CoreMap
+description:
+ ``CoreMap`` stored a non-recursive ``let`` under one key path and looked
+ it up under a different key path. When a map held two different
+ expressions, each lookup of an expression with a non-recursive ``let``
+ or join point failed. Thus CSE did not share identical bindings, and the
+ pattern-match checker could report spurious non-exhaustive matches for
+ guards or view patterns with equal expressions. ``CoreMap`` and
+ ``eqCoreExpr`` also ignore the multiplicities of binders.
+mrs: !16936
+issues: #27892 #28095
=====================================
compiler/GHC/Core/Map/Expr.hs
=====================================
@@ -28,7 +28,6 @@ import GHC.Core.Map.Type
import GHC.Core
import GHC.Core.Type
import GHC.Types.Tickish
-import GHC.Types.Var
import GHC.Utils.Misc
import GHC.Utils.Outputable
@@ -85,6 +84,14 @@ Note [Binders]
- the binders in an alternative
because they are totally fixed by the context
+ * We ignore the multiplicity of all binders, in the trie and in
+ 'eqDeBruijnExpr'. The multiplicity of a let binder has no meaning: see
+ Note [Multiplicity of let binders] in GHC.Types.Var. Core-to-core
+ passes do not keep the multiplicities of lambda binders correct: see
+ Note [Linting linearity] in GHC.Core.Lint. Thus two terms that differ
+ only in binder multiplicities are equal for CSE and for the
+ pattern-match checker (#28095).
+
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* For a key (Case e b ty (alt:alts)) we don't need to look the return type
@@ -104,6 +111,10 @@ See also Note [Empty case alternatives] in GHC.Core.
-- | @CoreMap a@ is a map from 'CoreExpr' to @a@. If you are a client, this
-- is the type you want.
+--
+-- 'CoreMap' is not linear: it ignores the multiplicities of binders. Two
+-- expressions that differ only in the multiplicities of their lambda or let
+-- binders have the same key. See Note [Binders].
newtype CoreMap a = CoreMap (CoreMapG a)
-- TODO(22292): derive
@@ -163,7 +174,7 @@ eqDeBruijnExpr (D env1 e1) (D env2 e2) = go e1 e2 where
go (Lam b1 e1) (Lam b2 e2)
= eqDeBruijnType (D env1 (varType b1)) (D env2 (varType b2))
- && D env1 (varMultMaybe b1) == D env2 (varMultMaybe b2)
+ -- Ignore multiplicities: see Note [Binders]
&& eqDeBruijnExpr (D (extendCME env1 b1) e1) (D (extendCME env2 b2) e2)
go (Let (NonRec v1 r1) e1) (Let (NonRec v2 r2) e2)
@@ -200,7 +211,8 @@ eqDeBruijnTickish (D env1 t1) (D env2 t2) = go t1 t2 where
&& lext == rext
go l r = l == r
--- Compares for equality, modulo alpha
+-- | Compares for equality, modulo alpha. Like 'CoreMap', it ignores the
+-- multiplicities of binders. See Note [Binders].
eqCoreExpr :: CoreExpr -> CoreExpr -> Bool
eqCoreExpr e1 e2 = eqDeBruijnExpr (deBruijnize e1) (deBruijnize e2)
@@ -374,8 +386,8 @@ xtE (D env (Lam v e)) f m = m { cm_lam = cm_lam m
|> xtG (D (extendCME env v) e)
|>> xtBndr env v f }
xtE (D env (Let (NonRec b r) e)) f m = m { cm_letn = cm_letn m
- |> xtG (D (extendCME env b) e)
- |>> xtG (D env r)
+ |> xtG (D env r)
+ |>> xtG (D (extendCME env b) e)
|>> xtBndr env b f }
xtE (D env (Let (Rec prs) e)) f m = m { cm_letr =
let (bndrs,rhss) = unzip prs
=====================================
compiler/GHC/Core/Map/Type.hs
=====================================
@@ -534,11 +534,6 @@ instance Eq (DeBruijn a) => Eq (DeBruijn [a]) where
D env xs == D env' xs'
_ == _ = False
-instance Eq (DeBruijn a) => Eq (DeBruijn (Maybe a)) where
- D _ Nothing == D _ Nothing = True
- D env (Just x) == D env' (Just x') = D env x == D env' x'
- _ == _ = False
-
--------- Variable binders -------------
-- | A 'BndrMap' is a 'TypeMapG' which allows us to distinguish between
@@ -548,46 +543,18 @@ instance Eq (DeBruijn a) => Eq (DeBruijn (Maybe a)) where
-- we can disambiguate this by matching on the type (or kind, if this
-- a binder in a type) of the binder.
--
--- We also need to do the same for multiplicity! Which, since multiplicities are
--- encoded simply as a 'Type', amounts to have a Trie for a pair of types. Tries
--- of pairs are composition.
-newtype BndrMap a = BndrMap (TypeMapG (MaybeMap TypeMapG a))
-
--- TODO(22292): derive
-instance Functor BndrMap where
- fmap f = \ (BndrMap tm) -> BndrMap (fmap (fmap f) tm)
- {-# INLINE fmap #-}
-
-instance TrieMap BndrMap where
- type Key BndrMap = Var
- emptyTM = BndrMap emptyTM
- lookupTM = lkBndr emptyCME
- alterTM = xtBndr emptyCME
- foldTM = fdBndrMap
- filterTM = ftBndrMap
- mapMaybeTM = mpBndrMap
-
-fdBndrMap :: (a -> b -> b) -> BndrMap a -> b -> b
-fdBndrMap f (BndrMap tm) = foldTM (foldTM f) tm
-
-mpBndrMap :: (a -> Maybe b) -> BndrMap a -> BndrMap b
-mpBndrMap f (BndrMap tm) = BndrMap (fmap (mapMaybeTM f) tm)
+-- The map ignores the multiplicity of the binder.
+-- See Note [Binders] in GHC.Core.Map.Expr.
+type BndrMap = TypeMapG
-- We need to use 'BndrMap' for 'Coercion', 'CoreExpr' AND 'Type', since all
-- of these data types have binding forms.
lkBndr :: CmEnv -> Var -> BndrMap a -> Maybe a
-lkBndr env v (BndrMap tymap) = do
- multmap <- lkG (D env (varType v)) tymap
- lookupTM (D env <$> varMultMaybe v) multmap
-
-
-xtBndr :: forall a . CmEnv -> Var -> XT a -> BndrMap a -> BndrMap a
-xtBndr env v xt (BndrMap tymap) =
- BndrMap (tymap |> xtG (D env (varType v)) |>> (alterTM (D env <$> varMultMaybe v) xt))
+lkBndr env v m = lkG (D env (varType v)) m
-ftBndrMap :: (a -> Bool) -> BndrMap a -> BndrMap a
-ftBndrMap f (BndrMap tm) = BndrMap (fmap (filterTM f) tm)
+xtBndr :: CmEnv -> Var -> XT a -> BndrMap a -> BndrMap a
+xtBndr env v f = xtG (D env (varType v)) f
--------- Variable occurrence -------------
data VarMap a = VM { vm_bvar :: BoundVarMap a -- Bound variable
=====================================
testsuite/tests/pmcheck/should_compile/T27892a.hs
=====================================
@@ -0,0 +1,21 @@
+{-# LANGUAGE ViewPatterns #-}
+module T27892a (f) where
+
+-- The pattern-match checker gives the same representative to the view
+-- expressions of clauses 2 and 3. Thus clause 2 excludes Other, and
+-- clause 3 covers the rest: f is exhaustive. Clause 1 puts an unrelated
+-- key into the CoreMap of the checker. Thus the lookups of clauses 2 and
+-- 3 go through the trie and not through the singleton comparison. The
+-- lambda prevents the simple optimiser from inlining the let. See #27892.
+
+data P = MkP Int Int
+data W = Wrap (Int -> P) | Other
+
+expensive :: Int -> Int
+expensive n = n * n
+{-# NOINLINE expensive #-}
+
+f :: Int -> Int
+f ((\v -> expensive v) -> 0) = 0
+f ((\v -> let x = expensive v in Wrap (\z -> MkP z x)) -> Other) = 1
+f ((\v -> let x = expensive v in Wrap (\z -> MkP z x)) -> Wrap _) = 2
=====================================
testsuite/tests/pmcheck/should_compile/T28095.hs
=====================================
@@ -0,0 +1,21 @@
+{-# LANGUAGE LinearTypes, ViewPatterns #-}
+module T28095 (f) where
+
+-- This test is the same as T27892a, but the let of clause 3 comes from
+-- the beta-reduction of a linear lambda. Thus its binder has multiplicity
+-- One, and the binder of the source let in clause 2 has multiplicity
+-- Many. The multiplicity of a let binder has no meaning (see
+-- Note [Multiplicity of let binders] in GHC.Types.Var). The checker must
+-- give the two expressions the same representative and find f exhaustive.
+
+data P = MkP Int Int
+data W = Wrap (Int %1 -> P) | Other
+
+expensive :: Int -> Int
+expensive n = n * n
+{-# NOINLINE expensive #-}
+
+f :: Int -> Int
+f ((\v -> expensive v) -> 0) = 0
+f ((\v -> let x = expensive v in Wrap (\z -> MkP z x)) -> Other) = 1
+f ((\v -> ((\x -> Wrap (\z -> MkP z x)) :: Int %1 -> W) (expensive v)) -> Wrap _) = 2
=====================================
testsuite/tests/pmcheck/should_compile/all.T
=====================================
@@ -193,3 +193,5 @@ test('T24867', [], compile_fail, [overlapping_incomplete])
test('T27323', normal, compile, ['-Wredundant-bang-patterns'])
test('T27323b', normal, compile, ['-Wredundant-bang-patterns'])
test('T27360', normal, compile, [overlapping_incomplete + '-g3'])
+test('T27892a', normal, compile, [overlapping_incomplete])
+test('T28095', normal, compile, [overlapping_incomplete])
=====================================
testsuite/tests/simplCore/should_compile/T27892.hs
=====================================
@@ -0,0 +1,10 @@
+module T27892 where
+
+-- CSE must find that f and g have identical right-hand sides. The
+-- binding h is between them in the CoreMap, and each body holds a
+-- non-recursive let. See #27892.
+
+f, g, h :: Int -> Int -> Int
+f x y = case (if x > y then x * 3 else y * 5) of m -> m * m + x * y
+h x y = case (if x > y then x * 7 else y * 9) of m -> m * m + x * y
+g x y = case (if x > y then x * 3 else y * 5) of m -> m * m + x * y
=====================================
testsuite/tests/simplCore/should_compile/T27892.stderr
=====================================
@@ -0,0 +1 @@
+f = g
=====================================
testsuite/tests/simplCore/should_compile/T28095a.hs
=====================================
@@ -0,0 +1,14 @@
+{-# LANGUAGE LinearTypes #-}
+module T28095a where
+
+-- CSE must find that f and g have identical right-hand sides. The two
+-- lambdas differ only in the multiplicity of their binders, and CSE
+-- ignores it. See Note [Binders] in GHC.Core.Map.Expr.
+
+data P = MkP Int Int
+
+f :: Int %1 -> Int -> P
+f x y = MkP x (y * 3)
+
+g :: Int -> Int -> P
+g x y = MkP x (y * 3)
=====================================
testsuite/tests/simplCore/should_compile/T28095a.stderr
=====================================
@@ -0,0 +1 @@
+f = g
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -629,3 +629,5 @@ test('T27749',
test('T27629', only_ways(['optasm']), makefile_test, ['T27629'])
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'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/13408a2b593d9c1831ea82faf2f532…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/13408a2b593d9c1831ea82faf2f532…
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/ncg-comment-fixes] Fix stale and false comments in the NCG
by Mikolaj Konarski (@Mikolaj) 16 Nov '26
by Mikolaj Konarski (@Mikolaj) 16 Nov '26
16 Nov '26
Mikolaj Konarski pushed to branch wip/ncg-comment-fixes at Glasgow Haskell Compiler / GHC
Commits:
5403c34f by Mikolaj Konarski at 2026-11-16T18:00:07+01:00
Fix stale and false comments in the NCG
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe."
Comments and documentation only: the generated code is the same. Each
item names a comment, says what it said, and says what holds instead.
- The comment above genMachCode in GHC.CmmToAsm named stix code
and the UniqSM monad. The code is Cmm, and genMachCode switches
from the UniqDSM monad to NatM.
- NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad, placed
Note [Unwinding information in the NCG] in that module. The Note
is in GHC.CmmToAsm.
- The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm,
AsmCodeGen and MachCodeGen. It now names the modules and functions
that do what it lists.
- The header of GHC.CmmToAsm.Reg.Target said that the module keeps
the NCG from emitting code for an architecture other than the host's.
Each of its functions dispatches on the target platform's
architecture, and the sentence is deleted.
- Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout ran
optimizeCFG right after instruction selection. cmmNativeGen runs
it after register allocation and shortcutting.
- Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight
as 20k; defaultWeights has 1000. It said that likely branches
are taken more than 80% of the time and unlikely ones less than 20%;
the default weights give 75% and 25%. It said that the false side
of a regular branch is preferred; getCfg gives both sides the same
weight, the x86-64 instruction selector adds 3 to the false side
of a floating-point comparison, and optHsPatterns' favourFewerPreds
may then prefer one side by its predecessors. It said that calls
are ignored completely; the layout leaves a call's edge out only while
it builds chains, and divides its weight by 64 when it merges them.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also
said that edges constituted by a call are ignored. The layout ignores
them only while it builds the chains, and counts a 64th of their
weight when it merges the chains.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two
heuristics where staticBranchPrediction applies three, ohPredicts
being the third.
- In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1
is the branch in the true case; s1 is the successor with the smaller
label. The guard commented "Only backedges" is also reached by a back
edge beside a heap or stack check's edge, and its comment now says so.
- The comment above findBackEdges, in GHC.CmmToAsm.CFG, said
that it finds back edges by BFS. It finds them by a depth-first search
(classifyEdges in GHC.Data.Graph.Directed).
- The Instruction class asked regUsageOfInstr to state precisely
the registers an instruction reads and writes. x86's states them
as the register allocators are to see them, and the comment now says
where that departs from what the hardware does.
- The comment at the last arm of regUsageOfInstr's MOV case,
in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching
it zero any remaining upper part of the destination. Some do, such
as a 32-bit MOV into a general register and a load at FF32 or FF64;
others keep it, such as a MOV between registers at FF32 or FF64,
printed movss or movsd, and an 8-bit or 16-bit MOV into a general
register. The comment now also says that the usage of the other MOV
instructions has a register destination written, not read.
- Comments in the liveness pass, in both register allocators and
at the Ord instances of CmmTickScope, LocalReg and VirtualReg said
that deterministic code generation is not supported, which
-fobject-determinism provides. In the liveness pass
and the allocators, each now says whether the order at hand matters
and, where it does, what it decides; at the Ord instances,
that the order compares uniques and so is deterministic only
if the uniques are.
- In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there
are no loops in the code, so that the block frequencies can be 1.
Given a CFG, slurpSpillCostInfo scales the uses and definitions
it counts by the CFG's block frequencies; the comment is deleted.
- linearRegAlloc's haddock and the comment over process said
that a block of an SCC is allocated before a jump into it only
if it is the procedure's first block; any of its entry blocks is.
The comment over process also said that process loops where a block's
assignment never gets set. It stops after a round that allocates
no block, and so drops such a block.
- findPrefRealReg's comment said that the preferred register
is the first one the variable was assigned to. It is the variable's
register in the first entry assignment, in allocation order, that maps
it to a register; a block's entry assignment is recorded at the first
jump into it.
- Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint,
which is -dasm-lint.
- Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag
-ddrop-asm-stats, which is -ddump-asm-stats.
- The executable specification of FreeRegs,
in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently
released registers first. It now gives noFreeRegs as [] and has
getFreeRegs hand out the registers in each instance's fixed order.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays
associated with its register to the end of the procedure. A register
that outgrows its slot moves to new ones; what holds is that no other
register gets the old slot.
- The comment at handleComponent's case for a cycle of moves,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that it spills all
the cycle's source registers. It spills one.
- makeRegMovementGraph's comment said that cyclic components seem
to occur only very rarely. They are frequent in some code:
in the benchmark of orthotope, a Haskell array library on Hackage,
compiled by a GHC build of 2026-10 whose linear allocator
was master's, the fixup code breaks 39 register cycles through a stack
slot in $w$s$wequalT1 and 59 in $w$s$w$ccompare1. The two counts
were not taken again on master. The sentence is deleted.
- GHC.CmmToAsm.Reg.Linear.State cited
Note [The one-shot state monad trick] across two lines, where
the notes linter does not match it. The citation is now on one line.
- GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal proc labels]
in GHC.Cmm.Label, across two lines. The Note is in GHC.Cmm.CLabel,
and the citation is now on one line.
- A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs
scans the integer registers from 28 down. It starts from x18,
and the comment now also says that it starts from v31 among the v
registers.
- The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86"
of what holds on i386 alone, and numbered the registers with 8-bit
versions 1-4, and the allocatable ones among them 1, 3 and 4. It now
says "On i386", and they are 0-3, and 0, 2 and 3.
- The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave
RISC-V as an example. registerArch gives RISC-V NoVectors
and no architecture Separate.
- X86's stmtToInstrs took the condition of a conditional branch
to be likely false, GHC.Cmm.ContFlowOpt having arranged for the likely
side to fall through. ContFlowOpt also inverts a condition whatever
its likelihood where the condition can be inverted, the true target
has one predecessor and the false target more than one,
so the condition may be likely true; genCondBranch does not read
the likelihood.
- mkCmmIfThenElse', in GHC.StgToCmm.Monad, said that the NCG does
not know about likely annotations. The PowerPC code generator has
printed them as branch hints since 2017, and since 2018 getCfg has
weighted the CFG's edges by them, which on x86-64 the block layout
and the order of some conditional branches' jumps (invertCondBranches)
follow. Its clause on a fallthrough is replaced by what the swap does:
where the test can be inverted it becomes a likely-true test
of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where
the true target, after shortcutting, has one predecessor.
- The users' guide said that -fcmm-static-pred's prediction is used
by the register allocation and code layout passes. The prediction
is made only in the x86-64 native code generator, and is used, after
register allocation and without -finfo-table-map, for the layout
and for the order of some conditional branches' jumps
(invertCondBranches).
- The users' guide's entry of -fcmm-sink said that the sinking pass
attempts to find identical Cmm blocks and eliminate the duplicates.
Those are words of the -fcmm-elim-common-blocks entry, run
into this entry's sentence since the two entries were written;
the sentence now says only that the pass attempts to move variable
bindings closer to their usage sites.
Assisted-by: Claude Opus 5.5
- - - - -
29 changed files:
- compiler/GHC/Cmm/Node.hs
- compiler/GHC/Cmm/Reg.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PIC.hs
- compiler/GHC/CmmToAsm/Reg/Graph.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Base.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/AArch64.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Base.hs
- compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- compiler/GHC/CmmToAsm/Reg/Target.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToAsm/X86/Regs.hs
- compiler/GHC/Platform/Reg.hs
- compiler/GHC/Platform/Reg/Class.hs
- compiler/GHC/StgToCmm/Monad.hs
- docs/users_guide/using-optimisation.rst
Changes:
=====================================
compiler/GHC/Cmm/Node.hs
=====================================
@@ -894,8 +894,8 @@ instance Eq CmmTickScope where
-- This is still deterministic because
-- the order is the same for equal lists
--- This is non-deterministic but we do not currently support deterministic
--- code-generation. See Note [Unique Determinism and code generation]
+-- This compares uniques, so the order is deterministic only if the uniques are:
+-- see Note [Unique Determinism and code generation].
-- See Note [No Ord for Unique]
instance Ord CmmTickScope where
compare GlobalScope GlobalScope = EQ
=====================================
compiler/GHC/Cmm/Reg.hs
=====================================
@@ -121,8 +121,8 @@ instance Eq LocalReg where
instance Outputable LocalReg where
ppr e = pprLocalReg e
--- This is non-deterministic but we do not currently support deterministic
--- code-generation. See Note [Unique Determinism and code generation]
+-- This compares uniques, so the order is deterministic only if the uniques are:
+-- see Note [Unique Determinism and code generation].
-- See Note [No Ord for Unique]
instance Ord LocalReg where
compare (LocalReg u1 _) (LocalReg u2 _) = nonDetCmpUnique u1 u2
=====================================
compiler/GHC/CmmToAsm.hs
=====================================
@@ -890,8 +890,8 @@ apply_mapping ncgImpl ufm (CmmProc info lbl live (ListGraph blocks))
-- -----------------------------------------------------------------------------
-- Instruction selection
--- Native code instruction selection for a chunk of stix code. For
--- this part of the computation, we switch from the UniqSM monad to
+-- Native code instruction selection for a chunk of Cmm. For
+-- this part of the computation, we switch from the UniqDSM monad to
-- the NatM monad. The latter carries not only a Unique, but also an
-- Int denoting the current C stack pointer offset in the generated
-- code; this is needed for creating correct spill offsets on
=====================================
compiler/GHC/CmmToAsm/BlockLayout.hs
=====================================
@@ -56,7 +56,7 @@ import GHC.Types.Unique.DSM (UniqDSM)
* Compute a CFG based on the Cmm AST, see getCfgProc.
This CFG will have edge weights representing a guess
on how important they are.
- * After we convert Cmm to Asm we run `optimizeCFG` which
+ * After register allocation and shortcutting we run `optimizeCFG` which
adds a few more "educated guesses" to the equation.
* Then we run loop analysis on the CFG (`loopInfo`) which tells us
about loop headers, loop nesting levels and the sort.
@@ -265,7 +265,8 @@ import GHC.Types.Unique.DSM (UniqDSM)
We apply a small modifier to them to ensure edges for which we can
eliminate the overhead completely are considered first. See also #18053.
- * Edges constituted by a call are ignored.
+ * Edges constituted by a call are ignored while the chains are built, and
+ count a 64th of their weight when the chains are merged at the end.
Considering these hardly helped with performance and ignoring
them helps quite a bit to improve compiler performance.
=====================================
compiler/GHC/CmmToAsm/CFG.hs
=====================================
@@ -560,22 +560,29 @@ addNodesBetween weights m updates =
* Unconditional Control Transfer - They will always
transfer control to their target. Unless there is a info table
we can turn the jump into a fallthrough as well.
- We use 20k as default, so it's easy to spot if values have been
- modified but unlikely that we run into issues with overflow.
+ We use 1000 as default ('defaultWeights' in GHC.CmmToAsm.CFG.Weight).
* If branches (likely) - We assume branches marked as likely
- are taken more than 80% of the time.
+ are taken 75% of the time: the default weights give the likely side 900 and
+ the other side 300.
By ranking them below unconditional jumps we make sure we
prefer the unconditional if there is a conditional and
unconditional edge towards a block.
- * If branches (regular) - The false branch can potentially be turned
- into a fallthrough so we prefer it slightly over the true branch.
- * Unlikely branches - These can be assumed to be taken less than 20%
- of the time. So we given them one of the lowest priorities.
+ * If branches (regular) - Both sides get the same weight, but on x86-64 the
+ instruction selector adds 3 to the weight of a floating-point comparison's
+ false edge (genCondBranch' in GHC.CmmToAsm.X86.CodeGen). If the weights are
+ still equal after optHsPatterns' other adjustments, favourFewerPreds adds
+ one to the side with fewer predecessors that could fall through into it, and
+ subtracts one from the other side.
+ * Unlikely branches - By the same weights we assume that these are taken 25%
+ of the time. So we give them one of the lowest priorities.
* Switches - Switches at this level are implemented as jump tables
so have a larger number of successors. So without more information
we can only say that each individual successor is unlikely to be
jumped to and we rank them accordingly.
- * Calls - We currently ignore calls completely:
+ * Calls - A call's edge to its continuation gets callWeight. The
+ layout leaves these edges out when it builds chains (directEdges in
+ GHC.CmmToAsm.BlockLayout), and divides their weight by 64 when it merges the
+ chains at the end:
* By the time we return from a call there is a good chance
that the address we return to has already been evicted from
cache eliminating a main advantage sequential placement brings.
@@ -659,7 +666,7 @@ getCfg platform weights graph =
blocks = revPostorder graph :: [CmmBlock]
---Find back edges by BFS
+--Find back edges by a depth-first search (classifyEdges)
findBackEdges :: HasDebugCallStack => BlockId -> CFG -> Edges
findBackEdges root cfg =
--pprTraceIt "Backedges:" $
@@ -991,9 +998,9 @@ check we do not apply any of the heuristics.
The reason is simple: They look like loops in the control flow graph
but are usually never entered, and if at most once.
-Currently implemented is a heuristic to predict that we do not exit
-loops (lehPredicts) and one to predict that backedges are more likely
-than any other edge.
+Three heuristics are implemented: that we do not exit loops (lehPredicts), that
+a comparison with a literal is unequal (ohPredicts), and that a back edge is
+more likely than any other edge.
The back edge case is special as it supersedes any other heuristic if it
applies.
@@ -1055,7 +1062,9 @@ staticBranchPrediction _root (LoopInfo l_backEdges loopLevels l_loops) cfg =
| length successors /= 2
= cfg
- -- Only backedges - no need to adjust
+ -- Only backedges - no need to adjust. This case also keeps the weights
+ -- of a back edge beside a heap or stack check's edge, which the mix
+ -- case above excludes.
| length m > 0
= cfg
@@ -1116,7 +1125,9 @@ staticBranchPrediction _root (LoopInfo l_backEdges loopLevels l_loops) cfg =
-- Heuristics return nothing if they don't say anything about this branch
-- or Just (prob_s1) where prob_s1 is the likelihood for s1 to be the
- -- taken branch. s1 is the branch in the true case.
+ -- taken branch. s1 is the successor with the smaller label, as
+ -- getSuccessorEdges orders them, and need not be the true branch: a
+ -- heuristic that needs the true branch looks it up, as ohPredicts does.
-- Loop exit heuristic.
-- We are unlikely to leave a loop unless it's to enter another one.
=====================================
compiler/GHC/CmmToAsm/Instr.hs
=====================================
@@ -29,7 +29,15 @@ class Instruction instr where
-- | Get the registers that are being used by this instruction.
-- regUsage doesn't need to do any trickery for jumps and such.
- -- Just state precisely the regs read and written by that insn.
+ -- State the regs read and written by that insn as the register
+ -- allocators are to see them, which need not be what the hardware
+ -- does. x86's regUsageOfInstr says that a zeroing XOR, VXOR,
+ -- PXOR or VPXOR reads nothing, and that at the format FF32 or
+ -- FF64 a MOV between registers or a MOVHLPS does not read its
+ -- destination, whose upper part the hardware keeps; it records
+ -- the float and vector registers a call clobbers at the format
+ -- FF64 whatever their width, and leaves out the real registers the
+ -- allocators do not hand out.
-- The consequences of control flow transfers, as far as register
-- allocation goes, are taken care of by the register allocator.
--
=====================================
compiler/GHC/CmmToAsm/Monad.hs
=====================================
@@ -117,7 +117,7 @@ data NcgImpl statics instr jumpDest = NcgImpl {
-- ^ given the instruction sequence of a block, produce a list of
-- the block's 'UnwindPoint's
-- See Note [What is this unwinding business?] in "GHC.Cmm.DebugBlock"
- -- and Note [Unwinding information in the NCG] in this module.
+ -- and Note [Unwinding information in the NCG] in "GHC.CmmToAsm".
invertCondBranches :: Maybe CFG -> LabelMap RawCmmStatics -> [NatBasicBlock instr]
-> [NatBasicBlock instr]
-- ^ Turn the sequence of @jcc l1; jmp l2@ into @jncc l2; \<block_l1>@
=====================================
compiler/GHC/CmmToAsm/PIC.hs
=====================================
@@ -7,12 +7,12 @@
Things outside this module which are related to this:
- + module CLabel
+ + GHC.Cmm.CLabel
- PIC base label (pretty printed as local label 1)
- DynamicLinkerLabels - several kinds:
CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset
- labelDynamic predicate
- + module Cmm
+ + GHC.Cmm.Reg and GHC.Cmm.Expr
- The GlobalReg datatype has a PicBaseReg constructor
- The CmmLit datatype has a CmmLabelDiffOff constructor
+ codeGen & RTS
@@ -22,15 +22,18 @@
because Win32 doesn't support external references in data sections.
TODO: make sure this still works, it might be bitrotted
+ NCG
- - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all
+ - cmmToCmm in GHC.Cmm.GenericOpt calls cmmMakeDynamicReference for all
labels.
- - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output
- all the necessary stuff for imported symbols.
+ - makeImportsDoc in GHC.CmmToAsm calls pprImportedSymbol and
+ pprGotDeclaration to output all the necessary stuff for imported
+ symbols.
- The NCG monad keeps track of a list of imported symbols.
- - MachCodeGen invokes initializePicBase to generate code to initialize
- the PIC base register when needed.
- - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel
- that wasn't in the original Cmm code (e.g. floating point literals).
+ - The x86 and PowerPC instruction selectors invoke initializePicBase_x86
+ and initializePicBase_ppc to generate code to initialize the PIC base
+ register when needed.
+ - The instruction selectors call cmmMakeDynamicReference whenever they
+ use a CLabel that wasn't in the original Cmm code (e.g. floating point
+ literals).
-}
module GHC.CmmToAsm.PIC (
=====================================
compiler/GHC/CmmToAsm/Reg/Graph.hs
=====================================
@@ -131,9 +131,8 @@ regAlloc_spin config spinCount triv regsFree slotsFree slotsCount debug_codeGrap
$$ text "regsFree = " <> (hcat $ punctuate space $ map ppr
$ nonDetEltsUniqSet $ unionManyUniqSets
$ nonDetEltsUFM regsFree)
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- The order decides only how the panic message lists the free
+ -- registers (Note [Unique Determinism and code generation])
$$ text "slotsFree = " <> ppr (sizeUniqSet slotsFree))
-- Build the register conflict graph from the cmm code.
@@ -193,7 +192,7 @@ regAlloc_spin config spinCount triv regsFree slotsFree slotsCount debug_codeGrap
-- Coloring was successful because no registers needed to be spilled.
then do
- -- if -fasm-lint is turned on then validate the graph.
+ -- if -dasm-lint is turned on then validate the graph.
-- This checks for bugs in the graph allocator itself.
let graph_colored_lint =
if ncgAsmLinting config
@@ -254,7 +253,7 @@ regAlloc_spin config spinCount triv regsFree slotsFree slotsCount debug_codeGrap
-- Coloring was unsuccessful. We need to spill some register to the
-- stack, make a new graph, and try to color it again.
else do
- -- if -fasm-lint is turned on then validate the graph
+ -- if -dasm-lint is turned on then validate the graph
let graph_colored_lint =
if ncgAsmLinting config
then Color.validateGraph (text "")
=====================================
compiler/GHC/CmmToAsm/Reg/Graph/Base.hs
=====================================
@@ -96,9 +96,8 @@ worst regsOfClass regAlias neighbors classN classC
= let regAliasS regs = unionManyUniqSets
$ map regAlias
$ nonDetEltsUniqSet regs
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- The union does not depend on the order
+ -- (Note [Unique Determinism and code generation])
-- all the regs in classes N, C
regsN = regsOfClass classN
=====================================
compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
=====================================
@@ -79,9 +79,9 @@ regSpill platform code slotsFree slotCount regs
-- See Note [UniqFM and the register allocator]
$ listToUFM
$ zip (nonDetEltsUniqSet regs) slots :: UniqFM Reg Int
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- The order of both lists decides which free slots
+ -- are taken and which spilled vreg gets each
+ -- (Note [Unique Determinism and code generation])
-- Grab the unique supply from the monad.
UDSM $ \us ->
=====================================
compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
=====================================
@@ -122,9 +122,9 @@ slurpSpillCostInfo platform cfg cmm
= do
-- Increment the lifetime counts for regs live on entry to this instr.
mapM_ incLifetime $ nonDetEltsUniqSet rsLiveEntry
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- Each vreg's lifetime is counted on
+ -- its own, so the order does not matter
+ -- (Note [Unique Determinism and code generation])
-- Increment counts for what regs were read/written from.
-- See Note [Cached register usage in liveness annotations] in GHC.CmmToAsm.Reg.Liveness
@@ -178,8 +178,6 @@ chooseSpill info graph
-- cost = sum loadCost * freq (u) + sum storeCost * freq (d)
-- u <- uses (v) d <- defs (v)
--
--- There are no loops in our code at the moment, so we can set the freq's to 1.
---
-- If we don't have live range splitting then Chaitins function performs badly
-- if we have lots of nested live ranges and very few registers.
--
=====================================
compiler/GHC/CmmToAsm/Reg/Linear.hs
=====================================
@@ -201,7 +201,7 @@ regAlloc _ (CmmProc _ _ _ _)
-- | Do register allocation on some basic blocks.
-- But be careful to allocate a block in an SCC only if it has
--- an entry in the block map or it is the first block.
+-- an entry in the block map or it is an entry block of the procedure.
--
linearRegAlloc
:: forall instr. (Instruction instr)
@@ -286,11 +286,10 @@ linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs)
before allocating one of its predecessors, which could lead to
inconsistent allocations. Make it so a block is only allocated
if a predecessor has set the "incoming" assignments for the block, or
- if it's the procedure's entry block.
+ if it is one of the procedure's entry blocks.
- BL 2009/02: Careful. If the assignment for a block doesn't get set for
- some reason then this function will loop. We should probably do some
- more sanity checking to guard against this eventuality.
+ A block whose assignment never gets set is dropped: process stops after
+ a round in which it allocates no block.
-}
process :: forall freeRegs instr. (OutputableRegConstraint freeRegs instr)
@@ -701,9 +700,10 @@ saveClobberedTemps clobbered dying
-> RegM freeRegs (RegMap Loc,[instr])
maybe_spill !temp !(assig,instrs) !loc =
case loc of
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- saveClobberedTemps folds maybe_spill over the vregs in the
+ -- order of their uniques, so the order decides which clobbered
+ -- values move to free registers and which are spilled once
+ -- those run out (Note [Unique Determinism and code generation])
Loc (InReg reg) fmt
| any (realRegsAlias reg) clobbered
, temp `notElem` map getUnique dying
@@ -775,9 +775,8 @@ clobberRegs clobbered
assig <- getAssigR
setAssigR $! clobber assig (nonDetUFMToList assig)
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- Each vreg is updated on its own, so the list's order does
+ -- not matter (Note [Unique Determinism and code generation])
where
-- if the temp was InReg and clobbered, then we will have
@@ -871,8 +870,13 @@ allocateRegsAndSpill reading keep spills alloc (r@(VirtualRegWithFormat vr vrFmt
| otherwise -> doSpill WriteNew
-- | Given a virtual reg find a preferred real register.
--- The preferred register is simply the first one the variable
--- was assigned to (if any). This way when we allocate for a loop
+-- A block's entry assignment is recorded at the first jump into it, and the
+-- preferred register is the variable's register in the first entry assignment,
+-- in allocation order, that maps it to a register ('updateBlockAssignment'
+-- keeps the first). That need not be the first register the variable was
+-- assigned to, and a variable that no entry assignment maps to a register has
+-- none.
+-- This way when we allocate for a loop
-- variables are likely to end up in the same registers at the
-- end and start of the loop, avoiding redundant reg-reg moves.
-- Note: I tried returning a list of past assignments, but that
@@ -932,9 +936,12 @@ allocRegsAndSpill_spill reading keep spills alloc r@(VirtualRegWithFormat vr vrF
flip delListFromUFM (fmap virtualRegWithFormat_reg keep) $
filterUFM (inRegOrBoth . locWithFormat_loc) $
assig
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- candidates lists the vregs in a register, except those
+ -- in keep, in the order of their uniques, and that order
+ -- picks the vreg evicted below: of those whose register
+ -- is of the class needed (compat), the first in both a
+ -- register and a slot, else the first in a register only
+ -- (Note [Unique Determinism and code generation])
let candidates = nonDetUFMToList candidates'
-- the vregs we could kick out that are already in a slot
=====================================
compiler/GHC/CmmToAsm/Reg/Linear/AArch64.hs
=====================================
@@ -72,7 +72,8 @@ allocateReg (RealRegSingle r) (FreeRegs g f)
| r > 31 = panic $ "Linear.AArch64.allocReg: double allocation of float reg v" ++ show (r - 32) ++ "; " ++ showBits f
| otherwise = pprPanic "Linear.AArch64.allocReg" $ text ("double allocation of gp reg x" ++ show r ++ "; " ++ showBits g)
--- we start from 28 downwards... the logic is similar to the ppc logic.
+-- getFreeRegs starts from x18 downwards (x19 to x28 hold STG's registers,
+-- below) and from v31 downwards... the logic is similar to the ppc logic.
-- 31 is Stack Pointer
-- 30 is Link Register
-- 29 is Stack Frame (by convention)
=====================================
compiler/GHC/CmmToAsm/Reg/Linear/Base.hs
=====================================
@@ -153,7 +153,7 @@ regsOfLoc (InBoth r _) = [r]
regsOfLoc (InMem _) = []
-- | Reasons why instructions might be inserted by the spiller.
--- Used when generating stats for -ddrop-asm-stats.
+-- Used when generating stats for -ddump-asm-stats.
--
data SpillReason
-- | vreg was spilled to a slot so we could use its
@@ -208,7 +208,7 @@ data RA_State freeRegs
-- | unique supply for generating names for join point fixup blocks.
, ra_us :: DUniqSupply
- -- | Record why things were spilled, for -ddrop-asm-stats.
+ -- | Record why things were spilled, for -ddump-asm-stats.
-- Just keep a list here instead of a map of regs -> reasons.
-- We don't want to slow down the allocator if we're not going to emit the stats.
, ra_spills :: [SpillReason]
=====================================
compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs
=====================================
@@ -23,11 +23,13 @@ import GHC.Platform
-- Here's an inefficient 'executable specification' of the FreeRegs data type:
--
-- type FreeRegs = [RegNo]
--- noFreeRegs = 0
+-- noFreeRegs = []
-- releaseReg n f = if n `elem` f then f else (n : f)
-- initFreeRegs = allocatableRegs
--- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) f
+-- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) (inOrder f)
-- allocateReg f r = filter (/= r) f
+--
+-- where inOrder sorts the registers into the instance's own fixed order.
import qualified GHC.CmmToAsm.Reg.Linear.PPC as PPC
import qualified GHC.CmmToAsm.Reg.Linear.X86 as X86
=====================================
compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
=====================================
@@ -97,9 +97,9 @@ joinToTargets' block_live new_blocks block_id instr (dest:dests)
-- and free up those registers which are now free.
let to_free =
[ r | (reg, Loc loc _locFmt) <- nonDetUFMToList assig
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- The registers are released into a bitmap of
+ -- free registers, so the order does not matter
+ -- (Note [Unique Determinism and code generation])
, not (elemUniqSet_Directly reg $ getRegs live_set)
, r <- regsOfLoc loc ]
@@ -159,9 +159,9 @@ joinToTargets_again
| equalIgnoringFormats
(nonDetUFMToList dest_assig)
(nonDetUFMToList src_assig)
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- Both lists are in the order of the uniques, so
+ -- the comparison does not depend on that order
+ -- (Note [Unique Determinism and code generation])
= joinToTargets' block_live new_blocks block_id instr dests
-- assignments don't match, need fixup code
@@ -237,17 +237,15 @@ joinToTargets_again
-- | Construct a graph of register\/spill movements.
--
--- Cyclic components seem to occur only very rarely.
---
-- We cut some corners by not handling memory-to-memory moves.
-- This shouldn't happen because every temporary gets its own stack slot.
--
makeRegMovementGraph :: RegMap Loc -> RegMap Loc -> [Node Loc Unique]
makeRegMovementGraph adjusted_assig dest_assig
= [ node | (vreg, src) <- nonDetUFMToList adjusted_assig
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- The list's order, by unique, decides the order of the
+ -- fixup moves and which move of a cycle goes through the
+ -- stack (Note [Unique Determinism and code generation])
-- source reg might not be needed at the dest:
, Just loc <- [lookupUFM_Directly dest_assig vreg]
, node <- expandNode vreg src loc ]
@@ -323,8 +321,10 @@ handleComponent delta _ (AcyclicSCC (DigraphNode vreg src dsts))
-- (vreg1, InReg r1, [InReg r2])
-- (vreg2, InReg r2, [InReg r1])
--
--- To avoid needing temp register, we just spill all the source regs, then
--- reaload them into their destination regs.
+-- To avoid needing a temp register, we spill the first move's source
+-- reg into its vreg's slot, do the other moves (handling any cycle left
+-- among them the same way), and reload the slot into the first move's
+-- destination reg last.
--
-- Note that we can not have cycles that involve memory locations as
-- sources as single destination because memory locations (stack slots)
=====================================
compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs
=====================================
@@ -7,8 +7,9 @@
-- The StackMap stack map keeps track of virtual register - stack slot
-- associations and of which stack slots are still free. Once it has been
--- associated, a stack slot is never "freed" or removed from the StackMap again,
--- it remains associated until we are done with the current CmmProc.
+-- associated, a stack slot is never "freed": no other virtual register
+-- gets it before we are done with the current CmmProc, even after its
+-- register has outgrown it and moved to new slots.
--
module GHC.CmmToAsm.Reg.Linear.StackMap (
StackSlot,
=====================================
compiler/GHC/CmmToAsm/Reg/Linear/State.hs
=====================================
@@ -64,8 +64,8 @@ newtype RegM freeRegs a
= RegM { unReg :: RA_State freeRegs -> RA_Result freeRegs a }
deriving (Functor, Applicative, Monad) via (Strict.State (RA_State freeRegs))
--- | Smart constructor for 'RegM', as described in Note [The one-shot state
--- monad trick] in GHC.Utils.Monad.
+-- | Smart constructor for 'RegM', as described in
+-- Note [The one-shot state monad trick] in GHC.Utils.Monad.
mkRegM :: (RA_State freeRegs -> RA_Result freeRegs a) -> RegM freeRegs a
mkRegM f = RegM (oneShot f)
=====================================
compiler/GHC/CmmToAsm/Reg/Liveness.hs
=====================================
@@ -522,9 +522,9 @@ slurpReloadCoalesce live
= listToUFM_Directly
$ [ (k, r1)
| (k, r1) <- nonDetUFMToList map1
- -- This is non-deterministic but we do not
- -- currently support deterministic code-generation.
- -- See Note [Unique Determinism and code generation]
+ -- Each entry is kept or dropped on its own and the list
+ -- becomes a map again, so its order does not matter
+ -- (Note [Unique Determinism and code generation])
, case lookupUFM_Directly map2 k of
Nothing -> False
Just r2 -> r1 == r2 ]
=====================================
compiler/GHC/CmmToAsm/Reg/Target.hs
=====================================
@@ -1,7 +1,5 @@
-- | Hard wired things related to registers.
--- This is module is preventing the native code generator being able to
--- emit code for non-host architectures.
--
-- TODO: Do a better job of the overloading, and eliminate this module.
-- We'd probably do better with a Register type class, and hook this to
=====================================
compiler/GHC/CmmToAsm/X86/CodeGen.hs
=====================================
@@ -344,8 +344,11 @@ stmtToInstrs bid stmt = do
CmmBranch id -> return $ genBranch id
- --We try to arrange blocks such that the likely branch is the fallthrough
- --in GHC.Cmm.ContFlowOpt. So we can assume the condition is likely false here.
+ -- The condition may be likely true here: GHC.Cmm.ContFlowOpt inverts a
+ -- condition whose true target has one predecessor if the condition is
+ -- likely true, but also, whatever its likelihood, if the false target
+ -- has more than one predecessor (Note [Invert Cmm conditionals]).
+ -- genCondBranch does not read the likelihood.
CmmCondBranch arg true false _ -> genCondBranch bid true false arg
CmmSwitch arg ids -> genSwitch arg ids bid
CmmCall { cml_target = arg
=====================================
compiler/GHC/CmmToAsm/X86/Instr.hs
=====================================
@@ -448,8 +448,12 @@ regUsageOfInstr platform instr
, OpReg {} <- src
, OpReg {} <- dst
-> readOp dst_fmt src <.> modifyOp dst_fmt dst
- -- other MOV instructions zero any remaining upper part of the destination
- -- (largely to avoid partial register stalls)
+ -- The usage of the other MOV instructions has a register destination
+ -- written, not read. Some of them zero any remaining upper part of the
+ -- destination (largely to avoid partial register stalls), such as a
+ -- 32-bit MOV into a general register and a load at FF32 or FF64; others
+ -- keep it, such as a MOV between registers at FF32 or FF64 (movss, movsd)
+ -- and an 8-bit or 16-bit MOV into a general register.
| otherwise
-> readOp dst_fmt src <.> writeOp dst_fmt dst
MOVD fmt1 fmt2 src dst ->
=====================================
compiler/GHC/CmmToAsm/X86/Ppr.hs
=====================================
@@ -105,8 +105,8 @@ pprNatCmmDecl config proc@(CmmProc top_info entry_lbl _ (ListGraph blocks)) =
-- info table and not the entry code!
, pprProcAlignment config
- -- Special label when ncgExposeInternalSymbols is enabled. See Note
- -- [Internal proc labels] in GHC.Cmm.Label
+ -- Special label when ncgExposeInternalSymbols is enabled. See
+ -- Note [Internal proc labels] in GHC.Cmm.CLabel
, pprExposedInternalProcLabel config entry_lbl
-- Subsections-via-symbols label. See Note [Subsections Via Symbols]
=====================================
compiler/GHC/CmmToAsm/X86/Regs.hs
=====================================
@@ -225,10 +225,10 @@ allMachRegNos platform = intregnos (platformWordSize platform) ++ floatregnos pl
-- | Take the class of a register.
{-# INLINE classOfRealReg #-}
classOfRealReg :: Platform -> RealReg -> RegClass
--- On x86, we might want to have an 8-bit RegClass, which would
--- contain just regs 1-4 (the others don't have 8-bit versions).
+-- On i386, we might want to have an 8-bit RegClass, which would
+-- contain just regs 0-3 (the others don't have 8-bit versions).
-- However, we can get away without this at the moment because the
--- only allocatable integer regs are also 8-bit compatible (1, 3, 4).
+-- only allocatable integer regs are also 8-bit compatible (0, 2, 3).
classOfRealReg platform reg
= case reg of
RealRegSingle i
=====================================
compiler/GHC/Platform/Reg.hs
=====================================
@@ -72,8 +72,8 @@ data VirtualReg
-- We can't derive Ord, because Unique doesn't have an Ord instance.
-- Note nonDetCmpUnique in the implementation. See Note [No Ord for Unique].
--- This is non-deterministic but we do not currently support deterministic
--- code-generation. See Note [Unique Determinism and code generation]
+-- This compares uniques, so the order is deterministic only if the uniques are:
+-- see Note [Unique Determinism and code generation].
instance Ord VirtualReg where
compare vr1 vr2 =
case compare (I# (dataToTag# vr1)) (I# (dataToTag# vr2)) of
=====================================
compiler/GHC/Platform/Reg/Class.hs
=====================================
@@ -30,7 +30,9 @@ instance Outputable RegClass where
data RegArch
-- | Floating-point and vector registers are unified (e.g. X86, AArch64).
= Unified
- -- | Floating-point and vector registers are separate (e.g. RISC-V).
+ -- | Floating-point and vector registers are separate. No architecture uses
+ -- this yet: registerArch gives RISC-V NoVectors, as its vector registers are
+ -- not supported.
| Separate
-- | No vector registers.
| NoVectors
=====================================
compiler/GHC/StgToCmm/Monad.hs
=====================================
@@ -835,10 +835,14 @@ mkCmmIfThenElse' e tbranch fbranch likely = do
let
(test, then_, else_, likely') = case likely of
Just False | Just e' <- maybeInvertCmmExpr e
- -- currently NCG doesn't know about likely
- -- annotations. We manually switch then and
- -- else branch so the likely false branch
- -- becomes a fallthrough.
+ -- The NCG uses likely annotations on x86-64, where getCfg in
+ -- GHC.CmmToAsm.CFG weights the CFG's edges by them for the block layout
+ -- and the order of some conditional branches' jumps, and on PowerPC,
+ -- which prints them as hints on its branches. Where maybeInvertCmmExpr
+ -- can invert it, a test annotated likely false becomes a likely-true
+ -- test of the inverse, with the branches swapped. GHC.Cmm.ContFlowOpt
+ -- swaps them back where the true target, after shortcutting, has one
+ -- predecessor (Note [Invert Cmm conditionals]).
-> (e', fbranch, tbranch, Just True)
_ -> (e, tbranch, fbranch, likely)
=====================================
docs/users_guide/using-optimisation.rst
=====================================
@@ -250,8 +250,7 @@ as such you shouldn't need to set any of them explicitly. A flag
:default: off but enabled by :ghc-flag:`-O`.
Enables the sinking pass in the code generator.
- This optimisation attempts to find identical Cmm blocks and
- eliminate the duplicates attempts to move variable bindings closer
+ This optimisation attempts to move variable bindings closer
to their usage sites. It also inlines simple expressions like
literals or registers.
@@ -263,10 +262,11 @@ as such you shouldn't need to set any of them explicitly. A flag
:default: off but enabled by :ghc-flag:`-O`.
- This enables static control flow prediction on the final Cmm
- code. If enabled GHC will apply certain heuristics to identify
- loops and hot code paths. This information is then used by the
- register allocation and code layout passes.
+ This enables static control flow prediction in the native code generator
+ for x86-64. If enabled GHC will apply certain heuristics to identify loops
+ and hot code paths, and use this information to lay out the code and to
+ order the jumps of some conditional branches. It has no effect when
+ :ghc-flag:`-finfo-table-map` is on.
.. ghc-flag:: -fcmm-control-flow
:shortdesc: Enable control flow optimisation in the Cmm backend. Implied by :ghc-flag:`-O`.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/5403c34f573df1f2775ccc74b76fc6d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/5403c34f573df1f2775ccc74b76fc6d…
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/ncg-notes] 10 commits: Fix stale and false comments in the NCG
by Mikolaj Konarski (@Mikolaj) 16 Nov '26
by Mikolaj Konarski (@Mikolaj) 16 Nov '26
16 Nov '26
Mikolaj Konarski pushed to branch wip/ncg-notes at Glasgow Haskell Compiler / GHC
Commits:
5403c34f by Mikolaj Konarski at 2026-11-16T18:00:07+01:00
Fix stale and false comments in the NCG
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe."
Comments and documentation only: the generated code is the same. Each
item names a comment, says what it said, and says what holds instead.
- The comment above genMachCode in GHC.CmmToAsm named stix code
and the UniqSM monad. The code is Cmm, and genMachCode switches
from the UniqDSM monad to NatM.
- NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad, placed
Note [Unwinding information in the NCG] in that module. The Note
is in GHC.CmmToAsm.
- The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm,
AsmCodeGen and MachCodeGen. It now names the modules and functions
that do what it lists.
- The header of GHC.CmmToAsm.Reg.Target said that the module keeps
the NCG from emitting code for an architecture other than the host's.
Each of its functions dispatches on the target platform's
architecture, and the sentence is deleted.
- Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout ran
optimizeCFG right after instruction selection. cmmNativeGen runs
it after register allocation and shortcutting.
- Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight
as 20k; defaultWeights has 1000. It said that likely branches
are taken more than 80% of the time and unlikely ones less than 20%;
the default weights give 75% and 25%. It said that the false side
of a regular branch is preferred; getCfg gives both sides the same
weight, the x86-64 instruction selector adds 3 to the false side
of a floating-point comparison, and optHsPatterns' favourFewerPreds
may then prefer one side by its predecessors. It said that calls
are ignored completely; the layout leaves a call's edge out only while
it builds chains, and divides its weight by 64 when it merges them.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also
said that edges constituted by a call are ignored. The layout ignores
them only while it builds the chains, and counts a 64th of their
weight when it merges the chains.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two
heuristics where staticBranchPrediction applies three, ohPredicts
being the third.
- In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1
is the branch in the true case; s1 is the successor with the smaller
label. The guard commented "Only backedges" is also reached by a back
edge beside a heap or stack check's edge, and its comment now says so.
- The comment above findBackEdges, in GHC.CmmToAsm.CFG, said
that it finds back edges by BFS. It finds them by a depth-first search
(classifyEdges in GHC.Data.Graph.Directed).
- The Instruction class asked regUsageOfInstr to state precisely
the registers an instruction reads and writes. x86's states them
as the register allocators are to see them, and the comment now says
where that departs from what the hardware does.
- The comment at the last arm of regUsageOfInstr's MOV case,
in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching
it zero any remaining upper part of the destination. Some do, such
as a 32-bit MOV into a general register and a load at FF32 or FF64;
others keep it, such as a MOV between registers at FF32 or FF64,
printed movss or movsd, and an 8-bit or 16-bit MOV into a general
register. The comment now also says that the usage of the other MOV
instructions has a register destination written, not read.
- Comments in the liveness pass, in both register allocators and
at the Ord instances of CmmTickScope, LocalReg and VirtualReg said
that deterministic code generation is not supported, which
-fobject-determinism provides. In the liveness pass
and the allocators, each now says whether the order at hand matters
and, where it does, what it decides; at the Ord instances,
that the order compares uniques and so is deterministic only
if the uniques are.
- In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there
are no loops in the code, so that the block frequencies can be 1.
Given a CFG, slurpSpillCostInfo scales the uses and definitions
it counts by the CFG's block frequencies; the comment is deleted.
- linearRegAlloc's haddock and the comment over process said
that a block of an SCC is allocated before a jump into it only
if it is the procedure's first block; any of its entry blocks is.
The comment over process also said that process loops where a block's
assignment never gets set. It stops after a round that allocates
no block, and so drops such a block.
- findPrefRealReg's comment said that the preferred register
is the first one the variable was assigned to. It is the variable's
register in the first entry assignment, in allocation order, that maps
it to a register; a block's entry assignment is recorded at the first
jump into it.
- Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint,
which is -dasm-lint.
- Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag
-ddrop-asm-stats, which is -ddump-asm-stats.
- The executable specification of FreeRegs,
in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently
released registers first. It now gives noFreeRegs as [] and has
getFreeRegs hand out the registers in each instance's fixed order.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays
associated with its register to the end of the procedure. A register
that outgrows its slot moves to new ones; what holds is that no other
register gets the old slot.
- The comment at handleComponent's case for a cycle of moves,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that it spills all
the cycle's source registers. It spills one.
- makeRegMovementGraph's comment said that cyclic components seem
to occur only very rarely. They are frequent in some code:
in the benchmark of orthotope, a Haskell array library on Hackage,
compiled by a GHC build of 2026-10 whose linear allocator
was master's, the fixup code breaks 39 register cycles through a stack
slot in $w$s$wequalT1 and 59 in $w$s$w$ccompare1. The two counts
were not taken again on master. The sentence is deleted.
- GHC.CmmToAsm.Reg.Linear.State cited
Note [The one-shot state monad trick] across two lines, where
the notes linter does not match it. The citation is now on one line.
- GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal proc labels]
in GHC.Cmm.Label, across two lines. The Note is in GHC.Cmm.CLabel,
and the citation is now on one line.
- A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs
scans the integer registers from 28 down. It starts from x18,
and the comment now also says that it starts from v31 among the v
registers.
- The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86"
of what holds on i386 alone, and numbered the registers with 8-bit
versions 1-4, and the allocatable ones among them 1, 3 and 4. It now
says "On i386", and they are 0-3, and 0, 2 and 3.
- The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave
RISC-V as an example. registerArch gives RISC-V NoVectors
and no architecture Separate.
- X86's stmtToInstrs took the condition of a conditional branch
to be likely false, GHC.Cmm.ContFlowOpt having arranged for the likely
side to fall through. ContFlowOpt also inverts a condition whatever
its likelihood where the condition can be inverted, the true target
has one predecessor and the false target more than one,
so the condition may be likely true; genCondBranch does not read
the likelihood.
- mkCmmIfThenElse', in GHC.StgToCmm.Monad, said that the NCG does
not know about likely annotations. The PowerPC code generator has
printed them as branch hints since 2017, and since 2018 getCfg has
weighted the CFG's edges by them, which on x86-64 the block layout
and the order of some conditional branches' jumps (invertCondBranches)
follow. Its clause on a fallthrough is replaced by what the swap does:
where the test can be inverted it becomes a likely-true test
of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where
the true target, after shortcutting, has one predecessor.
- The users' guide said that -fcmm-static-pred's prediction is used
by the register allocation and code layout passes. The prediction
is made only in the x86-64 native code generator, and is used, after
register allocation and without -finfo-table-map, for the layout
and for the order of some conditional branches' jumps
(invertCondBranches).
- The users' guide's entry of -fcmm-sink said that the sinking pass
attempts to find identical Cmm blocks and eliminate the duplicates.
Those are words of the -fcmm-elim-common-blocks entry, run
into this entry's sentence since the two entries were written;
the sentence now says only that the pass attempts to move variable
bindings closer to their usage sites.
Assisted-by: Claude Opus 5.5
- - - - -
d686f4d2 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Define the labels of the NCG's comments
Of what anyone working with the NCG needs, this commit serves "The kind
of each statement in the NCG's comments, shown at the statement: a bug,
half-done work, a likely change or code meant to stay.", "What a comment
that does not show the kind of its statements does and does not claim."
and "How the statements on bugs, half-done work and likely changes
are kept true as the code changes."
Comments only; the generated code is the same.
Note [Labels in NCG comments], added to GHC.CmmToAsm, defines the labels
that the native code generator's comments put at the head
of a statement. The commits that follow label each statement they add,
and are read under this Note:
BUG wrong behaviour, a missing check or misleading code;
the statement says in short what it leads to and where
it is reached
WIP half-done work
TODO what is likely to change, correct or buggy; a bug marked
TODO alone is accepted for now and worked around
BUG TODO both, where both are to be stressed
no label what is meant to stay; a kept trade-off says why
A BUG statement names its consequence: wrong code, wrong debugging
information, a panic or another failed compilation, assembly
the assembler rejects, only slower or larger code, only a warning
from the assembler, only more C stack space, or only a misled reader.
The Note does not reach back to older comments: their TODO, ToDo, FIXME
and XXX predate its meanings, and an older comment that carries no label
makes no claim that the code is meant to stay.
The Note also says how the labels are kept true. A change to what
a labelled statement describes removes or rewrites the statement
in the same change; BUG and TODO gain the issue's number when the issue
is filed; and a git grep given in the Note lists the labelled lines.
Assisted-by: Claude Opus 5.5
- - - - -
af781803 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Document bugs and TODOs in the NCG's CFG and block layout
Of what anyone working with the NCG needs, this commit serves "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- postRegCFG in GHC.CmmToAsm (BUG: X86's allocMoreStack retargets every
jump into an entry block to the block it adds after it,
but addImmediateSuccessor moves only the entry block's own edges).
The CFG keeps an edge into the entry block from each block that jumps
there, though the code now jumps to the added block, and lacks
those blocks' edges to the added block. This costs only speed.
It is reached on x86-64, the only target with a CFG after register
allocation, where ncgAllocMoreStack adds blocks, that is, where
allocation needs more spill slots than maxSpillSlots. This rests
on master's code read. The linear allocator's fixup blocks were added
to the CFG before postRegCFG, and the added block is reachable,
through the entry block's edge to it. No reader of the CFG after
postRegCFG panics on these edges: shortcutWeightMap has no lookup
that panics; optimizeCFG's lookups take their blocks and edges
from the CFG itself; sanityCheckCfg compares blocks only; sequenceTop
looks up only the blocks the CFG's edges name, all of them blocks
of the code; and invertCondBranches takes an edge's information
as a Maybe and leaves a jump without it alone.
- build_mapping in shortcutBranches, GHC.CmmToAsm (BUG: under -g a block
that holds only its jump also holds the location and unwinding
information that -g adds, so it is kept where without -g
it is shorted). The code under -g jumps through the kept block,
and static prediction and block layout get another CFG than without
-g. This costs only speed and code size, under -g
and -fasm-shortcutting, not on AArch64 or Darwin. This rests
on master's code read: split matches a block of exactly one
instruction, and under -g on ELF targets other than AArch64
the instruction selectors put a LOCATION at the head of a block
with a source note, and under -g x86's gives a CmmUnwind an UNWIND,
neither of which emits code. On a development branch whose block
layout differed from master's, this changed the code of a probe
under -g.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG (BUG:
with tables next to code too, a block that is only a tail call's jump
to a label is shortcut away, and with it the edge A -> B). A's branch
has one target fewer in the CFG than in the code, and a loop whose
only exit was the lost edge has no exit in the CFG, so calcFreqs caps
its cycle probability. This costs only speed. It is reached on x86-64,
the only target with a CFG after register allocation,
under -fasm-shortcutting, not on Darwin. This rests on master's code
read: the removed block ends in a tail call and has no edges out
in the CFG; it leaves the code and the CFG together, and no block
becomes unreachable; and the readers of the CFG after
shortcutWeightMap, listed above for postRegCFG, do not panic
on a missing edge.
- getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28088: the CFG gets only
the blocks reachable from the entry, while instruction selection still
covers the blocks that cmmToCmm makes unreachable when, after the Cmm
pipeline has removed the unreachable blocks, it turns a branch
on a constant into a jump). Where such a block updates the CFG
at its current block, as X86's cmpxchg loop for an atomic and, or, xor
or nand does, the compiler panics with "getSuccessorEdges: Block does
not exist". This is reached on x86 and x86-64, at any optimisation
level: cmmToCmm turns a branch on a literal into a jump under every
flag, and the literal comes at -O0 from cmmToCmm's own constant
folding and at -O from sinking's. For x86-64 this rests on master's
code read and on runs of master's compiler under -dcmm-lint.
A procedure whose if (1 != 0) leaves a block with a fetch-and-and
unreachable panics with that message at -O0 and at -O, and also
at both with -finfo-table-map added, under which no CFG is kept after
instruction selection, as on i386. Where the branch tests a local set
to 1 instead, the procedure panics at -O and compiles at -O0. For i386
it rests on master's code read alone, no i386 compiler having
been run: getCfgProc builds the CFG for every target, i386 runs
the same selector (ncgX86 = ncgX86_64), and updateCfgNat forces each
update, so addImmediateSuccessor's call of getSuccessorEdges panics
during instruction selection whether or not a CFG is kept after it.
It rests also on ISSUE 28088's record.
A TODO citing ISSUE 20428, at livenessCfg
and at ncgEnableDeadCodeElimination, says that -finfo-table-map turns
dead code elimination off, and with it every use of the CFG
from the liveness pass on. No CFG is then kept after register
allocation, so the layout has neither static prediction nor the chains
of -fblock-layout-cfg, and lays the blocks out without weights.
Two Notes now say what -fcmm-static-pred changes:
Note [CFG based code layout], that the loop analysis and the refinement
of the weights run for the layout only under it;
and Note [CFG Edge Weights], that under it the weights become estimated
frequencies before the layout uses them.
A TODO in Note [Layout relevant edge weights],
in GHC.CmmToAsm.BlockLayout, citing ISSUE 27799, says that the modifier
on the edges of a conditional branch under-prices such an edge where
buildChains skips the branch's other edge because it would close
a cycle, as it can skip a loop latch's back edge.
At getCfg's case for a switch, master's comment says that the weight -1
given to every target of a switch with more than ten targets, a compiler
performance hack, keeps the layout from considering them. A TODO there
now says that the layout considers them nonetheless, and that what
the hack saves has not been measured.
Other TODOs say:
- at the Ord instance of CfgEdge, that edges of equal weight are ordered
by their labels, which carry no meaning for the layout;
- in Note [Updating the CFG during shortcutting], that where
shortcutting redirects an edge onto one already there, only one
EdgeInfo is kept and the weights are not summed;
- at allEdges' relevantWeight in sequenceChain, that it differs
from directEdges';
- at dropJumps, that a block that only jumps to the next one is left
as an empty label and a jump over it is kept.
In X86's genCondBranch', a comment says that the 3 added to the weight
of a floating-point comparison's false edge breaks layout ties toward
the side GHC.Cmm.ContFlowOpt arranges to fall through.
Assisted-by: Claude Opus 5.5
- - - - -
0543b8f0 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Document bugs and TODOs in static branch prediction and loop analysis
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, BUG TODO for a bug that is also likely to change,
WIP for half-done work, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- getCfg in GHC.CmmToAsm.CFG (BUG: after fixStgRegisters, a test
of CurrentTSO or CurrentNursery reads BaseReg and is tagged
HeapStackCheck). The exemptions of Note [Static Branch Prediction]
for heap and stack checks then apply to such a test, so its weights
are left unpredicted. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read. The tag
decides the code only through isHeapOrStackCheck, all of whose callers
are in staticBranchPrediction, which runs inside mkGlobalWeights.
mkGlobalWeights reaches the code through staticPredCfg, only
under -fcmm-static-pred, and otherwise only through the graph
allocator's spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28083 (an edge into the entry block is never a back edge,
as mkDomMap leaves the root out of every dominator set). A loop whose
head is the entry block is not found. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read
and ISSUE 28083's record. loopInfo's result reaches the code only
through static prediction and block layout: of its two callers,
loopLevels is never called, and mkGlobalWeights serves staticPredCfg,
under -fcmm-static-pred, and otherwise only the graph allocator's
spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28093 (a self loop is a back edge only where its block dominates
no other block). A block that jumps to itself and to an exit
it dominates, as cmpxchg_code's retry loop in GHC.CmmToAsm.X86.CodeGen
does, is not a loop. calcFreqs then takes the block for irreducible
and gives frequency 0 to it and to every block it dominates.
This costs only speed, on x86-64 under -fcmm-static-pred, by the same
path as the BUG of ISSUE 28083. This rests on master's code read,
on the record of ISSUE 28093, and on -ddump-cfg-weights of a loop
calling fetchOrIntArray#, compiled by a GHC built from 3d326d7d28
with changes outside the native code generator: the retry block's
edges and the loop's back edge weigh 0. Between 3d326d7d28
and the master commit this branch starts from, GHC.CmmToAsm.CFG
and cmpxchg_code are unchanged, and the dominator code loses only
a `return = pure`.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG (BUG: the back
edge rule supersedes a likely annotation in the Cmm as well). A branch
with both a back edge and another edge is predicted to take the back
edge, whatever its annotation says. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read:
staticBranchPrediction's case for a mix of back edges and other edges
reads no annotation.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG (BUG TODO:
a constructor-tag test is predicted like any other comparison,
its equal side unlikely). The prediction is wrong for the trees
of Data.Map and Data.Set, which declare Bin first: in a lookup,
the side that stays in the loop is predicted unlikely. This costs only
speed, on x86-64 under -fcmm-static-pred. It is accepted until
the knowledge of the likely side reaches the CFG, hence TODO as well.
This rests on master's code read.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG, its BUG (s1
is taken for the true side only where it is ltrue, the label
the branch was made with, which an edge no longer ends at once
the linear allocator's fixup block, by addNodesBetween,
or shortcutting, by shortcutWeightMap, has redirected it). Where
the redirected true edge's new target has the smaller label
of the two, each side gets the other's prediction, and the layout's
estimate takes the likely side for the unlikely one. This costs only
speed, on x86-64 under -fcmm-static-pred. This rests on master's code
read, and on a count over nofib's modules on a development branch
whose static prediction also predicts an inequality with a literal,
which found such branches inverted at -O2 and none at -O1.
- calcFreqs in GHC.CmmToAsm.CFG (BUG: mkGlobalWeights passes the loops
in the order of loopInfo's back edges, by label, and not by nesting).
An enclosing loop's pass can come before an inner loop's and read
the branch probability of an inner back edge where its cycle
probability belongs, which gives nested loops wrong cycle
probabilities. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read.
A WIP in Note [Static Branch Prediction] says that the paper's other
heuristics are stubs.
calcFreqs' comment on an irreducible block, "Rare we don't care", now
says what frequency such a block keeps and, as a TODO, that such blocks
are not rare, that the layout then ranks edges by frequencies that do
not add up, with a loop calling fetchOrIntArray#, compiled by the GHC
named under ISSUE 28093 above, for a case, and what summing their inflow
measured on a development branch.
Other TODOs say:
- in Note [Back edges in loopInfo], that findBackEdges, which
optHsPatterns uses for the back edge bonus, disagrees with loopInfo
on edges into the entry block, on back edges of irreducible cycles
and on self loops;
- at ohPredicts, that only MO_Eq is read, so the spelling
GHC.Cmm.ContFlowOpt leaves decides whether a test is predicted,
and that predicting a pointer-tag test spelt with MO_Ne as its MO_Eq
spelling is predicted was tried on a development branch and gained
nothing;
- at lehPredicts, that where a heap or stack check's call to the garbage
collector returns into the procedure, loopInfo takes the cycle through
that call for a loop: the heuristic then says nothing about a branch
into the checking block where that block is the loop's head, and takes
a branch towards a case alternative without such a check for a loop
exit where the head is the block choosing the alternative;
- at calcFreqs, that nothing checks its result, and that a check could
compare each block's frequency with the sum of the frequencies
on its in-edges, which the propagation departs from at some blocks,
among them an irreducible block, a loop head whose cycle probability
is capped, and the entry block;
- at loopMembers, that neither it nor loopLevels has a caller in GHC:
loopMembers since the graph allocator's spill costs, for which
it was added early in 2019, began that year to weight by block
frequencies instead, and loopLevels since it came with the loop
analysis that year.
A comment at optimizeCFG says that static prediction starts
from the weights optHsPatterns leaves, so that their adjustments carry
into the predicted probabilities, except where the back edge rule
replaces them.
Assisted-by: Claude Opus 5.5
- - - - -
319ac3c8 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Document bugs and TODOs in liveness and the register allocators
Of what anyone working with the NCG needs, this commit serves
"The invariants the code depends on.", "Where the code does something
other than what reading it suggests.", "Where the code is known
to behave wrongly or is half done.", "What each known bug leads to, such
as wrong code, a compiler panic or only slower code, and under which
flags and on which targets it is reached." and "Where the code is likely
to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- regAlloc in GHC.CmmToAsm.Reg.Graph (BUG: it hands ncgAllocMoreStack
slotsCount', the highest slot number, which counts the preallocated
slots, where the linear allocator gives only the slots beyond
maxSpillSlots): the preallocated slots are reserved a second time.
This costs C stack space, under -fregs-graph or -fregs-iterative,
on every target, and where a target's mkStackAllocInstr needs more
instructions for a larger amount, code at entry and exit: on AArch64
one instruction more for each 4095 bytes, on RISC-V, LoongArch
and PowerPC more past the range of an immediate, and on Windows x86-64
a call of ___chkstk_ms past 4 KB. This rests on master's code read.
Every target's allocMoreStack moves the stack pointer by the slots
it is given times spillSlotSize. The graph allocator can be chosen
for any target, and trivColorable covers x86, x86-64, PowerPC,
AArch64, RISC-V and LoongArch.
- pprSpillCostRecord in GHC.CmmToAsm.Reg.Graph.SpillCost (BUG: it binds
a SpillCostRecord as (reg, uses, defs, life), where the type's
comments give its fields as the writes, the reads and the lifetime).
Only the names are wrong: it prints the two counts in the record's
order, under no names, and their sum divided by the register's node
degree, and nothing in GHC calls it. This rests on master's code read:
slurpSpillCostInfo's incDefs fills the second field and incUses
the third.
- joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG: on x86
a floating-point == or /= test's block ends in two jumps that name one
target, genCondBranch's parity jump and a conditional or unconditional
one, and each is joined on its own). Where that target needs a fixup
block, each of the two jumps gets one, with the same moves, and both
are reachable. This costs only code size, on x86 and x86-64
under the linear allocator. This rests on master's code read
and on constructed Cmm compiled by master's compiler; no module
of nofib or of the compile benchmarks was found to show it. A fix
that shares the block where the two jumps' stack deltas agree,
the target's vregs have the same locations at both and no value moves
between two slots was written on a development branch and is left out.
- joinToTargets_again in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG:
once it has made a fixup block for a target and patched the jump to go
there, the destinations still to consider keep the target's later
occurrences, as a jump table lists a target once for each entry naming
it). Each later occurrence makes the same moves again, into a block
nothing jumps to, which is given an edge in the CFG, laid out
and emitted: dead code. This costs only code size, under the linear
allocator. This rests on master's code read: x86's jumpDestsOfInstr
lists a jump table's targets with their repetitions, and the other
targets with jump tables do likewise. Such a block was found in GHC's
own GHC.CmmToAsm.Dwarf.Constants and in none of nofib's
or the testsuite's modules.
- makeRegMovementGraph, handleComponent and makeMove
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, and the header
of GHC.CmmToAsm.Reg.Linear.StackMap (BUG, ISSUE 27638: since
ISSUE 26668 a virtual register whose format has outgrown its slot gets
new slots, so a jump can need a move between two slots of one
register): such a move ends in makeMove's panic, "makeMove: we don't
handle mem->mem moves". And where handleComponent's cyclic case moves
to an InBoth destination (BUG, a statement of its own, ISSUE 27638
reporting only the panic), the destination's slot is written only
if it is the slot spillR picks; otherwise it keeps a stale value,
which is wrong code where the slot is reloaded. Both are reached
under the linear allocator, where a virtual register's format grows
past 8 bytes, which only a vector format does, and so only on i386,
x86-64 and AArch64, the targets whose code generators take vectors
(checkVecCompatibility in GHC.StgToCmm.Prim; PowerPC's, RV64's
and LA64's stop with sorry on vectors). The first is reached on x86-64
at -O1 and -O2: master's compiler panics so on a function in which
a Double, also broadcast to a DoubleX2#, is live at a join of two arms
of a case that both load eleven Int#s and seventeen Doubles.
No program reaching the second is known. The first can be reached two
ways, by expandNode: a jump into a block that holds the virtual
register in another of its slots only, and a jump into a block
that holds it in a register and another slot, where makeMove loads
the register first. A fix cannot count on a spare register: nothing
keeps one free at a jump, and the block's entry assignment can hold
every allocatable register, on x86-64 the eleven integer registers
(rax, rbx, rcx, rdx, rsi, rdi, r8 to r11 and r14) and the sixteen
vector registers, the others being the stack pointer and
those of STG's Base, Sp, Hp and SpLim (freeReg
in compiler/CodeGen.Platform.h). This rests on master's code read,
ISSUE 27638's record and a run of master's compiler. The cyclic case
drops the InMem half of an InBoth destination (expandNode lists InReg
first) and writes only spillR's slot, which is getStackSlotFor's
newest slot of the virtual register and differs from the destination's
only after the register grew. And allocateRegsAndSpill frees
the register of an InBoth virtual register without a store,
so that its next use reloads the slot.
- livenessSCCs in GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 27619: Regs' Eq
compares the registers and not their formats, so the fixpoint can stop
before the formats recorded for a cycle's blocks converge): a vector
register can be recorded live at a format narrower than the value
it holds, and a write at that format then kills
it in minusCoveredRegs, which is wrong code. No program giving a wrong
result is known. This rests on master's code read and ISSUE 27619's
record, whose program shows a register recorded so.
- getSlotMap in slurpReloadCoalesce, GHC.CmmToAsm.Reg.Liveness (BUG:
it folds the slot maps of a block's predecessors from the empty map
with mergeSlotMaps, which keeps only the slots both maps hold).
The slot map on entry to a block is always empty, so a reload
is coalesced with a spill only inside one block. This costs only speed
and code size, under -fregs-graph or -fregs-iterative, on every
target. This rests on master's code read; buildGraph
in GHC.CmmToAsm.Reg.Graph is the only caller of slurpReloadCoalesce.
- maxRegWithFormat in GHC.CmmToAsm.Reg.Regs (BUG, ISSUE 27619: Format's
derived Ord compares a VecFormat's number of elements before their
format, ranking VecFormat 16 FmtInt8, 128 bits, above VecFormat 4
FmtDouble, 256 bits): it can keep the narrower of two formats.
Were one register read at both, a write at the narrower would kill
it in minusCoveredRegs, which is wrong code; whether any register
is read so is not known. This rests on master's code read
and ISSUE 27619's record.
The other statements, by part.
The linear allocator:
- Note [The first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, says that the first jump
into a block that the allocator processes records the block's entry
assignment, spilled values included, and that every later jump
conforms to it by fixup code. Its three TODOs are what follows
from that: a loop head recorded from a preheader that spilled
a loop-carried value has the value reloaded on every iteration,
and stored again by every back edge once the body has written it;
a return continuation and the procedure's entry that enter one loop
at two blocks record incompatible assignments (ISSUE 27800);
and the block that a failed heap or stack check returns to
from the garbage collector can be allocated before the hot path's jump
into the checking block and record that block's entry assignment,
as the order of allocation depends on no frequency. process' comment
cites the Note.
- Note [Unique order in the linear allocator],
in GHC.CmmToAsm.Reg.Linear, says, as a TODO, which decisions take
the order of the vregs' uniques as a ranking: the spill victim,
and the order in which saveClobberedTemps moves values out
of clobbered registers. It also says that the order decides
joinToTargets' fixup moves. The comments at those three folds cite it.
- Open issues get labels where the code behaves as they report: TODO
for ISSUE 27980, closed as a duplicate of ISSUE 27800,
at findPrefRealReg, for ISSUE 27981 at joinToTargets_first's release
of registers, and for ISSUE 26631 at saveClobberedTemps' choice
of a register; BUG for ISSUE 27638 at handleComponent, makeMove,
makeRegMovementGraph and StackMap's header, whose comments ruled out
a move between two stack slots, which ISSUE 26668 made possible.
- TODOs without an issue: raInsn's elimination of a move gives
the destination the source's register, whatever register an entry
assignment recorded for a block it is live into expects;
findPrefRealReg's preference is keyed by virtual register, while a Cmm
local is one virtual register over all its live ranges; and expandNode
stores a value InBoth at both ends of a jump into the slot
that already holds it.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap says that a stack slot
belongs to one virtual register for the whole procedure,
as getStackSlotFor takes new slots only at the next free one, which
only grows, and a register that outgrows its slot gets another,
keeping the first; that the fixups at a jump rely on this; and
that it costs stack, the slots of a procedure adding up over every
register spilled in it.
- Step (j) of the outline at the top of GHC.CmmToAsm.Reg.Linear,
re-adding a dead spilled register's stack slot to the free list,
is marked WIP: it is not done, as a StackMap never frees a slot.
- A comment at clobberRegs' filter says that frAllocateReg panics
on a register already allocated on AArch64, RISC-V and LoongArch.
- Three designs that a trial on a development branch found no gain
in are recorded beside the code they would change: handing out
the floating-point registers in descending order (at the TODO
for ISSUE 26631 in saveClobberedTemps), taking the entry block first
and then, after each SCC, an SCC holding a block whose entry
assignment is recorded (at the TODO for ISSUE 27800), and putting
fixup moves before an unconditional jump rather than in a block
of their own (in joinToTargets_again).
Liveness, in GHC.CmmToAsm.Reg.Liveness and GHC.CmmToAsm.Reg.Regs:
- The fixpoint of livenessSCCs says that it compares the whole map
at every round (TODO, ISSUE 27437), and that its steps are monotone,
so that a test comparing the formats too would reach a result
independent of the order in which the blocks are walked. Regs' Eq says
that it ignores formats (TODO, ISSUE 27619).
- The comment on the SCCs' order says that no block may fall through
before allocation, and liveDieRead's haddock that at a branch it also
holds the registers live into its targets only.
- A comment at computeLiveness' panic on SCCs out of reverse dependent
order says that, where sccBlocks has a CFG, a jump to a block missing
from the CFG reaches it too.
The graph allocator: in GHC.CmmToAsm.Reg.Graph.SpillCost, a WIP comment
says that the block frequencies scale only the counts of uses
and definitions, on which no spill choice depends, as spillCost_chaitin,
which would read them, is commented out.
Both allocators: a TODO at patchRegsOfInstr says that, as it maps
a register to a register, both allocators reload a spilled value
into a register for an instruction that reads it, even at its last read,
where an x86 instruction could read the stack slot.
Assisted-by: Claude Opus 5.5
- - - - -
58fcbf7b by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Document bugs and TODOs in code generators, DWARF and an unused module
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- getRegister' in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28126:
isNbitEncodeable 12 admits label offsets from -2048 to 2047, while
check_off in GHC.CmmToAsm.AArch64.Ppr accepts only 0 to 4095):
on AArch64, compiling a label at an offset from -2048 to -1 stops
with check_off's error, a pgmError,
"GHC.CmmToAsm.AArch64.Ppr.check_off : -8 is out of 12 bit"
for an offset of -8. Below -2048 the guard fails, and the next clause
adds the offset through a register. This rests on master's code read
(litToImm', ImmIndex, check_off), ISSUE 28126's record and a run
of master's x86-64 compiler given an AArch64 target description,
in which a Cmm load from a label less 8, at -O0 and at -O,
and plusAddr# of a string literal and -1#, at -O, stop
with check_off's error; nothing was run on AArch64.
- lower_CmmRegOff in GHC.CmmToAsm.Wasm.FromCmm and the cases
for CmmRegOff of getRegister' in GHC.CmmToAsm.RV64.CodeGen
and GHC.CmmToAsm.LA64.CodeGen, one BUG at each (the sum
is not truncated to a sub-word register's width, as each target's
general lowering of a sub-word MO_Add truncates its result,
and cmmMachOpFoldM in GHC.Cmm.Opt folds a sub-word register plus
a literal into a CmmRegOff at any width validOffsetRep allows). Where
an operation reads the bits above the width, this is wrong code:
on wasm32 a widening MO_UU_Conv of a sub-word value masks nothing,
and on RV64 and LA64 Note [Signed arithmetic on RISCV64] and LA64's
comment "Signed arithmetic on LoongArch64" keep a sub-word value
zero-extended between operations. This rests on master's code read
alone; nothing was run on these targets. On RV64 and LA64 an offset
that fits in 12 bits goes to the case of MO_Add for such a literal,
or on RV64 for a negative offset to that of MO_Sub, which does
not truncate either (on RV64 ISSUE 28133).
- getRegister''s case for CmmRegOff in GHC.CmmToAsm.X86.CodeGen (BUG:
neither mangleIndexTree nor add_int narrows the offset
to the register's width, and cmmMachOpFoldM's folds of literals
into a CmmRegOff sum them unnarrowed). For a 16-bit register whose
offset lies outside 16 bits, add_int's LEA, printed as an ADD
of an immediate where the result takes the operand's register, makes
the assembler warn that it shortened the immediate (addw $90000,%ax
for a 16-bit register plus three times 30000); the shortened immediate
gives the value meant, so this costs only the warning, on x86
and x86-64. An 8-bit register's sum takes an ADD whose immediate
litToImm narrows, an LEA printed as an LEA takes the offset
as a 32-bit displacement without a warning, and a wider register holds
any offset add_int is given. This rests on master's code read
(mangleIndexTree, add_code, add_int and the printing of an LEA
as an ADD in GHC.CmmToAsm.X86.Ppr), on master's compiler, whose
assembly for such a sum in Cmm made the assembler warn so, and on GNU
as given addw and leaw with such an immediate and displacement,
with and without --32: it warned of the addw alone and assembled both.
- getHiVirtualRegFromLo in GHC.Platform.Reg, pointed to from localReg64
and getNewReg64 in GHC.CmmToAsm.Monad and from genByteSwap
in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28125: the high half keeps
the number of the low half's unique): a 64-bit Cmm local and a 64-bit
NCG temporary with the same number share their high half, and where
both are live, writing one overwrites the other's high 32 bits.
This is wrong code on i386; 32-bit PowerPC, which uses the same
functions, was not tried. Equal numbers occur, as the NCG's uniques
count from 0 in each Haskell module (initDUniqSupply 'n' 0
in GHC.Driver.Main.Compile). In genByteSwap, equal high halves
with different low halves arise only so, and the branch for that case
swaps correctly. This rests on master's code read and ISSUE 28125's
record.
- verifyBasicBlock in GHC.CmmToAsm.X86.CodeGen (BUG: nothing checks
that a block of native code ends in a transfer of control;
this checks, in a DEBUG compiler, only that nothing but jumps follows
a jump). A block that did not end in one would run on into whichever
block the layout puts after it, which is wrong code; no instruction
selector is known to make such a block. This rests on master's code
read.
- getAmode in GHC.CmmToAsm.X86.CodeGen, three clauses (BUG, ISSUE 28105:
each can emit a displacement outside the signed 32-bit range: -i where
i = -2^31; an offset left unchecked; and an offset checked only
at shift 3, as && binds tighter than ||): where the displacement does
not fit, the x86-64 assembler rejects the module. This rests
on master's code read and ISSUE 28105's record.
- getAmode in GHC.CmmToAsm.X86.CodeGen, its clause for a register offset
plus a shift (BUG: nor is the offset narrowed to the register's
width). On i386 an offset outside 32 bits reaches the assembler, which
warns and shortens it modulo 2^32, to the address meant, so this costs
only the warning; on x86-64 such an offset is the BUG of ISSUE 28105
at the same clause. This rests on master's code read, nothing having
been compiled for i386, and on GNU as given such displacements
with --32, which it shortened with a warning and assembled.
- genPrim in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 27694: MO_UF_Conv's
genWordToFloat does not return the last block it adds, so a later
statement of the same Cmm block that splits its current block in turn,
as a second conversion does, moves the wrong block's edges): the CFG
lacks the edges of the jumps ending the Cmm block, and where
the linear allocator puts a fixup block on one of them,
addNodesBetween panics with "Can't find weight for edge that should
have one", the panic of ISSUE 27915. Where the second conversion's
last block is a lone jump, shortcutting (-fasm-shortcutting,
on at -O2, never on Darwin) cuts it, and shortcutWeightMap drops
its out-edges, which in the CFG are the only edges into the first
conversion's blocks; the blocks stay in the CFG, unreachable
from the entry and with edges, and classifyEdges
in GHC.Data.Graph.Directed, which findBackEdges calls
for optHsPatterns, panics with "Failed to classify edge of CFG -
not not timed" on an edge out of them. Both are reached on x86-64,
the only target for which backendMaintainsCfg holds, and
not under -finfo-table-map, under which no pass after instruction
selection gets a CFG. -dasm-lint does not catch the missing edges
first, as sanityCheckCfg compares the CFG's blocks with the code's
and not its edges. This rests on master's code read, the records
of ISSUE 27694 and ISSUE 27915, a run of master's compiler on a loop
with two word2Double# in one Cmm block: it panics in addNodesBetween
at -O, at -O2 and at -O -dasm-lint, and compiles at -O0
and at -O -fregs-graph, as the graph allocator makes no fixup blocks;
and a run of master's compiler on two word2Double# in one Cmm block
ahead of a loop: it panics in classifyEdges at -O2, at -O2 -dasm-lint,
at -O2 -fregs-graph, at -O1 -fasm-shortcutting
and at -O0 -fasm-shortcutting, and compiles at -O0, at -O1
and at -O2 -fno-asm-shortcutting.
- addDefaultUnwindings in GHC.CmmToAsm.Dwarf (BUG: it gives every
unwinding table that does not name Sp the rule Sp has
at the procedure's entry, and the table that X86's addSpUnwindings
adds where the C stack pointer moves, as around a C call, names MachSp
alone). Up to the block's next table that names Sp, DWARF gives
the canonical frame address by Sp's rule at entry: after a C call,
rbp+0 on x86-64, where before the call it can be another offset, such
as rbp+16. A debugger unwinding from there finds the wrong frame.
This is reached under -g on ELF targets, on x86 and x86-64,
as ncgDwarfUnwindings holds on ELF targets under -g
and addSpUnwindings is X86's. This rests on master's code read
and on readelf's reading of the frame table of an object that master's
compiler made under -g.
The other statements:
- backendMaintainsCfg in GHC.CmmToAsm.BlockLayout said that i386 should
work but is untested. It now says, as WIP, that i386 is left out
because it is untested and its iselExpr64 splits blocks for 64-bit
shifts without adding them to the CFG.
- genPrim's comment says that its remaining cases add no blocks, while
MO_UF_Conv's genWordToFloat adds blocks: the BUG above stands there.
- mkRegRegMoveInstr in GHC.CmmToAsm.X86.Instr says that its move clears
the upper part of the register. A TODO says that for a float
or a double it is MOV FF64, printed movsd, which keeps
the destination's upper half.
- invertCondBranches inverts a jump only after an integer comparison.
A TODO says that maybeInvertCond's complement on the flags is as sound
after a floating-point one.
- pprBasicBlock in GHC.CmmToAsm.X86.Ppr aligns, past a procedure's
start, only a block with an info table (TODO, ISSUE 27668).
- condIntCode' tests a value against zero even on a path where
the instruction computing it has set ZF and SF from it, as on the back
edge of a loop that counts down: it sees only the comparison,
and another path into the test, such as the loop's entry, may set
no flags. Only a condition that reads ZF and SF alone could use
the flags of a dec, which writes OF and leaves CF where TEST clears
both (TODO, ISSUE 27738).
- GHC.CmmToAsm.Reg.Graph.Coalesce says, as a TODO, that no module
imports it, and that its pass, which ran before allocation, has had
no caller since 2007, when it was taken out of the pipeline in favour
of the coalescing that GHC.Data.Graph.Color.colorGraph does.
Assisted-by: Claude Opus 5.5
- - - - -
bec09c62 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
State the NCG's norms and where a branch's likely side is known
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Norms of the NCG], in GHC.CmmToAsm, states two norms that GHC's
own documents and testsuite hold the native code generator to, and what
each means for a change. Under -fobject-determinism the output
is bit-for-bit the same for the same inputs, so an order taken
from uniques is a question for review. The testsuite passes -dcmm-lint,
so a test written in Cmm must be one that Cmm lint accepts.
Note [Where a branch's likely side is known], in GHC.CmmToAsm.CFG, says
where the code generator learns which side of a conditional branch
is likely: where the branch is made, as for heap and stack checks;
upstream, and not carried down, for constructor-tag tests; and nowhere,
for the rest, to which static prediction applies its heuristics. It also
states the trade-offs kept with that knowledge, each with its reason:
conditions inverted so that the true side falls through even where
the false side is likely, and edges across calls left out when chains
are built.
Note [Norms of the NCG] points to it.
Assisted-by: Claude Opus 5.5
- - - - -
0f84d1a7 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Rewrite the NCG's overview Note
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe.", "Which targets go
through the NCG, which of its parts each target uses, and what the NCG
takes from the Cmm pipeline, StgToCmm and the RTS.", "The NCG's passes
in the order they run, and what each requires of the one before.",
"The invariants the code depends on." and "What the tests cover and what
they do not: which targets CI runs natively, which paths have few
or no tests, and which performance test exercises which pass."
Comments only; the generated code is the same.
Note [Native code generator], the module header of GHC.CmmToAsm, named
CmmStmts, cmmCodeGen, targetDoubleSize and smStablePtrTable, which
no longer exist, and machine-independent optimisations "defined below",
which are in GHC.Cmm.GenericOpt. This commit rewrites it. The Note now
says:
- which targets go through cmmNativeGen, that wasm32 has a generator
of its own, and which back end the other targets get by default;
- what the Cmm pipeline hands over, and what the NCG takes from StgToCmm
and the RTS;
- the interfaces through which the machine-independent parts access
a target, and what only some targets have;
- the passes, in the order cmmNativeGen runs them, with the flags
that turn them on and the dump flags that show their output, and,
at step 4, what instruction selection must ensure;
- where the NCG's uniques come from;
- what the assembler and the linker do after it;
- the flags, testsuite directories and benchmarks for working
on the NCG.
For detail it cites the Notes and labelled statements of the preceding
commits.
Assisted-by: Claude Opus 5.5
- - - - -
7cf93325 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Propose two principles for the NCG
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Proposed principles of the NCG], in GHC.CmmToAsm, puts two
principles to GHC's developers and says that the native code generator
does not keep them yet:
- correctness first: semantic correctness is not traded for a measured
gain that an incorrect form gives by accident, until a form with both
has been looked for and the trade agreed in review;
- one TODO set: a departure from correctness that is left in place
is marked TODO, as a member of one set that is accepted for now
and re-investigated together.
No other commit cites the Note, so this commit can be dropped
on its own.
Assisted-by: Claude Opus 5.5
- - - - -
c67b3e50 by Mikolaj Konarski at 2026-11-16T19:35:08+01:00
Add a README to the NCG's directory
Of what anyone working with the NCG needs, this commit serves "An order
in which to read the NCG's Notes.", "One place where the terms the NCG's
comments use are defined.", "One small function followed through
the NCG's dumps, in the order of its passes.", "Which parts of the NCG
were examined for bugs, half-done work and likely changes, and which
were not.", "The invariants the code depends on." and "How to find
the pass at fault for a miscompilation or a compiler panic, and how
to reduce the case to a Cmm test."
Documentation only; the generated code is the same.
compiler/GHC/CmmToAsm/README.md is a way in for anyone working
with the native code generator, whether reading its output and dumps,
tracking a fault to its pass, reviewing or making a change,
or maintaining it. It says what to read and what to do, and for each
fact about the code it cites a Note or a comment by name. Its sections:
- Where to start reading: three Notes of GHC.CmmToAsm, then Notes
on the passes, each with its module, in the overview's order.
- Vocabulary: the terms the NCG's comments use without defining them,
each with where it is defined or used.
- Finding the pass at fault for a wrong result or a panic: the oracles
to compare with, the flags that switch a pass off or swap it,
the lints, and how to cut a case down to a Cmm test.
- One function through the dumps: a small loop compiled at -O on x86-64,
with an excerpt for each dump flag in the overview's list of passes
but -ddump-asm-regalloc-stages, which prints nothing under the linear
allocator.
- Reviewing a change: the invariants the code depends on, as questions
by kind of change, each citing the Note or comment that states it.
- What the labelled statements cover: which parts of the NCG they
were first written from, and which were left out.
The excerpts are cut from the dumps of one compilation by a compiler
built from master: each of their lines but "..." is a line of a dump,
in the dump's order, with tabs replaced by spaces. Every Note, function,
module, flag and path the README names exists at this commit.
The overview, Note [Native code generator], now ends by pointing
to the README.
Assisted-by: Claude Opus 5.5
- - - - -
38 changed files:
- compiler/GHC/Cmm/Node.hs
- compiler/GHC/Cmm/Reg.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Dwarf.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/CodeGen.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PIC.hs
- + compiler/GHC/CmmToAsm/README.md
- compiler/GHC/CmmToAsm/RV64/CodeGen.hs
- compiler/GHC/CmmToAsm/Reg/Graph.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Base.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Coalesce.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/AArch64.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Base.hs
- compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- compiler/GHC/CmmToAsm/Reg/Regs.hs
- compiler/GHC/CmmToAsm/Reg/Target.hs
- compiler/GHC/CmmToAsm/Wasm/FromCmm.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToAsm/X86/Regs.hs
- compiler/GHC/Driver/Config/CmmToAsm.hs
- compiler/GHC/Platform/Reg.hs
- compiler/GHC/Platform/Reg/Class.hs
- compiler/GHC/StgToCmm/Monad.hs
- docs/users_guide/using-optimisation.rst
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/42f5e2e85f3dd6f6de4d079fdb252b…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/42f5e2e85f3dd6f6de4d079fdb252b…
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/jeltsch/haddock-without-pit-use
by Wolfgang Jeltsch (@jeltsch) 16 Nov '26
by Wolfgang Jeltsch (@jeltsch) 16 Nov '26
16 Nov '26
Wolfgang Jeltsch pushed new branch wip/jeltsch/haddock-without-pit-use at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/jeltsch/haddock-without-pit-u…
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/dcoutts/posix-cond-vars] 44 commits: testsuite: Fix T17088 flakiness and restore bug coverage
by Duncan Coutts (@dcoutts) 16 Nov '26
by Duncan Coutts (@dcoutts) 16 Nov '26
16 Nov '26
Duncan Coutts pushed to branch wip/dcoutts/posix-cond-vars at Glasgow Haskell Compiler / GHC
Commits:
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).
- - - - -
06055b48 by Duncan Coutts at 2026-11-16T11:31:47+00:00
Make clock_gettime required on posix platforms
It was defined in POSIX.1-2001 and has been manditory since
POSIX.1-2008. We will rely on CLOCK_MONOTONIC for the RTS-internal
monotonic time source.
On macOS it has been available since 10.12 released in 2016 (and EOL
2019). We already have 11.0 as our minimum version for which we build
binaries (MACOSX_DEPLOYMENT_TARGET=11.0).
Also we must now drop the workaround from #12858 that would make the CI
configuration invoke configure in a way that would always fail to detect
clock_gettime (since obviously now we must detect it). Re-generate the
gitlab jobs files for the benefit of CI.
- - - - -
9d32830c by Duncan Coutts at 2026-11-16T11:31:47+00:00
Simplify time code based on assuming defined(HAVE_CLOCK_GETTIME)
No need to fall back to gettimeofday or times
- - - - -
8368c51a by Duncan Coutts at 2026-11-16T11:31:47+00:00
Use clock_gettime CLOCK_REALTIME for getUnixEpochTime
- - - - -
680c8fa7 by Duncan Coutts at 2026-11-16T11:31:47+00:00
Simplify getCurrentThreadCPUTime to use clock_gettime
except on Solaris where it doesn't work.
In particular, this means we now use it on macOS. It apparently works
there from 10.12 onwards.
We drop the check for clock_getcpuclockid which is linux-specific,
archaic, and in any case isn't necessarily fatal.
- - - - -
d6e18c62 by Duncan Coutts at 2026-11-16T11:31:47+00:00
Remove now-redundant darwin time code
- - - - -
caba06bc by Duncan Coutts at 2026-11-16T11:31:47+00:00
Simplify getProcessCPUTime to use clock_gettime CLOCK_PROCESS_CPUTIME_ID
It would be nice to check during startup using sysconf that this is
really available. Unfortunately this doesn't actually work on macOS: it
reports via sysconf that it is not available, when actually it is.
Great.
- - - - -
ffe43c12 by Duncan Coutts at 2026-11-16T15:32:50+00:00
Tidy up posix time headers in various places
Also remove the definition of CLOCK_ID in HsBase.h, where CLOCK_ID does
not appear to be used at all. And we're going to tweak the clock
definitions soon so we don't want these parallel definitions getting
out of sync.
- - - - -
d24e4749 by Duncan Coutts at 2026-11-16T15:32:50+00:00
Split getPageFaults out into OSStats.{h,c}
Strictly speaking it never had any business living with the time
functions. It was merely convenience. Moving it out allows the remainder
to use PosixSource.h (at least on posix).
- - - - -
25424341 by Duncan Coutts at 2026-11-16T15:32:50+00:00
Move getProcessTimes to its only use site
Historically getProcessTimes made sense, since the main way to get the
elapsed time would also get the cpu time as well. After recent time code
simplification on posix then in all platforms it is just the pair of
getProcessCPUTime and getProcessElapsedTime separarely. So we can remove
three identical implementations and move it to be a local function in
Stats.c where it is used.
- - - - -
f9907b0f by Duncan Coutts at 2026-11-16T15:32:50+00:00
Make the "get the time" functions more consistent
We had:
Time getProcessElapsedTime(void); // pulbic
StgWord64 getMonotonicNSec(void); // public
void getUnixEpochTime(StgWord64 *sec, StgWord32 *nsec); // internal
These don't follow any naming convention, nor any common type
convention.
Now we have:
Time getMonotonicTime(void); // internal
Time getWallClockTime(void); // internal
StgWord64 getMonotonicNSec(void); // public compat alias
Time getProcessElapsedTime(void); // public compat alias
Now the two main ones use a common representation: Time which is int64_t
nanoseconds since the epoch. And their names better reflect that they
use different clocks: a monotonic clock, or a real time / wall clock.
We keep getMonotonicNSec and getProcessElapsedTime as aliases for
getMonotonicTime(). They are still used in ghc-internal.
Future directions: export the new ones from ghc-internal and base, and
provide clock precision functions. Provide more clocks, like coarse
ones: faster but less precise.
- - - - -
2768c693 by Duncan Coutts at 2026-11-16T15:32:50+00:00
Improve win32 implementation of getMonotonicNSec
We don't need the fallback GetTickCount method.
Fixes #14233
- - - - -
4f823be2 by Duncan Coutts at 2026-11-16T15:32:50+00:00
Improve win32 implementation of getUnixEpochTime
We can now use GetSystemTimePreciseAsFileTime, which is supported from
Windows 8 onwards. This is the recommendation from MS.
- - - - -
000af422 by Duncan Coutts at 2026-11-16T15:32:50+00:00
Remove initializeTimer
It is now a no-op on all platforms.
- - - - -
a135d12e by Duncan Coutts at 2026-11-16T15:32:50+00:00
Refine the meaning of the main monotonic clock and add a high-res clock
We now define the monotonic clock to prioritise accuracy, and to be
steady: which implies it must count time while the system is suspended.
In particular this means that on Linux we must use CLOCK_BOOTTIME.
Since different use cases want different trade-offs (where such
trade-offs are necessary on some platforms) we also add support for a
high resolution clock. This is defined to be as precise as possible, but
not necessarily steady or accurate over long timer periods. This is the
appropriate choice for measuring the time of short-running actions. We
don't get use this one, but will do in susbequent changes.
- - - - -
ac7acd67 by Duncan Coutts at 2026-11-16T15:57:11+00:00
Switch some RTS uses from getMonotonicTime to getHighResolutionTime
Wherever we want to measure the duration of relatively short time
intervals then we want getHighResolutionTime rather than
getMonotonicTime. In particular this is appropriate for RTS stats,
profiling and the eventlog timestamps.
In practice this is hardly a change in behaviour compared to the prior
implementation of getMonotonicNSec/getProcessElapsedTime. On Linux and
FreeBSD it used CLOCK_MONOTONIC, and still does (or the more-or-less
equivalent CLOCK_BOOTTIME on Linux). On macOS it used the low-level
mach_absolute_time and now uses the equivalent CLOCK_UPTIME_RAW for
getHighResolutionTime. While on Windows getHighResolutionTime uses
QueryPerformanceCounter, the same as previously.
- - - - -
b2447b43 by Duncan Coutts at 2026-11-16T15:57:11+00:00
Add support for macOS non-standard clock_gettime_nsec_np
It's a way to get what we want with fewer conversions, so plausibly
faster.
- - - - -
fc1c1bc9 by Duncan Coutts at 2026-11-16T15:57:11+00:00
Remove unused rtsSleep utility
- - - - -
1f64668d by Duncan Coutts at 2026-11-16T15:57:11+00:00
Add a changelog entry for the clock_gettime changes
- - - - -
330c6ac3 by Duncan Coutts at 2026-11-16T17:12:57+00:00
Rename timedWaitCondition to waitConditionTimedRelative
We will add an absolute variant, at least for posix.
- - - - -
9fe4900c by Duncan Coutts at 2026-11-16T17:22:47+00:00
Improve waitConditionTimedRelative
We really want to use the monotonic clock, to avoid discontinuities due
to the real time clock, but support for the monotonic clock for cond var
timed waits is patchy. There are newer posix functions that provide it,
but many platforms don't support these yet and have some of their own
non-standard extensions.
Furthermore, the existing timed wait code is pretty unpleasent: it uses
both a static and a dynamic test to try to use a monotonic clock, but if
either test fails then it falls back to a realtime clock. This is ok ish
for implementing relative timeouts, but we will also want to support
absolute timeouts (in the monotonic clock). Fortunately the static test
can go because we now require clock_gettime unconditionally. The dynamic
test is weird: it presumes the existence of platforms supporting
pthread_condattr_setclock but not supporting CLOCK_MONOTONIC. There do
not appear to be any such platforms (which is unsurprising since
clock_gettime predates pthread_condattr_setclock).
- - - - -
d2fb7d09 by Duncan Coutts at 2026-11-16T17:25:06+00:00
Add waitConditionTimedAbsolute for posix platforms
We add support for a waitConditionTimedAbsolute using an absolute
timeout using the monotonic clock. This will be useful later for
flexible timers, where the timeout is most naturally expressed as an
absolute (monotonic) time.
We don't currently provide this for Win32 because we do not need it for
flexible timers there: win32 uses a different timer implementation
entirely.
If more portable use cases arise, we could provide this on win32 but it
would have to do some time conversions to implement it in terms of a
relative-time timed wait (with only millisecond precision).
- - - - -
e1646706 by Duncan Coutts at 2026-11-16T17:26:55+00:00
Remove wrong initialiser INIT_COND_VAR, and add MUTEX_STATIC_INIT
INIT_COND_VAR was a static initialiser for condition variables. It had a
bogus implementation on Windows (though it could have a correct one,
namely CONDITION_VARIABLE_INIT). On posix, although
PTHREAD_COND_INITIALIZER exists, our own Condition abstraction relies
sometimes on setting attributes, which cannot be done statically (in a
portable way).
INIT_COND_VAR was also unused, so removing it is easy.
Add MUTEX_STATIC_INIT which is a (hopefully) correct portable static
initialiser for mutexes. This is convenient to avoid initSubsystemFoo
calls that do nothing but initialise mutexes.
- - - - -
166 changed files:
- .gitignore
- .gitlab/ci.sh
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/jobs.yaml
- + changelog.d/T9809-timer-manager-contention
- + changelog.d/clock_gettime
- + changelog.d/make-depends-deprecate-doMkDependHS
- + changelog.d/make-depends-json
- + changelog.d/make-depends-multiple-home-units
- + changelog.d/remove-long-deprecated-flags.md
- + changelog.d/stage3-cross-bindists
- compiler/GHC/CmmToC.hs
- compiler/GHC/CoreToStg.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Driver/Session/Units.hs
- compiler/GHC/Parser/Errors/Ppr.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Stg/Make.hs
- compiler/GHC/Types/Tickish.hs
- compiler/GHC/Utils/Json.hs
- 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/pragmas.rst
- docs/users_guide/ghc.rst
- + docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/profiling.rst
- docs/users_guide/separate_compilation.rst
- − docs/users_guide/what_glasgow_exts_does.rst
- ghc/Main.hs
- hadrian/src/BindistConfig.hs
- hadrian/src/Oracles/Setting.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Settings/Builders/RunTest.hs
- hadrian/src/Settings/Packages.hs
- libraries/base/tests/.gitignore
- + libraries/base/tests/T9809.hs
- libraries/base/tests/all.T
- libraries/ghc-internal/include/HsBase.h
- libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs
- m4/fp_check_pthreads.m4
- + rts/GetTime.c
- rts/GetTime.h
- rts/Linker.c
- rts/LinkerInternals.h
- + rts/OSStats.h
- rts/RtsStartup.c
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.c
- rts/Stats.c
- rts/configure.ac
- rts/eventlog/EventLog.c
- rts/include/Rts.h
- rts/include/rts/GetTime.h
- rts/include/rts/OSThreads.h
- + rts/include/rts/RtsSymbols.h
- rts/include/rts/Time.h
- rts/linker/PEi386.c
- rts/posix/Clock.h
- rts/posix/GetTime.c
- + rts/posix/OSStats.c
- rts/posix/OSThreads.c
- + rts/posix/OSThreads.h
- rts/posix/Poll.c
- rts/posix/Select.c
- rts/posix/SelectBis.c
- rts/posix/Ticker.c
- rts/posix/Timeout.c
- rts/rts.cabal
- rts/sm/GC.c
- rts/wasm/GetTime.c
- + rts/wasm/OSStats.c
- rts/win32/GetTime.c
- + rts/win32/OSStats.c
- rts/win32/OSThreads.c
- testsuite/README.md
- testsuite/config/ghc
- testsuite/driver/junit.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/driver/testutil.py
- testsuite/mk/test.mk
- testsuite/tests/cmm/should_run/all.T
- 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/mkdepend01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend01/A.hs
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu03.dep-json
- 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/ghci/linking/T25155_iserv_main.c
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/SkolemOccursLoop.hs
- testsuite/tests/perf/compiler/large-project/all.T
- + testsuite/tests/perf/compiler/large-project/large-project-mhu.sh
- testsuite/tests/primops/should_run/all.T
- testsuite/tests/rts/T17088.hs
- testsuite/tests/rts/TimeoutQueue.c
- testsuite/tests/rts/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
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Parser.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/bbbe8f42eb7d2be6a0b5ce18092e54…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/bbbe8f42eb7d2be6a0b5ce18092e54…
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/fendor/one-shot-no-eps] WIP: one-shot uses home loader state
by Hannes Siebenhandl (@fendor) 16 Nov '26
by Hannes Siebenhandl (@fendor) 16 Nov '26
16 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
0f928d0a by Hannes Siebenhandl at 2026-11-16T18:00:45+01:00
WIP: one-shot uses home loader state
- - - - -
21 changed files:
- compiler/GHC/Core/Opt/Monad.hs
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Core/Opt/Simplify.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Rules.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Linker/Deps.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Utils/Env.hs
- compiler/GHC/Tc/Utils/Instantiate.hs
- compiler/GHC/Tc/Utils/Monad.hs
- compiler/GHC/Unit/External.hs
- compiler/GHC/Unit/Home/PackageTable.hs
- compiler/GHC/Unit/Module/Env.hs
Changes:
=====================================
compiler/GHC/Core/Opt/Monad.hs
=====================================
@@ -16,8 +16,8 @@ module GHC.Core.Opt.Monad (
-- ** Reading from the monad
getModule,
- initRuleEnv, getExternalRuleBase,
- getDynFlags, getPackageFamInstEnv,
+ initRuleEnv, getExternalRuleBase, getLazyHomeRuleBase,
+ getDynFlags, getPackageFamInstEnv, getLazyHomeFamInstEnv,
getInteractiveContext,
getUniqTag,
getNamePprCtx, getSrcSpanM,
@@ -44,7 +44,7 @@ import GHC.Driver.Errors ( reportDiagnostic, reportError )
import GHC.Driver.Config.Diagnostic ( initDiagOpts )
import GHC.Driver.Env
-import GHC.Core.Rules ( RuleBase, RuleEnv, mkRuleEnv )
+import GHC.Core.Rules ( RuleBase, RuleEnv, mkRuleEnv, unionRuleBase )
import GHC.Core.Opt.Stats ( SimplCount, zeroSimplCount, plusSimplCount )
import GHC.Types.Annotations
@@ -73,6 +73,9 @@ import Data.Dynamic
import Data.Maybe (listToMaybe)
import Control.Monad
import Control.Applicative ( Alternative(..) )
+import GHC.Unit.Home.PackageTable (HomePackageTable)
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import GHC.Core.FamInstEnv
data FloatOutSwitches = FloatOutSwitches
{ floatOutLambdas :: Maybe Int -- ^ Just n <=> float lambdas to top level, if
@@ -248,7 +251,10 @@ instance HasHscEnv CoreM where
getHscEnv = read cr_hsc_env
getHomeRuleBase :: CoreM RuleBase
-getHomeRuleBase = read cr_rule_base
+getHomeRuleBase = do
+ hptRules <- read cr_rule_base
+ extraRules <- getLazyHomeRuleBase
+ pure $ hptRules `unionRuleBase` extraRules
initRuleEnv :: ModGuts -> CoreM RuleEnv
initRuleEnv guts
@@ -259,6 +265,9 @@ initRuleEnv guts
getExternalRuleBase :: CoreM RuleBase
getExternalRuleBase = eps_rule_base <$> get_eps
+getLazyHomeRuleBase :: CoreM RuleBase
+getLazyHomeRuleBase = get_hpt HomePackageTable.hptLoadedRuleBase
+
getNamePprCtx :: CoreM NamePprCtx
getNamePprCtx = read cr_name_ppr_ctx
@@ -302,11 +311,20 @@ getInteractiveContext = hsc_IC <$> getHscEnv
getPackageFamInstEnv :: CoreM PackageFamInstEnv
getPackageFamInstEnv = eps_fam_inst_env <$> get_eps
+getLazyHomeFamInstEnv :: CoreM FamInstEnv
+getLazyHomeFamInstEnv = get_hpt HomePackageTable.hptLoadedFamInstEnv
+
get_eps :: CoreM ExternalPackageState
get_eps = do
hsc_env <- getHscEnv
liftIO $ hscEPS hsc_env
+get_hpt :: (HomePackageTable -> IO a) -> CoreM a
+get_hpt f = do
+ hsc_env <- getHscEnv
+ a <- liftIO $ f $ hsc_HPT hsc_env
+ pure a
+
{-
************************************************************************
* *
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -449,8 +449,9 @@ doCorePass pass guts = do
dflags <- getDynFlags
us <- getUniqueSupplyM
p_fam_env <- getPackageFamInstEnv
+ l_fam_env <- getLazyHomeFamInstEnv
let platform = targetPlatform dflags
- let fam_envs = (p_fam_env, mg_fam_inst_env guts)
+ let fam_envs = (p_fam_env `unionFamInstEnv` l_fam_env, mg_fam_inst_env guts)
let updateBinds f = return $ guts { mg_binds = f (mg_binds guts) }
let updateBindsM f = f (mg_binds guts) >>= \b' -> return $ guts { mg_binds = b' }
let updateBindsAndRulesM f = f (mg_binds guts) (mg_rules guts) >>= \(b',r') -> return $ guts { mg_binds = b', mg_rules = r' }
=====================================
compiler/GHC/Core/Opt/Simplify.hs
=====================================
@@ -30,7 +30,7 @@ import GHC.Utils.Logger as Logger
import GHC.Utils.Outputable
import GHC.Utils.Constants (debugIsOn)
-import GHC.Unit.Env ( UnitEnv, ueEPS )
+import GHC.Unit.Env ( UnitEnv, ueEPS, ue_hpt )
import GHC.Unit.External
import GHC.Unit.Module.ModGuts
@@ -44,6 +44,7 @@ import GHC.Types.Unique.FM
import Control.Monad
import Data.Foldable ( for_ )
+import GHC.Unit.Home.PackageTable (hptLoadedRuleBase, HomePackageTable)
{-
************************************************************************
@@ -63,13 +64,14 @@ data SimplifyExprOpts = SimplifyExprOpts
simplifyExpr :: Logger
-> ExternalUnitCache
+ -> HomePackageTable
-> SimplifyExprOpts
-> CoreExpr
-> IO CoreExpr
-- ^ Simplify an expression using 'simplExprGently'.
--
-- See 'simplExprGently' for details.
-simplifyExpr logger euc opts expr
+simplifyExpr logger euc hpt opts expr
= withTiming logger (text "Simplify [expr]") (const ()) $
do { eps <- eucEPS euc ;
; let fam_envs = ( eps_fam_inst_env eps
@@ -81,7 +83,8 @@ simplifyExpr logger euc opts expr
base_env = mkSimplEnv (se_mode opts) fam_envs
top_env_cfg = se_top_env_cfg opts
read_eps_rules = eps_rule_base <$> eucEPS euc
- read_ruleenv = updExternalPackageRules emptyRuleEnv <$> read_eps_rules
+ read_home_rules = hptLoadedRuleBase hpt
+ read_ruleenv = (\ home_rules eps_rules -> updExternalPackageRules (updHomePackageRules emptyRuleEnv home_rules) eps_rules) <$> read_home_rules <*> read_eps_rules
; let sz = exprSize expr
@@ -285,8 +288,11 @@ simplifyPgm logger unit_env name_ppr_ctx opts
; read_eps_rules :: IO PackageRuleBase
; read_eps_rules = eps_rule_base <$> ueEPS unit_env
+ ; read_home_rules :: IO RuleBase
+ ; read_home_rules = hptLoadedRuleBase (ue_hpt unit_env)
+
; read_rule_env :: IO RuleEnv
- ; read_rule_env = updExternalPackageRules base_rule_env <$> read_eps_rules
+ ; read_rule_env = (\ home_rules eps_rules -> updExternalPackageRules (updHomePackageRules base_rule_env home_rules) eps_rules) <$> read_home_rules <*> read_eps_rules
; fam_envs = (eps_fam_inst_env eps, fam_inst_env)
; simpl_env = mkSimplEnv mode fam_envs } ;
=====================================
compiler/GHC/Core/Opt/Specialise.hs
=====================================
@@ -854,7 +854,8 @@ spec_import env callers dict_binds cis@(CIS fn _)
-- We keep doing this in case we "page-fault in"
-- more rules as we go along
; eps_rules <- getExternalRuleBase
- ; let rule_env = se_rules env `updExternalPackageRules` eps_rules
+ ; home_rules <- getLazyHomeRuleBase
+ ; let rule_env = se_rules env `updHomePackageRules` home_rules `updExternalPackageRules` eps_rules
-- ; debugTraceMsg (text "specImport1" <+> vcat
-- [ text "function:" <+> ppr fn
=====================================
compiler/GHC/Core/Rules.hs
=====================================
@@ -13,8 +13,9 @@ module GHC.Core.Rules (
-- ** RuleBase, RuleEnv
RuleBase, RuleEnv(..), mkRuleEnv, emptyRuleEnv,
- updExternalPackageRules, addLocalRules, updLocalRules,
- emptyRuleBase, mkRuleBase, extendRuleBaseList,
+ updExternalPackageRules, updHomePackageRules,
+ addLocalRules, updLocalRules,
+ emptyRuleBase, mkRuleBase, extendRuleBaseList, unionRuleBase,
pprRuleBase,
-- ** Checking rule applications
@@ -398,6 +399,10 @@ extendRuleBase rule_base rule
lookupRuleBase :: RuleBase -> Unique -> Maybe [CoreRule]
lookupRuleBase = lookupUFM
+unionRuleBase :: RuleBase -> RuleBase -> RuleBase
+unionRuleBase
+ = plusUFM
+
pprRuleBase :: RuleBase -> SDoc
pprRuleBase rules = pprUFM rules $ \rss ->
vcat [ pprRules (tidyRules emptyTidyEnv rs)
@@ -433,6 +438,10 @@ updExternalPackageRules :: RuleEnv -> RuleBase -> RuleEnv
updExternalPackageRules rule_env eps_rules
= rule_env { re_eps_rules = eps_rules }
+updHomePackageRules :: RuleEnv -> RuleBase -> RuleEnv
+updHomePackageRules rule_env eps_rules
+ = rule_env { re_home_rules = (re_home_rules rule_env ) `unionRuleBase` eps_rules }
+
updLocalRules :: RuleEnv -> [CoreRule] -> RuleEnv
-- Completely over-ride the local rules in RuleEnv
updLocalRules rule_env local_rules
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -98,6 +98,7 @@ import GHC.Builtin.Modules( gHC_PRIM )
import Data.IORef
import qualified Data.Set as Set
import GHC.Types.Name.Reader (ExactRdrName(..))
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env hsc = do
@@ -348,10 +349,11 @@ prepareAnnotations hsc_env mb_guts = do
home_pkg_anns <- fromMaybe (hugAllAnns (hsc_unit_env hsc_env))
$ uncurry (hugAnnsBelow hsc_env)
. get_mod <$> mb_guts
+ more_home_pkg_anns <- HomePackageTable.hptLoadedAnnEnv $ hsc_HPT hsc_env
let
other_pkg_anns = eps_ann_env eps
!ann_env = maybe id plusAnnEnv mb_this_module_anns $!
- plusAnnEnv home_pkg_anns other_pkg_anns
+ plusAnnEnv home_pkg_anns (plusAnnEnv more_home_pkg_anns other_pkg_anns)
return ann_env
-- | Find the 'TyThing' for the given 'Name' by using all the resources
@@ -374,12 +376,9 @@ lookupTypeInPTE hsc_env pte name = ty
then mkHomeModule (hsc_home_unit hsc_env) (moduleName (nameModule name))
else nameModule name
- ty = if isOneShot (ghcMode (hsc_dflags hsc_env))
- -- in one-shot, we don't use the HPT
- then return $! lookupNameEnv pte name
- else HUG.lookupHugByModule mod hpt >>= \case
- Just hm -> pure $! lookupNameEnv (md_types (hm_details hm)) name
- Nothing -> pure $! lookupNameEnv pte name
+ ty = HUG.lookupHugByModule mod hpt >>= \case
+ Just hm -> pure $! lookupNameEnv (md_types (hm_details hm)) name
+ Nothing -> pure $! lookupNameEnv pte name
-- | Find the 'ModIface' for a 'Module', searching in both the loaded home
-- and external package module information
=====================================
compiler/GHC/Driver/Main/Passes.hs
=====================================
@@ -1546,7 +1546,7 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do
let unit_env = hsc_unit_env hsc_env
let simplify_expr_opts = initSimplifyExprOpts dflags ic
- simpl_expr <- simplifyExpr logger (ue_eps unit_env) simplify_expr_opts ds_expr
+ simpl_expr <- simplifyExpr logger (ue_eps unit_env) (ue_hpt unit_env) simplify_expr_opts ds_expr
-- Create a unique temporary binding
--
=====================================
compiler/GHC/HsToCore/Monad.hs
=====================================
@@ -131,6 +131,7 @@ import GHC.Data.OrdList
import Data.IORef
import GHC.IO.Unsafe (unsafeInterleaveIO)
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{-
************************************************************************
@@ -385,6 +386,7 @@ mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
-- ToDo: what becomes of the values put into these ref-cells?
; eps <- liftIO $ hscEPS hsc_env
+ ; extra_matches <- liftIO $ HomePackageTable.hptLoadedCompleteMatches $ hsc_HPT hsc_env
; let unit_env = hsc_unit_env hsc_env
this_mod = tcg_mod tcg_env
type_env = tcg_type_env tcg_env
@@ -406,7 +408,7 @@ mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
-- Relevant test case: MultiLayerModulesTH_Make, which regresses
-- in allocations by ~5% if we don't do this.
traverse (lookupCompleteMatch type_env hsc_env) =<<
- localAndImportedCompleteMatches tcg_comp_env eps
+ localAndImportedCompleteMatches (tcg_comp_env ++ extra_matches) eps
; tcm_plugins <- liftIO $ readIORef (tcg_plugins tcg_env)
-- Pass the running 'TcM' plugins to the desugarer, so that the pattern-match
@@ -469,6 +471,7 @@ initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds
; statics_var <- newIORef nilOL
; known_key_maps_var <- newIORef Nothing
; eps <- liftIO $ hscEPS hsc_env
+ ; extra_matches <- liftIO $ HomePackageTable.hptLoadedCompleteMatches $ hsc_HPT hsc_env
; let unit_env = hsc_unit_env hsc_env
type_env = typeEnvFromEntities ids tycons patsyns fam_insts
ptc = initPromotionTickContext (hsc_dflags hsc_env)
@@ -476,7 +479,7 @@ initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds
bindsToIds (Rec binds) = map fst binds
ids = concatMap bindsToIds binds
; ds_complete_matches <- traverse (lookupCompleteMatch type_env hsc_env) =<<
- localAndImportedCompleteMatches local_complete_matches eps
+ localAndImportedCompleteMatches (local_complete_matches ++ extra_matches) eps
; let
tcm_plugins = emptyTcMPluginsRun
envs = mkDsEnvs unit_env this_mod rdr_env type_env
@@ -842,8 +845,8 @@ dsGetFamInstEnvs :: DsM FamInstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
dsGetFamInstEnvs
- = do { eps <- getEps; env <- getGblEnv
- ; return (eps_fam_inst_env eps, ds_fam_inst_env env) }
+ = do { eps <- getEps; env <- getGblEnv; lazy_env <- queryHpt HomePackageTable.hptLoadedFamInstEnv
+ ; return (eps_fam_inst_env eps, ds_fam_inst_env env `unionFamInstEnv` lazy_env) }
dsGetMetaEnv :: DsM (NameEnv DsMetaVal)
dsGetMetaEnv = do { env <- getLclEnv; return (dsl_meta env) }
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -152,6 +152,13 @@ import Data.Function ((&))
import Data.Map ( toList )
import System.FilePath
import System.Directory
+import GHC.Types.DefaultEnv (DefaultEnv)
+import GHC.Core (CoreRule)
+import GHC.Unit.Module.ModDetails (ModDetails(..))
+import GHC.Unit.Home.ModInfo (HomeModInfo(..), emptyHomeModInfoLinkable)
+import qualified Data.Set as Set
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import Control.Applicative ((<|>))
{- *********************************************************************
@@ -513,8 +520,9 @@ importDecl name
; Succeeded _ -> do
-- Now look it up again; this time we should find it
- { eps <- getEps
- ; case lookupTypeEnv (eps_PTE eps) name of
+ { eps <- getEps -- @fendor: DONE
+ ; loaderTypeEnv <- queryHpt HomePackageTable.hptLoadedTypeEnv
+ ; case lookupTypeEnv loaderTypeEnv name <|> lookupTypeEnv (eps_PTE eps) name of
Just thing -> return $ Succeeded thing
Nothing -> return $ Failed $
Can'tFindNameInInterface name
@@ -789,7 +797,9 @@ loadInterface doc_str mod from
_ -> do {
-- READ THE MODULE IN
- ; read_result <- case wantHiBootFile mhome_unit eps mod from of
+ ; hpt <- getHpt
+ ; hls <- liftIO (hptLoaderState hpt)
+ ; read_result <- case wantHiBootFile mhome_unit hls mod from of
Failed err -> return (Failed err)
Succeeded hi_boot_file -> do
hsc_env <- getTopEnv
@@ -818,108 +828,37 @@ loadInterface doc_str mod from
let
loc_doc = text (ml_hi_file loc)
in
- initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $
-
- dontLeakTheHUG $ do
-
- -- Load the new ModIface into the External Package State
- -- Even home-package interfaces loaded by loadInterface
- -- (which only happens in OneShot mode; in Batch/Interactive
- -- mode, home-package modules are loaded one by one into the HPT)
- -- are put in the EPS.
- --
- -- The main thing is to add the ModIface to the PIT, but
- -- we also take the
- -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules,
- -- out of the ModIface and put them into the big EPS pools
-
- -- NB: *first* we do tcIfaceDecls, so that the provenance of all the locally-defined
- --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
- -- If we do loadExport first the wrong info gets into the cache (unless we
- -- explicitly tag each export which seems a bit of a bore)
-
- -- Crucial assertion that checks if you are trying to load a HPT module into the EPS.
- -- If you start loading HPT modules into the EPS then you get strange errors about
- -- overlapping instances.
- ; massertPpr
- ((isOneShot (ghcMode (hsc_dflags hsc_env)))
- || moduleUnitId mod `notElem` hsc_all_home_unit_ids hsc_env
- || mod == gHC_PRIM)
- (text "Attempting to load home package interface into the EPS" $$ ppr (HUG.allUnits hug) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod))
- ; ignore_prags <- goptM Opt_IgnoreInterfacePragmas
- ; new_eps_decls <- tcIfaceDecls ignore_prags (mi_decls iface)
- ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
- ; new_eps_defaults <- tcIfaceDefaults mod (mi_defaults iface)
- ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
- ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
- ; new_eps_anns <- tcIfaceAnnotations (mi_anns iface)
- ; new_eps_complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
- ; purged_hsc_env <- getTopEnv
-
- ; let final_iface = iface
- & set_mi_decls (panic "No mi_decls in PIT")
- & set_mi_insts (panic "No mi_insts in PIT")
- & set_mi_defaults (panic "No mi_defaults in PIT")
- & set_mi_fam_insts (panic "No mi_fam_insts in PIT")
- & set_mi_rules (panic "No mi_rules in PIT")
- & set_mi_anns (panic "No mi_anns in PIT")
- & set_mi_simplified_core (panic "No mi_simplified_core in PIT")
-
- bad_boot = mi_boot iface == IsBoot
- && isJust (lookupKnotVars (if_rec_types gbl_env) mod)
- -- Warn against an EPS-updating import
- -- of one's own boot file! (one-shot only)
- -- See Note [Loading your own hi-boot file]
-
- -- Create an IO action that loads and compiles bytecode from Core
- -- bindings.
+ initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $ do
+
+ ; if fromMaybe False $ fmap (`isHomeModule` mod) mhome_unit -- TODO @fendor: horrible code
+ then do -- TODO @fendor: document that we don't want/need 'dontLeakTheHUG' here
+ massertPpr (moduleUnitId mod `Set.member` hsc_all_home_unit_ids hsc_env)
+ (text "Attempting to non-home package interface into the Home Loader State" $$ ppr (HUG.allUnits $ hsc_HUG hsc_env) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod))
+ tcParts <- tcPartsOfTheIface mod iface
+ addModIfacePartsToHpt gbl_env mod loc iface tcParts
+ else dontLeakTheHUG $ do
+ -- Load the new ModIface into the External Package State
--
- -- See Note [Interface Files with Core Definitions]
- add_bytecode old
- | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls)
- = extendModuleEnv old mod action
- -- Don't add an entry if the iface doesn't have 'extra_decls'
- -- so 'get_link_deps' knows that it should load object code.
- | otherwise
- = old
-
- ; warnPprTrace bad_boot "loadInterface" (ppr mod) $
- updateEps_ $ \ eps ->
- if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface
- then eps
- else if bad_boot
- -- See Note [Loading your own hi-boot file]
- then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls }
- else
- eps {
- eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
- eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
- eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
- eps_rule_base = extendRuleBaseList (eps_rule_base eps)
- new_eps_rules,
- eps_complete_matches
- = eps_complete_matches eps ++ new_eps_complete_matches,
- eps_inst_env = extendInstEnvList (eps_inst_env eps)
- new_eps_insts,
- eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
- new_eps_fam_insts,
- eps_ann_env = extendAnnEnvList (eps_ann_env eps)
- new_eps_anns,
- eps_mod_fam_inst_env
- = let
- fam_inst_env =
- extendFamInstEnvList emptyFamInstEnv
- new_eps_fam_insts
- in
- extendModuleEnv (eps_mod_fam_inst_env eps)
- mod
- fam_inst_env,
- eps_stats = addEpsInStats (eps_stats eps)
- (length new_eps_decls)
- (length new_eps_insts)
- (length new_eps_rules),
- eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults
- }
+ -- The main thing is to add the ModIface to the PIT, but
+ -- we also take the
+ -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules,
+ -- out of the ModIface and put them into the big EPS pools
+
+ -- NB: *first* we do tcIfaceDecls, so that the provenance of all the locally-defined
+ --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
+ -- If we do loadExport first the wrong info gets into the cache (unless we
+ -- explicitly tag each export which seems a bit of a bore)
+
+ -- Crucial assertion that checks if you are trying to load a HPT module into the EPS.
+ -- If you start loading HPT modules into the EPS then you get strange errors about
+ -- overlapping instances.
+
+ massertPpr
+ (moduleUnitId mod `Set.notMember` hsc_all_home_unit_ids hsc_env
+ || mod == gHC_PRIM)
+ (text "Attempting to load home package interface into the EPS" $$ ppr (HUG.allUnits $ hsc_HUG hsc_env) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod))
+ tcParts <- tcPartsOfTheIface mod iface
+ addModIfacePartsToEps gbl_env mod loc iface tcParts
; -- invoke plugins with *full* interface, not final_iface, to ensure
-- that plugins have access to declarations, etc.
@@ -927,6 +866,134 @@ loadInterface doc_str mod from
; return (Succeeded res)
}}}}
+tcPartsOfTheIface :: Module -> ModIface -> IfL ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], CompleteMatches)
+tcPartsOfTheIface mod iface = do
+ ignore_prags <- goptM Opt_IgnoreInterfacePragmas
+ new_eps_decls <- tcIfaceDecls ignore_prags (mi_decls iface)
+ new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
+ new_eps_defaults <- tcIfaceDefaults mod (mi_defaults iface)
+ new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
+ new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
+ new_eps_anns <- tcIfaceAnnotations (mi_anns iface)
+ new_eps_complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
+ pure
+ ( new_eps_decls
+ , new_eps_insts
+ , new_eps_defaults
+ , new_eps_fam_insts
+ , new_eps_rules
+ , new_eps_anns
+ , new_eps_complete_matches
+ )
+
+addModIfacePartsToHpt :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToHpt gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) = do
+ ; hsc_env <- getTopEnv
+ ; let details = ModDetails
+ { md_types = mkNameEnv new_eps_decls
+ , md_exports = mi_exports iface
+ , md_defaults = new_eps_defaults
+ , md_insts = mkInstEnv new_eps_insts
+ , md_fam_insts = new_eps_fam_insts
+ , md_rules = new_eps_rules
+ , md_anns = new_eps_anns
+ , md_complete_matches = new_eps_complete_matches
+ }
+ ; let final_iface = iface
+ & set_mi_decls (panic "No mi_decls in HomeLoaderState")
+ & set_mi_insts (panic "No mi_insts in HomeLoaderState")
+ & set_mi_defaults (panic "No mi_defaults in HomeLoaderState")
+ & set_mi_fam_insts (panic "No mi_fam_insts in HomeLoaderState")
+ & set_mi_rules (panic "No mi_rules in HomeLoaderState")
+ & set_mi_anns (panic "No mi_anns in HomeLoaderState")
+ & set_mi_simplified_core (panic "No mi_simplified_core in HomeLoaderState")
+
+ bad_boot = mi_boot iface == IsBoot
+ && isJust (lookupKnotVars (if_rec_types gbl_env) mod)
+ -- Warn against an HPT-updating import
+ -- of one's own boot file! (one-shot only)
+ -- See Note [Loading your own hi-boot file]
+
+ ; warnPprTrace bad_boot "loadInterface" (ppr mod) $ do
+ hpt <- getHpt
+ -- Create an IO action that loads and compiles bytecode from Core
+ -- bindings.
+ --
+ -- See Note [Interface Files with Core Definitions]
+ let lazy_bytecode = loadIfaceByteCode hsc_env iface loc (mkNameEnv new_eps_decls)
+ liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
+ liftIO $ addOnDemandHomeModule hpt mod final_iface bad_boot (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) lazy_bytecode
+
+addModIfacePartsToEps :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) = do
+ ; purged_hsc_env <- getTopEnv
+
+ ; let final_iface = iface
+ & set_mi_decls (panic "No mi_decls in PIT")
+ & set_mi_insts (panic "No mi_insts in PIT")
+ & set_mi_defaults (panic "No mi_defaults in PIT")
+ & set_mi_fam_insts (panic "No mi_fam_insts in PIT")
+ & set_mi_rules (panic "No mi_rules in PIT")
+ & set_mi_anns (panic "No mi_anns in PIT")
+ & set_mi_simplified_core (panic "No mi_simplified_core in PIT")
+
+ bad_boot = mi_boot iface == IsBoot
+ && isJust (lookupKnotVars (if_rec_types gbl_env) mod)
+ -- Warn against an EPS-updating import
+ -- of one's own boot file! (one-shot only)
+ -- See Note [Loading your own hi-boot file]
+
+ -- Create an IO action that loads and compiles bytecode from Core
+ -- bindings.
+ --
+ -- See Note [Interface Files with Core Definitions]
+ add_bytecode old
+ | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls)
+ = extendModuleEnv old mod action
+ -- Don't add an entry if the iface doesn't have 'extra_decls'
+ -- so 'get_link_deps' knows that it should load object code.
+ | otherwise
+ = old
+ ; let mhome_unit = ue_homeUnit (hsc_unit_env purged_hsc_env)
+ ; warnPprTrace bad_boot "loadInterface" (ppr mod) $
+ updateEps_ $ \ eps ->
+ if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface
+ then eps
+ else if bad_boot
+ -- See Note [Loading your own hi-boot file]
+ then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls }
+ else
+ eps {
+ eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
+ eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
+ eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
+ eps_rule_base = extendRuleBaseList (eps_rule_base eps)
+ new_eps_rules,
+ eps_complete_matches
+ = eps_complete_matches eps ++ new_eps_complete_matches,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps)
+ new_eps_insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
+ new_eps_fam_insts,
+ eps_ann_env = extendAnnEnvList (eps_ann_env eps)
+ new_eps_anns,
+ eps_mod_fam_inst_env
+ = let
+ fam_inst_env =
+ extendFamInstEnvList emptyFamInstEnv
+ new_eps_fam_insts
+ in
+ extendModuleEnv (eps_mod_fam_inst_env eps)
+ mod
+ fam_inst_env,
+ eps_stats = addEpsInStats (eps_stats eps)
+ (length new_eps_decls)
+ (length new_eps_insts)
+ (length new_eps_rules),
+ eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults
+ }
+
+
{- Note [Loading your own hi-boot file]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally speaking, when compiling module M, we should not
@@ -1142,10 +1209,10 @@ moduleFreeHolesPrecise doc_str mod
return (Succeeded (renameFreeHoles ifhs insts))
Failed err -> return (Failed err)
-wantHiBootFile :: Maybe HomeUnit -> ExternalPackageState -> Module -> WhereFrom
+wantHiBootFile :: Maybe HomeUnit -> HomeLoaderState -> Module -> WhereFrom
-> MaybeErr MissingInterfaceError IsBootInterface
-- Figure out whether we want Foo.hi or Foo.hi-boot
-wantHiBootFile mhome_unit eps mod from
+wantHiBootFile mhome_unit hls mod from
= case from of
ImportByUser usr_boot
| usr_boot == IsBoot && notHomeModuleMaybe mhome_unit mod
@@ -1164,8 +1231,8 @@ wantHiBootFile mhome_unit eps mod from
-- We never import boot modules from other packages!
| otherwise
- -> case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of
- Just (GWIB { gwib_isBoot = is_boot }) ->
+ -> case hlsIsBoot hls (toUnitId <$> mod) of
+ Just is_boot ->
Succeeded is_boot
Nothing ->
Succeeded NotBoot
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -93,6 +93,7 @@ import GHC.ByteCode.Serialize (ModuleByteCode, gbc_hash)
import GHC.Unit.Home.Graph (lookupHugByModule)
import GHC.Unit.Home.ModInfo (HomeModLinkable(..), HomeModInfo (..))
import GHC.Linker.Types (linkableParts)
+import GHC.Unit.Home.PackageTable
{-
-----------------------------------------------
@@ -427,7 +428,8 @@ checkVersions hsc_env mod_summary iface self_recomp
-- case we'll compile the module from scratch anyhow).
when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- ; updateEps_ $ \eps -> eps { eps_is_boot = mkModDeps $ dep_boot_mods (mi_deps iface) }
+ ; hpt <- getHpt
+ ; liftIO $ hlsSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface))
}
; recomp <- checkList [checkModUsage (hsc_FC hsc_env) u
| u <- mi_sr_usages self_recomp]
=====================================
compiler/GHC/IfaceToCore.hs
=====================================
@@ -137,6 +137,7 @@ import Language.Haskell.Syntax.BooleanFormula (BooleanFormula)
import Language.Haskell.Syntax.BooleanFormula qualified as BF(BooleanFormula(..))
import Language.Haskell.Syntax.Extension (NoExtField (NoExtField))
import GHC.Builtin.KnownKeys (ioTyConKey)
+import GHC.Unit.Home.PackageTable
{-
This module takes
@@ -631,12 +632,13 @@ tcHiBootIface hsc_src mod
-- current module, which either means a module loop (not
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
- do { eps <- getEps
- ; case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of
+ do { hpt <- getHpt
+ ; hls <- liftIO $ hptLoaderState hpt
+ ; case hlsIsBoot hls (toUnitId <$> mod) of
-- The typical case
Nothing -> return NoSelfBoot
-- error cases
- Just (GWIB { gwib_isBoot = is_boot }) -> case is_boot of
+ Just is_boot -> case is_boot of
IsBoot ->
let diag = Can'tFindInterface err
(LookingForHiBoot mod)
=====================================
compiler/GHC/Linker/Deps.hs
=====================================
@@ -157,8 +157,8 @@ get_link_deps opts pls maybe_normal_osuf span mods = do
else homeModInfoObject hmi <|> homeModInfoByteCode hmi
get_linkable osuf mod -- A home-package module
- = HUG.lookupHugByModule mod (ue_home_unit_graph unit_env) >>= \case
- Just mod_info -> adjust_linkable (expectJust (homeModLinkable mod_info))
+ = lookupHomeLinkable mod (ue_home_unit_graph unit_env) >>= \ case
+ Just home_linkable -> adjust_linkable home_linkable
Nothing -> do
-- It's not in the HPT because we are in one shot mode,
-- so use the Finder to get a ModLocation...
@@ -175,6 +175,10 @@ get_link_deps opts pls maybe_normal_osuf span mods = do
maybe (fallback_no_bytecode home_unit mod) pure from_bc
_ -> fallback_no_bytecode home_unit mod
where
+ lookupHomeLinkable mod hug =
+ HUG.lookupHugByModule mod hug >>= \case
+ Just mod_info -> pure $ homeModLinkable mod_info
+ Nothing -> pure Nothing
fallback_no_bytecode home_unit mod = do
let fc = ldFinderCache opts
=====================================
compiler/GHC/Linker/Loader.hs
=====================================
@@ -668,6 +668,7 @@ findWholeCoreBindings hsc_env mod = do
loadInterface (text "get_reachable_nodes" <+> parens (ppr mod))
mod ImportBySystem
EPS {eps_iface_bytecode} <- hscEPS hsc_env
+
sequence (lookupModuleEnv eps_iface_bytecode mod)
=====================================
compiler/GHC/Tc/Instance/Family.hs
=====================================
@@ -57,6 +57,8 @@ import Data.Function ( on )
import qualified GHC.LanguageExtensions as LangExt
import Data.List (sortOn)
import qualified GHC.Unit.Home.Graph as HUG
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import Control.Applicative ((<|>))
{- Note [The type family instance consistency story]
@@ -407,8 +409,9 @@ getFamInsts hpt_fam_insts mod
| Just env <- lookupModuleEnv hpt_fam_insts mod = return env
| otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod)
; eps <- getEps
+ ; hpt_extra_mod_fam_insts <- queryHpt HomePackageTable.hptLoadedModFamInstEnv
; return (expectJust $
- lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
+ lookupModuleEnv hpt_extra_mod_fam_insts mod <|> lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
where
doc = ppr mod <+> text "is a family-instance module"
@@ -615,7 +618,8 @@ addLocalFamInst (home_fie, my_fis) fam_inst
-- by the current module, rather than every instance
-- we've ever seen. Fixing this is part of #13102.
; eps <- getEps
- ; let inst_envs = (eps_fam_inst_env eps, home_fie)
+ ; extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv
+ ; let inst_envs = (eps_fam_inst_env eps `unionFamInstEnv` extra, home_fie)
home_fie' = extendFamInstEnv home_fie fam_inst
-- Check for conflicting instance decls and injectivity violations
@@ -948,7 +952,7 @@ tcGetFamInstEnvs :: TcM FamInstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
tcGetFamInstEnvs
- = do { eps <- getEps; env <- getGblEnv
+ = do { eps <- getEps; env <- getGblEnv; !extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv
; let !pkg_env = eps_fam_inst_env eps
!home_env = tcg_fam_inst_env env
- ; return (pkg_env, home_env) }
+ ; return (pkg_env, home_env `unionFamInstEnv` extra) }
=====================================
compiler/GHC/Tc/Module.hs
=====================================
@@ -157,7 +157,6 @@ import GHC.Types.SourceFile
import qualified GHC.LanguageExtensions as LangExt
import GHC.Unit.Env as UnitEnv
-import GHC.Unit.External
import GHC.Unit.Types
import GHC.Unit.State
import GHC.Unit.Home
@@ -192,6 +191,7 @@ import qualified Data.Map as M
import Data.Foldable ( for_ )
import Data.Traversable ( for )
import Data.IORef( newIORef )
+import GHC.Unit.Home.PackageTable (hlsSetBootInfo)
{-
************************************************************************
@@ -513,7 +513,8 @@ tcRnImports hsc_env import_decls
-- visible to loadHiBootInterface in tcRnSrcDecls,
-- and any other incrementally-performed imports
; when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- updateEps_ $ \eps -> eps { eps_is_boot = imp_boot_mods imports }
+ ; hpt <- getHpt
+ ; liftIO $ hlsSetBootInfo hpt (imp_boot_mods imports)
}
-- Update the gbl env
=====================================
compiler/GHC/Tc/Utils/Env.hs
=====================================
@@ -152,6 +152,7 @@ import Control.Monad
import Data.IORef
import Data.List ( intercalate )
import qualified Data.List.NonEmpty as NE
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{- *********************************************************************
* *
@@ -385,7 +386,8 @@ tcGetClsDefaults :: [Module] -> TcM [DefaultEnv]
tcGetClsDefaults mods = do
hug <- hsc_HUG <$> getTopEnv
module_env_defaults <- eps_defaults <$> getEps
- liftIO $ mapMaybeM (lookupClsDefault hug module_env_defaults) mods
+ more_env_defaults <- queryHpt HomePackageTable.hptLoadedDefaults
+ liftIO $ mapMaybeM (lookupClsDefault hug (module_env_defaults `plusModuleEnv` more_env_defaults)) mods
lookupClsDefault :: HomeUnitGraph -> ModuleEnv DefaultEnv -> Module -> IO (Maybe DefaultEnv)
lookupClsDefault hug module_env_defaults mod =
@@ -398,8 +400,9 @@ tcGetInstEnvs :: TcM InstEnvs
-- and the home-pkg inst env (includes module being compiled)
tcGetInstEnvs = do { eps <- getEps
; env <- getGblEnv
+ ; extra <- queryHpt HomePackageTable.hptLoadedInstEnv
; return (InstEnvs { ie_global = eps_inst_env eps
- , ie_local = tcg_inst_env env
+ , ie_local = tcg_inst_env env `unionInstEnv` extra
, ie_visible = tcVisibleOrphanMods env }) }
-- Illegal term-level use of type things
=====================================
compiler/GHC/Tc/Utils/Instantiate.hs
=====================================
@@ -88,6 +88,7 @@ import Data.List ( mapAccumL )
import qualified Data.List.NonEmpty as NE
import Control.Monad( when, unless )
import Data.Function ( on )
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{-
************************************************************************
@@ -922,6 +923,7 @@ addLocalInst (home_ie, my_insts) ispec
-- 'dups' are those 'matches' that are equal to the new one
; isGHCi <- getIsGHCi
; eps <- getEps
+ ; extra_inst_env <- queryHpt HomePackageTable.hptLoadedInstEnv
; tcg_env <- getGblEnv
-- In GHCi, we *override* any identical instances
@@ -933,7 +935,7 @@ addLocalInst (home_ie, my_insts) ispec
global_ie = eps_inst_env eps
inst_envs = InstEnvs { ie_global = global_ie
- , ie_local = home_ie'
+ , ie_local = home_ie' `unionInstEnv` extra_inst_env
, ie_visible = tcVisibleOrphanMods tcg_env }
-- Check for inconsistent functional dependencies
@@ -945,6 +947,13 @@ addLocalInst (home_ie, my_insts) ispec
; let (_tvs, cls, tys) = instanceHead ispec
(matches, _, _) = lookupInstEnv False inst_envs cls tys
dups = filter (identicalClsInstHead ispec) (map fst matches)
+ ; traceRn "addLocalInst 0" (ppr ispec)
+ ; traceRn "addLocalInst 1" (ppr home_ie)
+ ; traceRn "addLocalInst 2" (ppr my_insts)
+ ; traceRn "addLocalInst 3" (ppr matches)
+ ; traceRn "addLocalInst 4" (ppr dups)
+ ; traceRn "addLocalInst 5" (ppr global_ie)
+ ; traceRn "addLocalInst 6" (ppr extra_inst_env)
; unless (null dups) $
dupInstErr ispec (head dups)
=====================================
compiler/GHC/Tc/Utils/Monad.hs
=====================================
@@ -30,7 +30,7 @@ module GHC.Tc.Utils.Monad(
getEpsVar,
getEps,
updateEps, updateEps_,
- getHpt, getEpsAndHug,
+ getHpt, queryHpt, getEpsAndHug,
-- * Initialising TcM plugins
TcMPluginHandling(..),
@@ -261,6 +261,7 @@ import Control.Monad.Catch ( bracket_, finally, onException, mask, mask_, MonadC
import Data.Foldable (traverse_)
import Data.IORef
import qualified Data.Map as Map
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{-
************************************************************************
@@ -740,6 +741,11 @@ updateEps_ upd_fn = updateEps (\eps -> (upd_fn eps, ()))
getHpt :: TcRnIf gbl lcl HomePackageTable
getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
+queryHpt :: (HomePackageTable -> IO a) -> TcRnIf gbl lcl a
+queryHpt f = do
+ hpt <- getHpt
+ liftIO $ f hpt
+
getEpsAndHug :: TcRnIf gbl lcl (ExternalPackageState, HomeUnitGraph)
getEpsAndHug = do { env <- getTopEnv; eps <- liftIO $ hscEPS env
; return (eps, hsc_HUG env) }
@@ -2740,8 +2746,9 @@ getCompleteMatchesTcM
= do { hsc_env <- getTopEnv
; eps <- liftIO $ hscEPS hsc_env
; tcg_env <- getGblEnv
+ ; extra_matches <- queryHpt HomePackageTable.hptLoadedCompleteMatches
; let tcg_comps = tcg_complete_match_env tcg_env
- ; liftIO $ localAndImportedCompleteMatches tcg_comps eps
+ ; liftIO $ localAndImportedCompleteMatches (tcg_comps ++ extra_matches) eps
}
localAndImportedCompleteMatches :: CompleteMatches -> ExternalPackageState -> IO CompleteMatches
=====================================
compiler/GHC/Unit/External.hs
=====================================
@@ -71,8 +71,7 @@ eucEPS = readIORef . euc_eps
initExternalPackageState :: ExternalPackageState
initExternalPackageState = EPS
- { eps_is_boot = emptyInstalledModuleEnv
- , eps_PIT = emptyPackageIfaceTable
+ { eps_PIT = emptyPackageIfaceTable
, eps_free_holes = emptyInstalledModuleEnv
, eps_PTE = emptyTypeEnv
, eps_iface_bytecode = emptyModuleEnv
@@ -101,19 +100,6 @@ initExternalPackageState = EPS
-- their interface files
data ExternalPackageState
= EPS {
- eps_is_boot :: !(InstalledModuleEnv ModuleNameWithIsBoot),
- -- ^ In OneShot mode (only), home-package modules
- -- accumulate in the external package state, and are
- -- sucked in lazily. For these home-pkg modules
- -- (only) we need to record which are boot modules.
- -- We set this field after loading all the
- -- explicitly-imported interfaces, but before doing
- -- anything else
- --
- -- The 'ModuleName' part is not necessary, but it's useful for
- -- debug prints, and it's convenient because this field comes
- -- direct from 'GHC.Tc.Utils.imp_dep_mods'
-
eps_PIT :: !PackageIfaceTable,
-- ^ The 'ModIface's for modules in external packages
-- whose interfaces we have opened.
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -23,9 +23,12 @@
-- 'hptCollectObjects'...
module GHC.Unit.Home.PackageTable
(
- HomePackageTable(..)
+ HomePackageTable
, emptyHomePackageTable
+ , HomeLoaderState -- TODO: should this be opaque? Probably
+ , emptyHomeLoaderState
+
-- * Lookups in the HPT
, lookupHpt
, lookupHptByModule
@@ -33,6 +36,7 @@ module GHC.Unit.Home.PackageTable
-- * Extending the HPT
, addHomeModInfoToHpt
, addHomeModInfosToHpt
+ , addOnDemandHomeModule
-- * Restrict the HPT
, restrictHpt
@@ -42,6 +46,18 @@ module GHC.Unit.Home.PackageTable
, hptAllInstances
, hptAllFamInstances
, hptAllAnnotations
+ , hlsIsModuleNameWithBoot
+ , hlsIsBoot
+ , hlsSetBootInfo
+ , hptLoadedIsBoot
+ , hptLoadedTypeEnv
+ , hptLoadedInstEnv
+ , hptLoadedFamInstEnv
+ , hptLoadedModFamInstEnv
+ , hptLoadedRuleBase
+ , hptLoadedAnnEnv
+ , hptLoadedCompleteMatches
+ , hptLoadedDefaults
-- ** More Traversal-based queries
, hptCollectDependencies
@@ -64,7 +80,7 @@ module GHC.Unit.Home.PackageTable
-- it is not sufficient to go through the intended insert-only API.
, hptInternalTableRef
, hptInternalTableFromRef
-
+ , hptLoaderState
-- * Legacy API
--
-- | This API is deprecated and meant to be removed.
@@ -80,8 +96,14 @@ import qualified Data.Set as Set
import GHC.Core.FamInstEnv
import GHC.Core.InstEnv
+import GHC.Core.Rules (RuleBase, extendRuleBaseList, emptyRuleBase)
+import GHC.Data.Word64Set qualified as W64
+import GHC.Linker.Types (Linkable)
import GHC.Types.Annotations
import GHC.Types.CompleteMatch
+import GHC.Types.TypeEnv
+import GHC.Types.TyThing
+import GHC.Types.Unique (getKey, getUnique)
import GHC.Types.Unique.DFM
import GHC.Unit.Home.ModInfo
import GHC.Unit.Module
@@ -89,13 +111,15 @@ import GHC.Unit.Module.Deps
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface
import GHC.Utils.Outputable
-import GHC.Types.Unique (getUnique, getKey)
-import qualified GHC.Data.Word64Set as W64
+import GHC.Types.Name
+import GHC.Types.Name.Env (extendNameEnvList)
+import GHC.Types.DefaultEnv (DefaultEnv)
+import GHC.Core
-- | Helps us find information about modules in the home package
-newtype HomePackageTable = HPT {
+data HomePackageTable = HPT {
- table :: IORef (DModuleNameEnv HomeModInfo)
+ table :: IORef (DModuleNameEnv HomeModInfo),
-- ^ Domain = modules in this home unit
--
-- This is an IORef because we want to avoid leaking HPTs (see the particularly bad #25511).
@@ -109,6 +133,7 @@ newtype HomePackageTable = HPT {
-- to temporarily violate the HPT monotonicity.
--
-- The elements of this table may be updated (e.g. on rehydration).
+ loader :: IORef HomeLoaderState
}
-- | Create a new 'HomePackageTable'.
@@ -120,7 +145,38 @@ emptyHomePackageTable :: IO HomePackageTable
-- romes:todo: use a MutableArray directly?
emptyHomePackageTable = do
table <- newIORef emptyUDFM
- return HPT{table}
+ loader <- newIORef emptyHomeLoaderState
+ return HPT{table, loader}
+
+data HomeLoaderState = HomeLoaderState
+ { hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
+ , hls_iface_table :: ModuleEnv ModIface
+ , hls_type_env :: !TypeEnv
+ , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
+ , hls_inst_env :: !InstEnv
+ , hls_fam_inst_env :: !FamInstEnv
+ , hls_mod_fam_inst_env :: !(ModuleEnv FamInstEnv)
+ , hls_rule_base :: !RuleBase
+ , hls_ann_env :: !AnnEnv
+ , hls_complete_matches :: !CompleteMatches
+ , hls_defaults :: ModuleEnv DefaultEnv
+ }
+
+emptyHomeLoaderState :: HomeLoaderState
+emptyHomeLoaderState =
+ HomeLoaderState
+ { hls_is_boot = emptyInstalledModuleEnv
+ , hls_iface_table = emptyModuleEnv
+ , hls_type_env = emptyTypeEnv
+ , hls_iface_bytecode = emptyModuleEnv
+ , hls_inst_env = emptyInstEnv
+ , hls_fam_inst_env = emptyFamInstEnv
+ , hls_mod_fam_inst_env = emptyModuleEnv
+ , hls_rule_base = emptyRuleBase
+ , hls_ann_env = emptyAnnEnv
+ , hls_complete_matches = []
+ , hls_defaults = emptyModuleEnv
+ }
--------------------------------------------------------------------------------
-- * Lookups in the HPT
@@ -139,6 +195,36 @@ lookupHptByModule hpt mod
Just hm | mi_module (hm_iface hm) == mod -> Just hm
_otherwise -> Nothing
+hptLoaderState :: HomePackageTable -> IO HomeLoaderState
+hptLoaderState = readIORef . loader
+
+hptLoadedIsBoot :: HomePackageTable -> IO (InstalledModuleEnv ModuleNameWithIsBoot)
+hptLoadedIsBoot hpt = hls_is_boot <$> readIORef (loader hpt)
+
+hptLoadedTypeEnv :: HomePackageTable -> IO TypeEnv
+hptLoadedTypeEnv hpt = hls_type_env <$> readIORef (loader hpt)
+
+hptLoadedInstEnv :: HomePackageTable -> IO InstEnv
+hptLoadedInstEnv hpt = hls_inst_env <$> readIORef (loader hpt)
+
+hptLoadedFamInstEnv :: HomePackageTable -> IO FamInstEnv
+hptLoadedFamInstEnv hpt = hls_fam_inst_env <$> readIORef (loader hpt)
+
+hptLoadedModFamInstEnv :: HomePackageTable -> IO (ModuleEnv FamInstEnv)
+hptLoadedModFamInstEnv hpt = hls_mod_fam_inst_env <$> readIORef (loader hpt)
+
+hptLoadedRuleBase :: HomePackageTable -> IO RuleBase
+hptLoadedRuleBase hpt = hls_rule_base <$> readIORef (loader hpt)
+
+hptLoadedAnnEnv :: HomePackageTable -> IO AnnEnv
+hptLoadedAnnEnv hpt = hls_ann_env <$> readIORef (loader hpt)
+
+hptLoadedCompleteMatches :: HomePackageTable -> IO CompleteMatches
+hptLoadedCompleteMatches hpt = hls_complete_matches <$> readIORef (loader hpt)
+
+hptLoadedDefaults :: HomePackageTable -> IO (ModuleEnv DefaultEnv)
+hptLoadedDefaults hpt = hls_defaults <$> readIORef (loader hpt)
+
--------------------------------------------------------------------------------
-- * Extending the HPT
--------------------------------------------------------------------------------
@@ -186,6 +272,56 @@ restrictHpt HPT{table=hptr} hmis =
addListToHpt :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> IO ()
addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
+addOnDemandHomeModule :: HomePackageTable -> Module -> ModIface -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
+addOnDemandHomeModule hpt mn iface bad_boot (new_hls_decls, new_hls_insts, new_hls_defaults, new_hls_fam_insts, new_hls_rules, new_hls_anns, new_hls_complete_matches) bytecode = do
+ atomicModifyIORef (loader hpt) $ \hls ->
+ ( if mn `elemModuleEnv` hls_iface_table hls
+ then hls -- If already loaded, don't add twice
+ else
+ if bad_boot
+ then addHomeModTypeEnv hls
+ else addHomeModData hls
+ , ()
+ )
+ where
+ addHomeModTypeEnv hls = hls
+ { hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls
+ }
+
+ addHomeModData hls = hls {
+ hls_iface_table = extendModuleEnv (hls_iface_table hls) mn iface,
+ hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls,
+ hls_iface_bytecode = case bytecode of
+ Nothing -> hls_iface_bytecode hls
+ Just bc -> extendModuleEnv (hls_iface_bytecode hls) mn bc,
+ hls_rule_base = extendRuleBaseList (hls_rule_base hls)
+ new_hls_rules,
+ hls_complete_matches
+ = hls_complete_matches hls ++ new_hls_complete_matches,
+ hls_inst_env = extendInstEnvList (hls_inst_env hls)
+ new_hls_insts,
+ hls_fam_inst_env = extendFamInstEnvList (hls_fam_inst_env hls)
+ new_hls_fam_insts,
+ hls_ann_env = extendAnnEnvList (hls_ann_env hls)
+ new_hls_anns,
+ hls_mod_fam_inst_env
+ =
+ let
+ fam_inst_env =
+ extendFamInstEnvList emptyFamInstEnv
+ new_hls_fam_insts
+ in
+ extendModuleEnv (hls_mod_fam_inst_env hls)
+ mn
+ fam_inst_env,
+ hls_defaults = extendModuleEnv (hls_defaults hls) mn new_hls_defaults
+ }
+
+hlsSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
+hlsSetBootInfo hpt is_boot_env =
+ atomicModifyIORef' (loader hpt) $ \ hls ->
+ (hls { hls_is_boot = is_boot_env }, ())
+
----------------------------------------------------------------------------------
---- * Queries
----------------------------------------------------------------------------------
@@ -216,6 +352,11 @@ hptAllFamInstances = fmap mkModuleEnv . concatHpt (\hmi -> [(hmiModule hmi, hmiF
hptAllAnnotations :: HomePackageTable -> IO AnnEnv
hptAllAnnotations = fmap mkAnnEnv . concatHpt (md_anns . hm_details)
+hlsIsBoot :: HomeLoaderState -> InstalledModule -> Maybe IsBootInterface
+hlsIsBoot hls mn = gwib_isBoot <$> hlsIsModuleNameWithBoot hls mn
+
+hlsIsModuleNameWithBoot :: HomeLoaderState -> InstalledModule -> Maybe ModuleNameWithIsBoot
+hlsIsModuleNameWithBoot hls mn = lookupInstalledModuleEnv (hls_is_boot hls) mn
--------------------------------------------------------------------------------
-- * Traversal-based queries
@@ -315,7 +456,8 @@ hptInternalTableRef = table
-- Use with care, only if you can really justify going around the intended insert-only API.
hptInternalTableFromRef :: IORef (DModuleNameEnv HomeModInfo) -> IO HomePackageTable
hptInternalTableFromRef ref = do
+ loader <- newIORef emptyHomeLoaderState
return HPT {
- table = ref
+ table = ref,
+ loader
}
-
=====================================
compiler/GHC/Unit/Module/Env.hs
=====================================
@@ -13,7 +13,12 @@ module GHC.Unit.Module.Env
, extendModuleEnvWith, filterModuleEnv, mapMaybeModuleEnv
-- * ModuleName mappings
- , ModuleNameEnv, DModuleNameEnv
+ , ModuleNameEnv
+ , extendModuleNameEnv
+ , emptyModuleNameEnv
+ , lookupModuleNameEnv
+ , unionModuleNameEnv
+ , DModuleNameEnv
-- * Sets of Modules
, ModuleSet
@@ -234,6 +239,17 @@ UniqFM.
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM ModuleName elt
+extendModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> elt -> ModuleNameEnv elt
+extendModuleNameEnv = addToUFM
+
+emptyModuleNameEnv :: ModuleNameEnv elt
+emptyModuleNameEnv = emptyUFM
+
+lookupModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> Maybe elt
+lookupModuleNameEnv = lookupUFM
+
+unionModuleNameEnv :: ModuleNameEnv elt -> ModuleNameEnv elt -> ModuleNameEnv elt
+unionModuleNameEnv = unionModuleNameEnv
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
-- Has deterministic folds and can be deterministically converted to a list
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0f928d0a6db34470ba941f37d58ee0f…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0f928d0a6db34470ba941f37d58ee0f…
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/romes/async-rpc] 2 commits: fixup! runWithPipes: avoid race to close their end on windows
by Andrea Vezzosi (@trac-Saizan) 16 Nov '26
by Andrea Vezzosi (@trac-Saizan) 16 Nov '26
16 Nov '26
Andrea Vezzosi pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC
Commits:
a30a4599 by Andrea Vezzosi at 2026-11-16T12:27:36+01:00
fixup! runWithPipes: avoid race to close their end on windows
- - - - -
000d737c by Andrea Vezzosi at 2026-11-16T17:27:25+01:00
interp: cleanup with stopInterp outside interpLoader lock
- - - - -
13 changed files:
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Env/Types.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Runtime/Interpreter/Init.hs
- compiler/GHC/Runtime/Interpreter/Types.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Runtime/Utils.hs
- compiler/GHC/Tc/Gen/Splice.hs
- ghc/GHCi/UI/Monad.hs
Changes:
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -56,7 +56,7 @@ import GHC.Driver.Config.Diagnostic (initDiagOpts, initPrintConfig)
import GHC.Driver.Env.Types ( Hsc(..), HscEnv(..), HasHscEnv (..) )
import GHC.Runtime.Context
-import GHC.Runtime.Interpreter.Types (Interp)
+import GHC.Runtime.Interpreter.Types (SafeInterp)
import GHC.Unit
import GHC.Unit.External.Database
@@ -410,7 +410,7 @@ mainModIs hue = mkHomeModule (expectJust $ homeUnitEnv_home_unit hue) (mainModul
-- | Retrieve the target code interpreter
--
-- Fails if no target code interpreter is available
-hscInterp :: HscEnv -> Interp
+hscInterp :: HscEnv -> SafeInterp
hscInterp hsc_env = case hsc_interp hsc_env of
Nothing -> throw (InstallationError "Couldn't find a target code interpreter. Try with -fexternal-interpreter")
Just i -> i
=====================================
compiler/GHC/Driver/Env/Types.hs
=====================================
@@ -14,7 +14,7 @@ import GHC.Driver.LlvmConfigCache (LlvmConfigCache)
import GHC.Prelude
import GHC.Runtime.Context
-import GHC.Runtime.Interpreter.Types ( Interp )
+import GHC.Runtime.Interpreter.Types ( SafeInterp )
import GHC.Types.Error ( Messages )
import GHC.Types.Name.Cache
import GHC.Types.Target
@@ -88,7 +88,7 @@ data HscEnv
-- the 'IfGblEnv'. See 'tcg_knot_vars' in 'GHC.Tc.Utils.TcGblEnv'.
-- See also Note [hsc_type_env_var hack]
- , hsc_interp :: Maybe Interp
+ , hsc_interp :: Maybe SafeInterp
-- ^ target code interpreter (if any) to use for TH and GHCi.
-- See Note [Target code interpreter]
=====================================
compiler/GHC/Driver/Main/Passes.hs
=====================================
@@ -1604,10 +1604,9 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do
let (stg_binds, _stg_deps) = unzip stg_binds_with_deps
let interp = hscInterp hsc_env
-
- case interp of
+ case interpInstance interp of
-- always generate JS code for the JS interpreter (no bytecode!)
- Interp { interpInstance = ExternalInterp (ExtJS i) } ->
+ ExternalInterp (ExtJS i) ->
jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id
_ -> do
@@ -1645,7 +1644,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
let logger = hsc_logger hsc_env
tmpfs = hsc_tmpfs hsc_env
dflags = hsc_dflags hsc_env
- interp = hscInterp hsc_env
+ interp0 = hscInterp hsc_env
tmp_dir = tmpDir dflags
unit_env = hsc_unit_env hsc_env
js_config = initStgToJSConfig dflags
@@ -1671,10 +1670,10 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
-- by default, so we can safely ignore them here.
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
-- Take lock for the actual work.
- (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp $ \pls -> do
+ (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp0 $ \interp pls -> do
let link_opts = initLinkDepsOpts hsc_env
-- Find what packages and linkables are required
@@ -1715,7 +1714,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
jsLinkObject logger tmpfs tmp_dir js_config unit_env (hsc_FC hsc_env) inst out_obj roots needed_units
-- look up "id_sym" closure and create a StablePtr (HValue) from it
- binding_fref <- lookupClosure interp (IFaststringSymbol id_sym) >>= \case
+ binding_fref <- withInterp interp0 $ \interp -> lookupClosure interp (IFaststringSymbol id_sym) >>= \case
Nothing -> pprPanic "Couldn't find just linked TH closure" (ppr id_sym)
Just r -> pure r
=====================================
compiler/GHC/Driver/Make.hs
=====================================
@@ -837,7 +837,7 @@ pruneCache hpt summ
-- ---------------------------------------------------------------------------
--
-- | Unloading
-unload :: Interp -> HscEnv -> IO ()
+unload :: SafeInterp -> HscEnv -> IO ()
unload interp hsc_env
= case ghcLink (hsc_dflags hsc_env) of
LinkInMemory -> Linker.unload interp hsc_env
=====================================
compiler/GHC/Linker/Loader.hs
=====================================
@@ -170,19 +170,19 @@ import Foreign.Ptr (nullPtr)
uninitialised :: a
uninitialised = panic "Loader not initialised"
-modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()
-modifyLoaderState_ interp f =
+modifyLoaderState_ :: SafeInterp -> (Interp -> LoaderState -> IO LoaderState) -> IO ()
+modifyLoaderState_ interp0 f = withInterp interp0 $ \ interp ->
modifyMVar_ (loader_state (interpLoader interp))
- (fmap pure . f . fromMaybe uninitialised)
+ (fmap pure . f interp . fromMaybe uninitialised)
-modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
-modifyLoaderState interp f =
+modifyLoaderState :: SafeInterp -> (Interp -> LoaderState -> IO (LoaderState, a)) -> IO a
+modifyLoaderState interp0 f = withInterp interp0 $ \ interp ->
modifyMVar (loader_state (interpLoader interp))
- (fmapFst pure . f . fromMaybe uninitialised)
+ (fmapFst pure . f interp . fromMaybe uninitialised)
where fmapFst f = fmap (\(x, y) -> (f x, y))
-getLoaderState :: Interp -> IO (Maybe LoaderState)
-getLoaderState interp = readMVar (loader_state (interpLoader interp))
+getLoaderState :: SafeInterp -> IO (Maybe LoaderState)
+getLoaderState (SafeInterp interp) = readMVar (loader_state (interpLoader interp))
emptyLoaderState :: UnitEnv -> LoaderState
@@ -206,21 +206,21 @@ emptyLoaderState unit_env = LoaderState
pkg_to_dfm rtsUnitId
] ++ fmap pkg_to_dfm deps
-extendLoadedEnv :: Interp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
+extendLoadedEnv :: SafeInterp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
extendLoadedEnv interp modify_bytecode_loader_state new_bindings =
- modifyLoaderState_ interp $ \pls -> do
+ modifyLoaderState_ interp $ \_ pls -> do
return $! modifyBytecodeLoaderState modify_bytecode_loader_state pls $ \bco_loader_state ->
modifyClosureEnv bco_loader_state $ \ce -> extendClosureEnv ce new_bindings
-- strictness is important for not retaining old copies of the pls
-deleteFromLoadedHomeEnv :: Interp -> [Name] -> IO ()
+deleteFromLoadedHomeEnv :: SafeInterp -> [Name] -> IO ()
deleteFromLoadedHomeEnv interp to_remove =
- modifyLoaderState_ interp $ \pls -> do
+ modifyLoaderState_ interp $ \_ pls -> do
return $ modifyBytecodeLoaderState modifyHomePackageBytecodeState pls $ \bco_state ->
modifyClosureEnv bco_state $ \ce -> delListFromNameEnv ce to_remove
-- | Have we already loaded a name into the interpreter?
-lookupFromLoadedEnv :: Interp -> Name -> IO (Maybe ForeignHValue)
+lookupFromLoadedEnv :: SafeInterp -> Name -> IO (Maybe ForeignHValue)
lookupFromLoadedEnv interp name = do
mstate <- getLoaderState interp
return $ do
@@ -231,10 +231,10 @@ lookupFromLoadedEnv interp name = do
-- | Load the module containing the given Name and get its associated 'HValue'.
--
-- Throws a 'ProgramError' if loading fails or the name cannot be found.
-loadName :: Interp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
-loadName interp hsc_env name = do
- initLoaderState interp hsc_env
- modifyLoaderState interp $ \pls0 -> do
+loadName :: SafeInterp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
+loadName interp0 hsc_env name = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState interp0 $ \interp pls0 -> do
(pls, links, pkgs) <- if not (isExternalName name)
then return (pls0, [], emptyUDFM)
else do
@@ -248,6 +248,7 @@ loadName interp hsc_env name = do
Just (_,aa) -> return (pls,(aa, links, pkgs))
Nothing -> assertPpr (isExternalName name) (ppr name) $
do let sym_to_find = IClosureSymbol name
+ -- TODO: does not take loader state lock
m <- lookupClosure interp sym_to_find
r <- case m of
Just fhv -> return fhv
@@ -295,7 +296,7 @@ loadDependencies interp hsc_env pls span needed_mods = do
-- | Temporarily extend the loaded env.
withExtendedLoadedEnv
:: (ExceptionMonad m)
- => Interp
+ => SafeInterp
-> [(Name,ForeignHValue)]
-> m a
-> m a
@@ -314,9 +315,9 @@ withExtendedLoadedEnv interp new_env action
-- | Display the loader state.
-showLoaderState :: Interp -> IO SDoc
+showLoaderState :: SafeInterp -> IO SDoc
showLoaderState interp = do
- ls <- readMVar (loader_state (interpLoader interp))
+ ls <- getLoaderState interp
let docs = case ls of
Nothing -> [ text "Loader not initialised"]
Just pls -> [ text "Pkgs:" <+> ppr (map loaded_pkg_uid $ eltsUDFM $ pkgs_loaded pls)
@@ -352,8 +353,8 @@ showLoaderState interp = do
-- nothing. This is useful in Template Haskell, where we call it before
-- trying to link.
--
-initLoaderState :: Interp -> HscEnv -> IO ()
-initLoaderState interp hsc_env = do
+initLoaderState :: SafeInterp -> HscEnv -> IO ()
+initLoaderState interp0 hsc_env = withInterp interp0 $ \ interp -> do
modifyMVar_ (loader_state (interpLoader interp)) $ \pls -> do
case pls of
Just _ -> return pls
@@ -382,10 +383,10 @@ reallyInitLoaderState interp hsc_env = do
loadCmdLineLibs' interp hsc_env pls
-loadCmdLineLibs :: Interp -> HscEnv -> IO ()
-loadCmdLineLibs interp hsc_env = do
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls ->
+loadCmdLineLibs :: SafeInterp -> HscEnv -> IO ()
+loadCmdLineLibs interp0 hsc_env = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls ->
loadCmdLineLibs' interp hsc_env pls
@@ -730,13 +731,13 @@ get_reachable_nodes hsc_env mods
********************************************************************* -}
-- | Load the dependencies of a linkable, and then load the linkable itself.
-loadDecls :: Interp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
-loadDecls interp hsc_env span linkable = do
+loadDecls :: SafeInterp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
+loadDecls interp0 hsc_env span linkable = do
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
-- Take lock for the actual work.
- modifyLoaderState interp $ \pls0 -> do
+ modifyLoaderState interp0 $ \interp pls0 -> do
-- Link the packages and modules required
(pls, ok, links_needed, units_needed) <- loadDependencies interp hsc_env pls0 span needed_mods
if failed ok
@@ -770,10 +771,10 @@ loadDecls interp hsc_env span linkable = do
********************************************************************* -}
-loadModule :: Interp -> HscEnv -> Module -> IO ()
-loadModule interp hsc_env mod = do
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls -> do
+loadModule :: SafeInterp -> HscEnv -> Module -> IO ()
+loadModule interp0 hsc_env mod = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls -> do
(pls', ok, _, _) <- loadDependencies interp hsc_env pls noSrcSpan [mod]
if failed ok
then throwGhcExceptionIO (ProgramError "could not load module")
@@ -1158,16 +1159,16 @@ gets actually written to the loader state, the failure to do so is tracked by
-- * we also implicitly unload all temporary bindings at this point.
--
unload
- :: Interp
+ :: SafeInterp
-> HscEnv
-> IO ()
-unload interp hsc_env
+unload interp0 hsc_env
= mask_ $ do -- mask, so we're safe from Ctrl-C in here
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
- _new_pls <- modifyLoaderState interp $ \pls -> do
+ _new_pls <- modifyLoaderState interp0 $ \interp pls -> do
pls1 <- unload_wkr interp pls
return (pls1, pls1)
@@ -1234,7 +1235,7 @@ showLS (BytecodeLibrary nm) = "(bytecode) " ++ nm
-- automatically, and it doesn't matter what order you specify the input
-- packages.
--
-loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
+loadPackages :: SafeInterp -> HscEnv -> [UnitId] -> IO ()
-- NOTE: in fact, since each module tracks all the packages it depends on,
-- we don't really need to use the package-config dependencies.
--
@@ -1243,11 +1244,11 @@ loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
-- perhaps makes the error message a bit more localised if we get a link
-- failure. So the dependency walking code is still here.
-loadPackages interp hsc_env new_pkgs = do
+loadPackages interp0 hsc_env new_pkgs = do
-- It's probably not safe to try to load packages concurrently, so we take
-- a lock.
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls ->
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls ->
loadPackages' interp hsc_env new_pkgs pls
-- | Compute 'LoadedPkgInfo' metadata (with transitive deps) for new packages,
=====================================
compiler/GHC/Runtime/Eval.hs
=====================================
@@ -468,7 +468,7 @@ resumeExec step mbCnt r = do
| otherwise -> pure prevHistoryLst
handleRunStatus step eval_opts expr bindings final_ids status =<< hist'
-setupBreakpoint :: GhcMonad m => Interp -> InternalBreakpointId -> Int -> m () -- #19157
+setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157
setupBreakpoint interp ibi cnt = do
hug <- hsc_HUG <$> getSession
liftIO $ do
@@ -476,18 +476,18 @@ setupBreakpoint interp ibi cnt = do
breakArray <- getBreakArray interp ibi modBreaks
GHCi.storeBreakpoint interp breakArray (ibi_info_index ibi) cnt
-getBreakArray :: Interp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
+getBreakArray :: SafeInterp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
getBreakArray interp InternalBreakpointId{ibi_info_mod} imbs = do
breaks0 <- bco_linked_breaks . homePackage_loaded . bco_loader_state . fromMaybe (panic "Loader not initialised") <$> getLoaderState interp
case lookupModuleEnv (breakarray_env breaks0) ibi_info_mod of
Just ba -> return ba
Nothing -> do
- modifyLoaderState interp $ \ld_st -> do
+ modifyLoaderState interp $ \interp' ld_st -> do
let lb = bco_linked_breaks . homePackage_loaded . bco_loader_state $ ld_st
-- Recall that BreakArrays are allocated only at BCO link time, so if we
-- haven't linked the BCOs we intend to break at yet, we allocate the arrays here.
- ba_env <- allocateBreakArrays interp (breakarray_env lb) [imbs]
+ ba_env <- allocateBreakArrays interp' (breakarray_env lb) [imbs]
let ld_st' = modifyBytecodeLoaderState modifyHomePackageBytecodeState ld_st $ \bco_state -> bco_state { bco_linked_breaks = (bco_linked_breaks bco_state) { breakarray_env = ba_env } }
let ba = expectJust {- just computed -} $ lookupModuleEnv ba_env ibi_info_mod
=====================================
compiler/GHC/Runtime/Interpreter.hs
=====================================
@@ -64,6 +64,9 @@ module GHC.Runtime.Interpreter
-- * Reexport for convenience
, Message (..)
, module GHC.Runtime.Interpreter.Process
+
+ -- * High-level interface to the interpreter
+ , withInterp
) where
import GHC.Prelude
@@ -198,7 +201,7 @@ interpCmd interp msg = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> run msg -- Just run it directly
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst ->
+ ExternalInterp ext -> withExtInterp ext $ \inst ->
sendMessage inst msg
-- | Calls `interpCmd` and the continuation while masked.
@@ -208,13 +211,20 @@ interpCmd interp msg = case interpInstance interp of
withInterpCmdMasked :: Binary a => Interp -> Message a -> (a -> IO b) -> IO b
withInterpCmdMasked interp msg own = mask_ $ interpCmd interp msg >>= own
-withExtInterp :: ExceptionMonad m => Interp -> ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
-withExtInterp interp ext action = stopInterpOnPipeClosed $ case ext of
+-- | Passes the `Interp` to the continuation while setting up a
+-- 'PipeClosedException' handler that calls 'stopInterp'.
+--
+-- Will take the 'interpLoader' lock on a 'PipeClosedException'.
+withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
+withInterp interp0@(SafeInterp interp) k = stopInterpOnPipeClosed $ k interp
+ where
+ stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> liftIO (stopInterp interp0) >> MC.throwM e
+
+withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
+withExtInterp ext action = case ext of
ExtJS i -> withJSInterp i action
ExtWasm i -> withWasmInterp i action
ExtIServ i -> withIServ i action
- where
- stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> liftIO (stopInterp interp) >> MC.throwM e
withExtInterpStatus :: ExtInterp -> (forall d. ExtInterpStatusVar d -> m a) -> m a
withExtInterpStatus ext action = case ext of
@@ -294,11 +304,11 @@ withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do
-- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for
-- each of the results.
evalStmt
- :: Interp
+ :: SafeInterp
-> EvalOpts
-> EvalExpr ForeignHValue
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
-evalStmt interp opts foreign_expr = do
+evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do
status <- withExpr foreign_expr $ \expr ->
interpCmd interp (EvalStmt opts expr)
handleEvalStatus interp status
@@ -312,17 +322,17 @@ evalStmt interp opts foreign_expr = do
cont (EvalApp fl' fr')
resumeStmt
- :: Interp
+ :: SafeInterp
-> EvalOpts
-> ForeignRef (ResumeContext [HValueRef])
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
-resumeStmt interp opts resume_ctxt = do
+resumeStmt interp0 opts resume_ctxt = withInterp interp0 $ \interp -> do
status <- withForeignRef resume_ctxt $ \rhv ->
interpCmd interp (ResumeStmt opts rhv)
handleEvalStatus interp status
-abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
-abandonStmt interp resume_ctxt =
+abandonStmt :: SafeInterp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
+abandonStmt interp0 resume_ctxt = withInterp interp0 $ \ interp ->
withForeignRef resume_ctxt $ \rhv ->
interpCmd interp (AbandonStmt rhv)
@@ -341,20 +351,20 @@ handleEvalStatus interp status =
EvalSuccess <$> mapM (mkFinalizedHValue interp) rs
-- | Execute an action of type @IO ()@
-evalIO :: Interp -> ForeignHValue -> IO ()
-evalIO interp fhv =
+evalIO :: SafeInterp -> ForeignHValue -> IO ()
+evalIO interp0 fhv = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalIO fhv) >>= fromEvalResult
-- | Execute an action of type @IO String@
-evalString :: Interp -> ForeignHValue -> IO String
-evalString interp fhv =
+evalString :: SafeInterp -> ForeignHValue -> IO String
+evalString interp0 fhv = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalString fhv) >>= fromEvalResult
-- | Execute an action of type @String -> IO String@
-evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String
-evalStringToIOString interp fhv str =
+evalStringToIOString :: SafeInterp -> ForeignHValue -> String -> IO String
+evalStringToIOString interp0 fhv str = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalStringToString fhv str) >>= fromEvalResult
@@ -388,44 +398,44 @@ addHpcModule :: Interp -> SBS.ShortByteString -> Int -> Int -> SBS.ShortByteStri
addHpcModule interp modLabel tickNo hash tickboxes =
interpCmd interp (AddHpcModule modLabel tickNo hash tickboxes)
-costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String]
-costCentreStackInfo interp ccs =
+costCentreStackInfo :: SafeInterp -> RemotePtr CostCentreStack -> IO [String]
+costCentreStackInfo interp0 ccs = withInterp interp0 $ \interp ->
interpCmd interp (CostCentreStackInfo ccs)
newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray)
newBreakArray interp size =
withInterpCmdMasked interp (NewBreakArray size) (mkFinalizedHValue interp)
-storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO ()
-storeBreakpoint interp ref ix cnt = do -- #19157
+storeBreakpoint :: SafeInterp -> ForeignRef BreakArray -> Int -> Int -> IO ()
+storeBreakpoint interp0 ref ix cnt = withInterp interp0 $ \ interp -> do -- #19157
withForeignRef ref $ \breakarray ->
interpCmd interp (SetupBreakpoint breakarray ix cnt)
-breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool
-breakpointStatus interp ref ix =
+breakpointStatus :: SafeInterp -> ForeignRef BreakArray -> Int -> IO Bool
+breakpointStatus interp0 ref ix = withInterp interp0 $ \ interp ->
withForeignRef ref $ \breakarray ->
interpCmd interp (BreakpointStatus breakarray ix)
-getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
-getBreakpointVar interp ref ix =
+getBreakpointVar :: SafeInterp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
+getBreakpointVar interp0 ref ix = withInterp interp0 $ \ interp ->
withForeignRef ref $ \apStack ->
withInterpCmdMasked interp (GetBreakpointVar apStack ix)
(mapM (mkFinalizedHValue interp))
-getClosure :: Interp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
-getClosure interp ref =
+getClosure :: SafeInterp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
+getClosure interp0 ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval ->
withInterpCmdMasked interp (GetClosure hval) $
mapM (mkFinalizedHValue interp)
-whereFrom :: Interp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
-whereFrom interp ref =
+whereFrom :: SafeInterp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
+whereFrom interp0 ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
interpCmd interp (WhereFrom hval)
-- | Send a Seq message to the iserv process to force a value #2950
-seqHValue :: Interp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
-seqHValue interp unit_env logger ref =
+seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
+seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
status <- interpCmd interp (Seq hval)
handleSeqHValueStatus interp unit_env logger status
@@ -649,23 +659,29 @@ spawnIServ conf = do
pure inst
-- | Stop the interpreter
-stopInterp :: Interp -> IO ()
-stopInterp interp = case interpInstance interp of
+stopInterp :: SafeInterp -> IO ()
+stopInterp (SafeInterp interp) = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> pure ()
#endif
- ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> do
- MC.mask $ \restore -> modifyMVar mstate $ \state -> do
+ ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do
+ -- takes interpLoader lock before ExternalInterp lock to avoid deadlocks.
+ -- commits emptied values before 'gracefulShutdown' so we don't hold locks
+ -- more than necessary.
+ mi <- modifyMVar (loader_state (interpLoader interp)) $ \l_st -> do
+ modifyMVar mstate $ \state -> do
case state of
- InterpPending -> pure (state, Nothing) -- already stopped
+ InterpPending -> pure (state, (l_st, Nothing)) -- already stopped
InterpRunning i -> do
- e <- getProcessExitCode (interpHandle (instProcess i)) >>= \case
- Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
- Nothing -> gracefulShutdown i restore
- modifyMVar_ (loader_state (interpLoader interp)) (const $ pure Nothing)
purgeInterpSymbolCache (interpSymbolCache interp)
modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
- pure (InterpPending,e)
+ pure (InterpPending,(Nothing,Just i))
+ case mi of
+ Nothing -> pure Nothing
+ Just i -> getProcessExitCode (interpHandle (instProcess i)) >>= \case
+ Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
+ Nothing -> gracefulShutdown i restore
+
where
gracefulShutdown i restore = do
x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i)))))
@@ -731,7 +747,7 @@ principle it would probably be ok, but it seems less hairy this way.
-- | Creates a 'ForeignRef' that will automatically release the
-- 'RemoteRef' when it is no longer referenced.
-mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a)
+mkFinalizedHValue :: HasInterpInstance i => i -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue interp rref = do
case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
@@ -754,13 +770,13 @@ freeHValueRefs interp refs = interpCmd interp (FreeHValueRefs refs)
-- | Convert a 'ForeignRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
-wormhole :: Interp -> ForeignRef a -> IO a
+wormhole :: SafeInterp -> ForeignRef a -> IO a
wormhole interp r = wormholeRef interp (unsafeForeignRefToRemoteRef r)
-- | Convert an 'RemoteRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
-wormholeRef :: Interp -> RemoteRef a -> IO a
+wormholeRef :: SafeInterp -> RemoteRef a -> IO a
wormholeRef interp _r = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> localRef _r
=====================================
compiler/GHC/Runtime/Interpreter/Init.hs
=====================================
@@ -29,7 +29,9 @@ import GHC.Utils.Monad
import GHC.Utils.Outputable
import GHC.Utils.Logger
import GHC.Utils.Error
+
import Control.Concurrent
+import Data.Coerce
import System.Process
data InterpOpts = InterpOpts
@@ -67,8 +69,8 @@ initInterpreter
-> FinderCache
-> UnitEnv
-> InterpOpts
- -> IO (Maybe Interp)
-initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = do
+ -> IO (Maybe SafeInterp)
+initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = coerce $ do
lookup_cache <- liftIO $ mkInterpSymbolCache
=====================================
compiler/GHC/Runtime/Interpreter/Types.hs
=====================================
@@ -4,6 +4,8 @@
-- | Types used by the runtime interpreter
module GHC.Runtime.Interpreter.Types
( Interp(..)
+ , SafeInterp(..)
+ , HasInterpInstance(..)
, InterpInstance(..)
, InterpProcess (..)
, ExtInterp (..)
@@ -66,9 +68,36 @@ import System.Process ( ProcessHandle, CreateProcess )
import System.IO
import GHC.Unit.Finder.Types (FinderCache, FinderOpts)
+{-
+Note [Interpreter locks order]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To avoid deadlocks, the 'interpLoader' lock should be taken before the lock that
+contains the 'InterpStatus'.
+
+Further, you should wrap the code that takes the 'interpLoader' lock with
+'withInterp', as it will cleanup the whole interpreter state in case the
+external interpreter pipe died:
+```
+withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
+```
+
+'SafeInterp' is a newtype introduced to aid with the discipline: only code that
+has ownership over a 'SafeInterp' should take its 'interpLoader' lock.
+
+-}
+
+
+
+
+-- | An 'Interp' where we have not taken the 'interpLoader' lock in this thread.
+--
+-- See Note [Interpreter locks order]
+newtype SafeInterp = SafeInterp Interp
+
-- | Interpreter
data Interp = Interp
- { interpInstance :: !InterpInstance
+ { _interpInstance :: !InterpInstance
-- ^ Interpreter instance (internal, external)
, interpLoader :: !Loader
@@ -81,6 +110,13 @@ data Interp = Interp
-- ^ MallocStrings cache
}
+class HasInterpInstance a where
+ interpInstance :: a -> InterpInstance
+instance HasInterpInstance SafeInterp where
+ interpInstance (SafeInterp interp) = interpInstance interp
+instance HasInterpInstance Interp where
+ interpInstance = _interpInstance
+
data InterpInstance
= ExternalInterp !ExtInterp -- ^ External interpreter
#if defined(HAVE_INTERNAL_INTERPRETER)
@@ -143,7 +179,7 @@ data ExtInterpInstance c = ExtInterpInstance
}
-- | Interpreter uses Profiling way
-interpreterProfiled :: Interp -> Bool
+interpreterProfiled :: HasInterpInstance a => a -> Bool
interpreterProfiled interp = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> hostIsProfiled
@@ -154,7 +190,7 @@ interpreterProfiled interp = case interpInstance interp of
ExtWasm i -> wasmInterpProfiled $ interpConfig i
-- | Interpreter uses Dynamic way
-interpreterDynamic :: Interp -> Bool
+interpreterDynamic :: HasInterpInstance a => a -> Bool
interpreterDynamic interp = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> hostIsDynamic
=====================================
compiler/GHC/Runtime/Loader.hs
=====================================
@@ -283,7 +283,7 @@ getValueSafely hsc_env val_name expected_type = do
logger = hsc_logger hsc_env
hooks = hsc_hooks hsc_env
-getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
+getHValueSafely :: SafeInterp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
getHValueSafely interp hsc_env val_name expected_type = do
forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name
-- Now look up the names for the value and type constructor in the type environment
=====================================
compiler/GHC/Runtime/Utils.hs
=====================================
@@ -76,6 +76,12 @@ toFdHandleIfNeeded h
toFdHandleIfNeeded = return
#endif
+-- | Workaround for locking prone closeCommunicationHandle on windows
+--
+-- Called after a createProcess: the subprocess might start reading from the
+-- inherited raw handle before this close is scheduled, and, on windows,
+-- closeCommunicationHandle will block on a pending read during its conversion
+-- to Handle. Calling Win32.closeHandle directly avoids the blocking.
closeTheirEnd :: CommunicationHandle -> IO ()
#if defined(mingw32_HOST_OS)
closeTheirEnd (CommunicationHandle h) = Win32.closeHandle h
=====================================
compiler/GHC/Tc/Gen/Splice.hs
=====================================
@@ -1151,16 +1151,16 @@ runRemoteModFinalizers (ThModFinalizers finRefs) = do
let withForeignRefs [] f = f []
withForeignRefs (x : xs) f = withForeignRef x $ \r ->
withForeignRefs xs $ \rs -> f (r : rs)
- interp <- tcGetInterp
+ interp0 <- tcGetInterp
- case interpInstance interp of
+ withInterp interp0 $ \interp -> case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> do
qs <- liftIO (withForeignRefs finRefs $ mapM localRef)
runQinTcM $ sequence_ qs
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
+ ExternalInterp ext -> withExtInterp ext $ \inst -> do
tcg <- getGblEnv
th_state <- readTcRef (tcg_th_remote_state tcg)
case th_state of
@@ -1807,17 +1807,17 @@ runTHDec = runTH THDec
runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
runTH ty fhv = do
- interp <- tcGetInterp
- case interpInstance interp of
+ interp0 <- tcGetInterp
+ withInterp interp0 $ \ interp -> case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> do
-- Run it in the local TcM
- hv <- liftIO $ wormhole interp fhv
+ hv <- liftIO $ wormhole interp0 fhv
r <- runQinTcM (unsafeCoerce hv :: TH.Q a)
return r
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
+ ExternalInterp ext -> withExtInterp ext $ \inst -> do
-- Run it on the server. For an overview of how TH works with
-- Remote GHCi, see Note [Remote Template Haskell] in
-- libraries/ghci/GHCi/TH.hs.
@@ -3031,7 +3031,7 @@ mkThAppTs fun_ty arg_tys = foldl' TH.AppT fun_ty arg_tys
noTH :: UnrepresentableTypeDescr -> Type -> TcM a
noTH s d = failWithTc $ TcRnTHError $ THReifyError $ CannotRepresentType s d
-tcGetInterp :: TcM Interp
+tcGetInterp :: TcM SafeInterp
tcGetInterp = do
hsc_env <- getTopEnv
case hsc_interp hsc_env of
=====================================
ghc/GHCi/UI/Monad.hs
=====================================
@@ -475,8 +475,8 @@ printStats dflags ActionStats{actionAllocs = mallocs, actionElapsedTime = secs}
revertCAFs :: GhciMonad m => m ()
revertCAFs = do
- interp <- hscInterp <$> GHC.getSession
- liftIO $ interpCmd interp RtsRevertCAFs
+ interp0 <- hscInterp <$> GHC.getSession
+ liftIO $ withInterp interp0 $ \interp -> interpCmd interp RtsRevertCAFs
s <- getGHCiState
when (not (ghc_e s)) turnOffBuffering
-- Have to turn off buffering again, because we just
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/76c49a91c44801ad9e4c9f5f6f957f…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/76c49a91c44801ad9e4c9f5f6f957f…
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