[Git][ghc/ghc][wip/fendor/one-shot-no-eps] Fix hugSomeThingsBelowUs check
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
4a84e770 by fendor at 2026-11-30T14:38:38+01:00
Fix hugSomeThingsBelowUs check
- - - - -
3 changed files:
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Tc/Module.hs
Changes:
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -102,7 +102,7 @@ core2core hsc_env guts@(ModGuts { mg_module = mod
logger = hsc_logger hsc_env
unit_env = hsc_unit_env hsc_env
extra_vars = interactiveInScope (hsc_IC hsc_env)
- home_pkg_rules = hugRulesBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) (moduleUnitId mod)
+ home_pkg_rules = hugRulesBelow (hsc_unit_env hsc_env) (moduleUnitId mod)
(GWIB { gwib_mod = moduleName mod, gwib_isBoot = NotBoot })
name_ppr_ctx = mkNamePprCtx ptc unit_env rdr_env
ptc = initPromotionTickContext dflags
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -260,26 +260,26 @@ hscUIC hsc_env = ue_uic (hsc_unit_env hsc_env)
-- | Find all rules in modules that are in the transitive closure of the given
-- module.
-hugRulesBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO RuleBase
-hugRulesBelow mg hug uid mn = foldr (flip extendRuleBaseList) emptyRuleBase <$>
- hugSomeThingsBelowUs (md_rules . hm_details) False mg hug uid mn
+hugRulesBelow :: UnitEnv -> UnitId -> ModuleNameWithIsBoot -> IO RuleBase
+hugRulesBelow unit_env uid mn = foldr (flip extendRuleBaseList) emptyRuleBase <$>
+ hugSomeThingsBelowUs (md_rules . hm_details) False unit_env uid mn
-- | Get annotations from all modules "below" this one (in the dependency
-- sense) within the home units. If the module is @Nothing@, returns /all/
-- annotations in the home units.
-hugAnnsBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO AnnEnv
-hugAnnsBelow mg hug uid mn = foldr (flip extendAnnEnvList) emptyAnnEnv <$>
- hugSomeThingsBelowUs (md_anns . hm_details) False mg hug uid mn
+hugAnnsBelow :: UnitEnv -> UnitId -> ModuleNameWithIsBoot -> IO AnnEnv
+hugAnnsBelow unit_env uid mn = foldr (flip extendAnnEnvList) emptyAnnEnv <$>
+ hugSomeThingsBelowUs (md_anns . hm_details) False unit_env uid mn
-- | Find all COMPLETE pragmas in modules that are in the transitive closure of the
-- given module.
-hugCompleteSigsBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO CompleteMatches
-hugCompleteSigsBelow mg hug uid mn = foldr (++) [] <$>
- hugSomeThingsBelowUs (md_complete_matches . hm_details) False mg hug uid mn
+hugCompleteSigsBelow :: UnitEnv -> UnitId -> ModuleNameWithIsBoot -> IO CompleteMatches
+hugCompleteSigsBelow unit_env uid mn = foldr (++) [] <$>
+ hugSomeThingsBelowUs (md_complete_matches . hm_details) False unit_env uid mn
-- | Find instances visible from the given set of imports
-hugInstancesBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst])
-hugInstancesBelow mg hug uid mnwib = do
+hugInstancesBelow :: UnitEnv -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst])
+hugInstancesBelow unit_env uid mnwib = do
let mn = mkModule uid (gwib_mod mnwib)
(insts, famInsts) <-
unzip . concat <$>
@@ -290,8 +290,7 @@ hugInstancesBelow mg hug uid mnwib = do
then []
else [(md_insts details, md_fam_insts details)])
True -- Include -hi-boot
- mg
- hug
+ unit_env
uid
mnwib
return (foldl' unionInstEnv emptyInstEnv insts, concat famInsts)
@@ -299,18 +298,19 @@ hugInstancesBelow mg hug uid mnwib = do
-- | Get things from modules in the transitive closure of the given module.
--
-- Note: Don't expose this function. This is a footgun if exposed!
-hugSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO [[a]]
+hugSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> UnitEnv -> UnitId -> ModuleNameWithIsBoot -> IO [[a]]
-- An explicit check to see if we are in one-shot mode to avoid poking the ModuleGraph thunk
--- These things are currently stored in the EPS for home packages. (See #25795 for
+-- These things are currently stored in the HPT's loader state for home packages. (See #25795 for
-- progress in removing these kind of checks; and making these functions of
-- `UnitEnv` rather than `HscEnv`)
-- See Note [The ModuleGraph]
-hugSomeThingsBelowUs extract include_hi_boot mg hug uid mn =
- -- If the first hpt is a one-shot table, we don't recurse into it.
- -- TODO @fendor: I guess that's nonsense to a certain degree
- if HPT.isOneShotMode $ homeUnitEnv_hpt $ unitEnv_lookup uid hug
- then pure []
- else
+hugSomeThingsBelowUs extract include_hi_boot unit_env uid mn
+ | HPT.isOneShotMode (ue_hpt unit_env)
+ = pure []
+ | otherwise
+ = let hug = ue_home_unit_graph unit_env
+ mg = ue_module_graph unit_env
+ in
sequence
[ things
-- "Finding each non-hi-boot module below me" maybe could be cached (well,
@@ -350,7 +350,7 @@ prepareAnnotations hsc_env mb_guts = do
-- entries regardless of dependency ordering.
get_mod mg = (moduleUnitId (mg_module mg), GWIB (moduleName (mg_module mg)) NotBoot)
home_pkg_anns <- fromMaybe (hugAllAnns (hsc_unit_env hsc_env))
- $ uncurry (hugAnnsBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env))
+ $ uncurry (hugAnnsBelow (hsc_unit_env hsc_env))
. get_mod <$> mb_guts
more_home_pkg_anns <- HomePackageTable.hptLoadedAnnEnv $ hsc_HPT hsc_env
let
=====================================
compiler/GHC/Tc/Module.hs
=====================================
@@ -501,13 +501,13 @@ tcRnImports hsc_env import_decls
-- modules batch (@--make@) compiled before this one, but
-- which are not below this one.
; (home_insts, home_fam_insts) <- liftIO $
- hugInstancesBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) unitId mnwib
+ hugInstancesBelow (hsc_unit_env hsc_env) unitId mnwib
-- We use 'unsafeInterleaveIO' to avoid redundant memory allocations
-- See Note [Lazily loading COMPLETE pragmas] from GHC.HsToCore.Monad
-- and see https://gitlab.haskell.org/ghc/ghc/-/merge_requests/14274#note_620545
; completeSigsBelow <- liftIO $ unsafeInterleaveIO $
- hugCompleteSigsBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) unitId mnwib
+ hugCompleteSigsBelow (hsc_unit_env hsc_env) unitId mnwib
-- Record boot-file info in the HPT, so that it's
-- visible to loadHiBootInterface in tcRnSrcDecls,
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/4a84e770e44280d52e65eddaff453e0…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/4a84e770e44280d52e65eddaff453e0…
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] Add eps stats, fix retainer leak, and make fam inst more consistent
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
7198f0bd by fendor at 2026-11-30T14:30:00+01:00
Add eps stats, fix retainer leak, and make fam inst more consistent
- - - - -
7 changed files:
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Main/Hsc.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Unit/Home/PackageTable.hs
Changes:
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -468,7 +468,7 @@ doCorePass pass guts = do
p_fam_env <- getPackageFamInstEnv
l_fam_env <- getLazyHomeFamInstEnv
let platform = targetPlatform dflags
- let fam_envs = (p_fam_env `unionFamInstEnv` l_fam_env, mg_fam_inst_env guts)
+ let fam_envs = (p_fam_env, mg_fam_inst_env guts `unionFamInstEnv` l_fam_env)
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/Driver/Main/Compile.hs
=====================================
@@ -1,5 +1,6 @@
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
{-# OPTIONS_GHC -fprof-auto-top #-}
@@ -215,7 +216,7 @@ loadIfaceByteCode hsc_env iface location type_env =
where
compile decls = do
bco <- compileWholeCoreBindings hsc_env type_env decls
- return $! Linkable (gbc_hash bco) (mi_module iface) (pure (DotGBC bco))
+ return $! Linkable (gbc_hash bco) (decls.wcb_module) (pure (DotGBC bco))
loadIfaceByteCodeLazy ::
HscEnv ->
=====================================
compiler/GHC/Driver/Main/Hsc.hs
=====================================
@@ -85,6 +85,7 @@ import GHC.Types.Error
import GHC.Types.Name.Cache ( newNameCache )
import GHC.Utils.Panic
+import qualified GHC.Utils.Outputable as Outputable
import GHC.Utils.Logger
import GHC.Utils.TmpFs
@@ -274,8 +275,10 @@ dumpIfaceStats hsc_env = do
logger = hsc_logger hsc_env
dump_rn_stats = logHasDumpFlag logger Opt_D_dump_rn_stats
dump_if_trace = logHasDumpFlag logger Opt_D_dump_if_trace
- when (dump_if_trace || dump_rn_stats) $
- logDumpMsg logger "Interface statistics" (ifaceStats eps)
+ when (dump_if_trace || dump_rn_stats) $ do
+ mb_home_stats <- hptLoadedStats (hsc_HPT hsc_env)
+ logDumpMsg logger "Interface statistics" $
+ ifaceStats eps Outputable.$$ maybe Outputable.empty pprHptStats mb_home_stats
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -918,7 +918,8 @@ addModIfacePartsToHpt gbl_env mod loc iface (new_decls, new_insts, new_defaults,
warnPprTrace bad_boot "loadInterface" (ppr mod) $ do
hpt <- getHpt
when (not bad_boot) $ do
- liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
+ let final_iface = stripLoadedIface "home package table" iface
+ liftIO $ addHomeModInfoToHpt (HomeModInfo final_iface details emptyHomeModInfoLinkable) hpt
liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) mb_bytecode
addModIfacePartsToEps :: Module -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
@@ -926,14 +927,7 @@ addModIfacePartsToEps mod iface (new_decls, new_insts, new_defaults, new_fam_ins
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")
+ final_iface = stripLoadedIface "PIT" iface
mhome_unit = ue_homeUnit (hsc_unit_env purged_hsc_env)
updateEps_ $ \ eps ->
@@ -970,6 +964,19 @@ addModIfacePartsToEps mod iface (new_decls, new_insts, new_defaults, new_fam_ins
}
+stripLoadedIface :: String -> ModIface -> ModIface
+stripLoadedIface table iface = iface
+ & set_mi_decls (gone "mi_decls")
+ & set_mi_insts (gone "mi_insts")
+ & set_mi_defaults (gone "mi_defaults")
+ & set_mi_fam_insts (gone "mi_fam_insts")
+ & set_mi_rules (gone "mi_rules")
+ & set_mi_anns (gone "mi_anns")
+ & set_mi_simplified_core (gone "mi_simplified_core")
+ where
+ gone :: String -> a
+ gone field = panic ("No " ++ field ++ " in " ++ table)
+
{- Note [Loading your own hi-boot file]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally speaking, when compiling module M, we should not
=====================================
compiler/GHC/IfaceToCore.hs
=====================================
@@ -138,6 +138,8 @@ 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
+import GHC.Unit.Home (isHomeModule)
+import GHC.Driver.Env (hsc_HPT, hsc_home_unit_maybe)
{-
This module takes
@@ -1103,8 +1105,19 @@ tc_iface_decl_fingerprint ignore_prags (_version, decl)
bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
bumpDeclStats name
= do { traceIf (text "Loading decl for" <+> ppr name)
- ; updateEps_ (\eps -> let stats = eps_stats eps
- in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
+ ; hsc_env <- getTopEnv
+ ; let hpt = hsc_HPT hsc_env
+ is_on_demand_home_decl
+ | isOneShotMode hpt
+ , Just home_unit <- hsc_home_unit_maybe hsc_env
+ , Just mod <- nameModule_maybe name
+ = isHomeModule home_unit mod
+ | otherwise
+ = False
+ ; if is_on_demand_home_decl
+ then liftIO $ hptBumpDeclsOut hpt
+ else updateEps_ (\eps -> let stats = eps_stats eps
+ in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
}
tc_fd :: FunDep IfLclName -> IfL (FunDep TyVar)
=====================================
compiler/GHC/Tc/Instance/Family.hs
=====================================
@@ -619,7 +619,7 @@ addLocalFamInst (home_fie, my_fis) fam_inst
-- we've ever seen. Fixing this is part of #13102.
; eps <- getEps
; extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv
- ; let inst_envs = (eps_fam_inst_env eps `unionFamInstEnv` extra, home_fie)
+ ; let inst_envs = (eps_fam_inst_env eps, home_fie `unionFamInstEnv` extra)
home_fie' = extendFamInstEnv home_fie fam_inst
-- Check for conflicting instance decls and injectivity violations
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -63,6 +63,10 @@ module GHC.Unit.Home.PackageTable
, hptLoadedCompleteMatches
, hptLoadedDefaults
, hptLoadedByteCode
+ , HptStats(..)
+ , hptLoadedStats
+ , hptBumpDeclsOut
+ , pprHptStats
-- ** More Traversal-based queries
, hptCollectDependencies
@@ -153,7 +157,6 @@ emptyOnDemandHomePackageTable = do
data HomeLoaderState = HomeLoaderState
{ hls_table :: DModuleNameEnv HomeModInfo
- , hls_modules :: ModuleEnv ()
, hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
, hls_type_env :: !TypeEnv
, hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
@@ -167,13 +170,13 @@ data HomeLoaderState = HomeLoaderState
, hls_ann_env :: !AnnEnv
, hls_complete_matches :: !CompleteMatches
, hls_defaults :: ModuleEnv DefaultEnv
+ , hls_stats :: !HptStats
}
emptyHomeLoaderState :: HomeLoaderState
emptyHomeLoaderState =
HomeLoaderState
{ hls_table = emptyUDFM
- , hls_modules = emptyModuleEnv
, hls_is_boot = emptyInstalledModuleEnv
, hls_type_env = emptyTypeEnv
, hls_iface_bytecode = emptyModuleEnv
@@ -184,6 +187,7 @@ emptyHomeLoaderState =
, hls_ann_env = emptyAnnEnv
, hls_complete_matches = []
, hls_defaults = emptyModuleEnv
+ , hls_stats = emptyHptStats
}
--------------------------------------------------------------------------------
@@ -248,6 +252,52 @@ hptLoadedByteCode :: HomePackageTable -> Module -> IO (Maybe (IO Linkable))
hptLoadedByteCode hpt mod =
queryOnDemandHpt Nothing (\ hls -> lookupModuleEnv (hls_iface_bytecode hls) mod) hpt
+hptLoadedStats :: HomePackageTable -> IO (Maybe HptStats)
+hptLoadedStats = queryOnDemandHpt Nothing (Just . hls_stats)
+
+hptBumpDeclsOut :: HomePackageTable -> IO ()
+hptBumpDeclsOut HPT_Make{} = pure ()
+hptBumpDeclsOut HPT_OneShot{loader} =
+ atomicModifyIORef' loader $ \ hls ->
+ let stats = hls_stats hls
+ in (hls { hls_stats = stats { hpt_n_decls_out = hpt_n_decls_out stats + 1 } }, ())
+
+data HptStats = HptStats
+ { hpt_n_ifaces_in :: !Int
+ , hpt_n_decls_in :: !Int
+ , hpt_n_decls_out :: !Int
+ , hpt_n_insts_in :: !Int
+ , hpt_n_rules_in :: !Int
+ }
+
+emptyHptStats :: HptStats
+emptyHptStats = HptStats
+ { hpt_n_ifaces_in = 0
+ , hpt_n_decls_in = 0
+ , hpt_n_decls_out = 0
+ , hpt_n_insts_in = 0
+ , hpt_n_rules_in = 0
+ }
+
+addHptInStats :: HptStats -> Int -> Int -> Int -> HptStats
+addHptInStats stats n_decls n_insts n_rules
+ = stats { hpt_n_ifaces_in = hpt_n_ifaces_in stats + 1
+ , hpt_n_decls_in = hpt_n_decls_in stats + n_decls
+ , hpt_n_insts_in = hpt_n_insts_in stats + n_insts
+ , hpt_n_rules_in = hpt_n_rules_in stats + n_rules }
+
+pprHptStats :: HptStats -> SDoc
+pprHptStats stats
+ = hcat [text "Home interface stats: ", msg]
+ where
+ msg = vcat
+ [int (hpt_n_ifaces_in stats) <+> text "interfaces read",
+ hsep [ int (hpt_n_decls_out stats), text "type/class/variable imported, out of",
+ int (hpt_n_decls_in stats), text "read"],
+ hsep [ int (hpt_n_insts_in stats), text "instance decls read"],
+ hsep [ int (hpt_n_rules_in stats), text "rule decls read"]
+ ]
+
listHptIfaces :: HomePackageTable -> IO (DModuleNameEnv HomeModInfo)
listHptIfaces = \ case
HPT_Make{table} -> readIORef table
@@ -306,13 +356,10 @@ addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
addOnDemandHomeModule HPT_Make{} _ _ _ _ = pure ()
addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) mb_bytecode = do
- atomicModifyIORef loader $ \hls ->
- ( if mn `elemModuleEnv` hls_modules hls
- then hls -- If already loaded, don't add twice
- else
- if bad_boot
- then addHomeModTypeEnv hls
- else addHomeModData hls
+ atomicModifyIORef' loader $ \hls ->
+ ( if bad_boot
+ then addHomeModTypeEnv hls
+ else addHomeModData hls
, ()
)
where
@@ -321,7 +368,6 @@ addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new
}
addHomeModData hls = hls {
- hls_modules = extendModuleEnv (hls_modules hls) mn (),
hls_type_env = extendNameEnvList (hls_type_env hls) new_decls,
-- Don't add an entry if the iface doesn't have Core bindings, so that
-- 'get_link_deps' knows that it should load object code.
@@ -348,7 +394,11 @@ addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new
extendModuleEnv (hls_mod_fam_inst_env hls)
mn
fam_inst_env,
- hls_defaults = extendModuleEnv (hls_defaults hls) mn new_defaults
+ hls_defaults = extendModuleEnv (hls_defaults hls) mn new_defaults,
+ hls_stats = addHptInStats (hls_stats hls)
+ (length new_decls)
+ (length new_insts)
+ (length new_rules)
}
hptSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/7198f0bd3a1d5e900e9012eba9e29ac…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/7198f0bd3a1d5e900e9012eba9e29ac…
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] Add eps stats, fix retainer leak, and make fam inst more consistent
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
bc53c2eb by fendor at 2026-11-30T14:27:20+01:00
Add eps stats, fix retainer leak, and make fam inst more consistent
- - - - -
7 changed files:
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Main/Hsc.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Unit/Home/PackageTable.hs
Changes:
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -468,7 +468,7 @@ doCorePass pass guts = do
p_fam_env <- getPackageFamInstEnv
l_fam_env <- getLazyHomeFamInstEnv
let platform = targetPlatform dflags
- let fam_envs = (p_fam_env `unionFamInstEnv` l_fam_env, mg_fam_inst_env guts)
+ let fam_envs = (p_fam_env, mg_fam_inst_env guts `unionFamInstEnv` l_fam_env)
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/Driver/Main/Compile.hs
=====================================
@@ -215,7 +215,7 @@ loadIfaceByteCode hsc_env iface location type_env =
where
compile decls = do
bco <- compileWholeCoreBindings hsc_env type_env decls
- return $! Linkable (gbc_hash bco) (mi_module iface) (pure (DotGBC bco))
+ return $! Linkable (gbc_hash bco) (wcb_module decls) (pure (DotGBC bco))
loadIfaceByteCodeLazy ::
HscEnv ->
=====================================
compiler/GHC/Driver/Main/Hsc.hs
=====================================
@@ -85,6 +85,7 @@ import GHC.Types.Error
import GHC.Types.Name.Cache ( newNameCache )
import GHC.Utils.Panic
+import qualified GHC.Utils.Outputable as Outputable
import GHC.Utils.Logger
import GHC.Utils.TmpFs
@@ -274,8 +275,10 @@ dumpIfaceStats hsc_env = do
logger = hsc_logger hsc_env
dump_rn_stats = logHasDumpFlag logger Opt_D_dump_rn_stats
dump_if_trace = logHasDumpFlag logger Opt_D_dump_if_trace
- when (dump_if_trace || dump_rn_stats) $
- logDumpMsg logger "Interface statistics" (ifaceStats eps)
+ when (dump_if_trace || dump_rn_stats) $ do
+ mb_home_stats <- hptLoadedStats (hsc_HPT hsc_env)
+ logDumpMsg logger "Interface statistics" $
+ ifaceStats eps Outputable.$$ maybe Outputable.empty pprHptStats mb_home_stats
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -918,7 +918,8 @@ addModIfacePartsToHpt gbl_env mod loc iface (new_decls, new_insts, new_defaults,
warnPprTrace bad_boot "loadInterface" (ppr mod) $ do
hpt <- getHpt
when (not bad_boot) $ do
- liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
+ let final_iface = stripLoadedIface "home package table" iface
+ liftIO $ addHomeModInfoToHpt (HomeModInfo final_iface details emptyHomeModInfoLinkable) hpt
liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) mb_bytecode
addModIfacePartsToEps :: Module -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
@@ -926,14 +927,7 @@ addModIfacePartsToEps mod iface (new_decls, new_insts, new_defaults, new_fam_ins
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")
+ final_iface = stripLoadedIface "PIT" iface
mhome_unit = ue_homeUnit (hsc_unit_env purged_hsc_env)
updateEps_ $ \ eps ->
@@ -970,6 +964,19 @@ addModIfacePartsToEps mod iface (new_decls, new_insts, new_defaults, new_fam_ins
}
+stripLoadedIface :: String -> ModIface -> ModIface
+stripLoadedIface table iface = iface
+ & set_mi_decls (gone "mi_decls")
+ & set_mi_insts (gone "mi_insts")
+ & set_mi_defaults (gone "mi_defaults")
+ & set_mi_fam_insts (gone "mi_fam_insts")
+ & set_mi_rules (gone "mi_rules")
+ & set_mi_anns (gone "mi_anns")
+ & set_mi_simplified_core (gone "mi_simplified_core")
+ where
+ gone :: String -> a
+ gone field = panic ("No " ++ field ++ " in " ++ table)
+
{- Note [Loading your own hi-boot file]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally speaking, when compiling module M, we should not
=====================================
compiler/GHC/IfaceToCore.hs
=====================================
@@ -138,6 +138,8 @@ 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
+import GHC.Unit.Home (isHomeModule)
+import GHC.Driver.Env (hsc_HPT, hsc_home_unit_maybe)
{-
This module takes
@@ -1103,8 +1105,19 @@ tc_iface_decl_fingerprint ignore_prags (_version, decl)
bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
bumpDeclStats name
= do { traceIf (text "Loading decl for" <+> ppr name)
- ; updateEps_ (\eps -> let stats = eps_stats eps
- in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
+ ; hsc_env <- getTopEnv
+ ; let hpt = hsc_HPT hsc_env
+ is_on_demand_home_decl
+ | isOneShotMode hpt
+ , Just home_unit <- hsc_home_unit_maybe hsc_env
+ , Just mod <- nameModule_maybe name
+ = isHomeModule home_unit mod
+ | otherwise
+ = False
+ ; if is_on_demand_home_decl
+ then liftIO $ hptBumpDeclsOut hpt
+ else updateEps_ (\eps -> let stats = eps_stats eps
+ in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
}
tc_fd :: FunDep IfLclName -> IfL (FunDep TyVar)
=====================================
compiler/GHC/Tc/Instance/Family.hs
=====================================
@@ -619,7 +619,7 @@ addLocalFamInst (home_fie, my_fis) fam_inst
-- we've ever seen. Fixing this is part of #13102.
; eps <- getEps
; extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv
- ; let inst_envs = (eps_fam_inst_env eps `unionFamInstEnv` extra, home_fie)
+ ; let inst_envs = (eps_fam_inst_env eps, home_fie `unionFamInstEnv` extra)
home_fie' = extendFamInstEnv home_fie fam_inst
-- Check for conflicting instance decls and injectivity violations
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -63,6 +63,10 @@ module GHC.Unit.Home.PackageTable
, hptLoadedCompleteMatches
, hptLoadedDefaults
, hptLoadedByteCode
+ , HptStats(..)
+ , hptLoadedStats
+ , hptBumpDeclsOut
+ , pprHptStats
-- ** More Traversal-based queries
, hptCollectDependencies
@@ -153,7 +157,6 @@ emptyOnDemandHomePackageTable = do
data HomeLoaderState = HomeLoaderState
{ hls_table :: DModuleNameEnv HomeModInfo
- , hls_modules :: ModuleEnv ()
, hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
, hls_type_env :: !TypeEnv
, hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
@@ -167,13 +170,13 @@ data HomeLoaderState = HomeLoaderState
, hls_ann_env :: !AnnEnv
, hls_complete_matches :: !CompleteMatches
, hls_defaults :: ModuleEnv DefaultEnv
+ , hls_stats :: !HptStats
}
emptyHomeLoaderState :: HomeLoaderState
emptyHomeLoaderState =
HomeLoaderState
{ hls_table = emptyUDFM
- , hls_modules = emptyModuleEnv
, hls_is_boot = emptyInstalledModuleEnv
, hls_type_env = emptyTypeEnv
, hls_iface_bytecode = emptyModuleEnv
@@ -184,6 +187,7 @@ emptyHomeLoaderState =
, hls_ann_env = emptyAnnEnv
, hls_complete_matches = []
, hls_defaults = emptyModuleEnv
+ , hls_stats = emptyHptStats
}
--------------------------------------------------------------------------------
@@ -248,6 +252,52 @@ hptLoadedByteCode :: HomePackageTable -> Module -> IO (Maybe (IO Linkable))
hptLoadedByteCode hpt mod =
queryOnDemandHpt Nothing (\ hls -> lookupModuleEnv (hls_iface_bytecode hls) mod) hpt
+hptLoadedStats :: HomePackageTable -> IO (Maybe HptStats)
+hptLoadedStats = queryOnDemandHpt Nothing (Just . hls_stats)
+
+hptBumpDeclsOut :: HomePackageTable -> IO ()
+hptBumpDeclsOut HPT_Make{} = pure ()
+hptBumpDeclsOut HPT_OneShot{loader} =
+ atomicModifyIORef' loader $ \ hls ->
+ let stats = hls_stats hls
+ in (hls { hls_stats = stats { hpt_n_decls_out = hpt_n_decls_out stats + 1 } }, ())
+
+data HptStats = HptStats
+ { hpt_n_ifaces_in :: !Int
+ , hpt_n_decls_in :: !Int
+ , hpt_n_decls_out :: !Int
+ , hpt_n_insts_in :: !Int
+ , hpt_n_rules_in :: !Int
+ }
+
+emptyHptStats :: HptStats
+emptyHptStats = HptStats
+ { hpt_n_ifaces_in = 0
+ , hpt_n_decls_in = 0
+ , hpt_n_decls_out = 0
+ , hpt_n_insts_in = 0
+ , hpt_n_rules_in = 0
+ }
+
+addHptInStats :: HptStats -> Int -> Int -> Int -> HptStats
+addHptInStats stats n_decls n_insts n_rules
+ = stats { hpt_n_ifaces_in = hpt_n_ifaces_in stats + 1
+ , hpt_n_decls_in = hpt_n_decls_in stats + n_decls
+ , hpt_n_insts_in = hpt_n_insts_in stats + n_insts
+ , hpt_n_rules_in = hpt_n_rules_in stats + n_rules }
+
+pprHptStats :: HptStats -> SDoc
+pprHptStats stats
+ = hcat [text "Home interface stats: ", msg]
+ where
+ msg = vcat
+ [int (hpt_n_ifaces_in stats) <+> text "interfaces read",
+ hsep [ int (hpt_n_decls_out stats), text "type/class/variable imported, out of",
+ int (hpt_n_decls_in stats), text "read"],
+ hsep [ int (hpt_n_insts_in stats), text "instance decls read"],
+ hsep [ int (hpt_n_rules_in stats), text "rule decls read"]
+ ]
+
listHptIfaces :: HomePackageTable -> IO (DModuleNameEnv HomeModInfo)
listHptIfaces = \ case
HPT_Make{table} -> readIORef table
@@ -306,13 +356,10 @@ addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
addOnDemandHomeModule HPT_Make{} _ _ _ _ = pure ()
addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) mb_bytecode = do
- atomicModifyIORef loader $ \hls ->
- ( if mn `elemModuleEnv` hls_modules hls
- then hls -- If already loaded, don't add twice
- else
- if bad_boot
- then addHomeModTypeEnv hls
- else addHomeModData hls
+ atomicModifyIORef' loader $ \hls ->
+ ( if bad_boot
+ then addHomeModTypeEnv hls
+ else addHomeModData hls
, ()
)
where
@@ -321,7 +368,6 @@ addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new
}
addHomeModData hls = hls {
- hls_modules = extendModuleEnv (hls_modules hls) mn (),
hls_type_env = extendNameEnvList (hls_type_env hls) new_decls,
-- Don't add an entry if the iface doesn't have Core bindings, so that
-- 'get_link_deps' knows that it should load object code.
@@ -348,7 +394,11 @@ addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new
extendModuleEnv (hls_mod_fam_inst_env hls)
mn
fam_inst_env,
- hls_defaults = extendModuleEnv (hls_defaults hls) mn new_defaults
+ hls_defaults = extendModuleEnv (hls_defaults hls) mn new_defaults,
+ hls_stats = addHptInStats (hls_stats hls)
+ (length new_decls)
+ (length new_insts)
+ (length new_rules)
}
hptSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/bc53c2eb6da117767a4710cf212e166…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/bc53c2eb6da117767a4710cf212e166…
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] Add lazy bytecode loading back
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
ce01df3c by fendor at 2026-11-30T14:04:05+01:00
Add lazy bytecode loading back
- - - - -
5 changed files:
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Unit/External.hs
- compiler/GHC/Unit/Home/PackageTable.hs
- compiler/GHC/Unit/Module/WholeCoreBindings.hs
Changes:
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -835,7 +835,7 @@ loadInterface doc_str mod from
massertPpr (moduleUnitId mod `Set.member` hsc_all_home_unit_ids hsc_env)
(text "Attempting to load 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 iface tcParts
+ addModIfacePartsToHpt gbl_env mod loc iface tcParts
else dontLeakTheHUG $ do
-- Load the new ModIface into the External Package State
--
@@ -857,7 +857,7 @@ loadInterface doc_str mod from
(moduleUnitId mod `Set.notMember` hsc_all_home_unit_ids hsc_env)
(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 mod loc iface tcParts
+ addModIfacePartsToEps mod iface tcParts
; -- invoke plugins with *full* interface, not final_iface, to ensure
-- that plugins have access to declarations, etc.
@@ -885,8 +885,12 @@ tcPartsOfTheIface mod iface = do
, new_complete_matches
)
-addModIfacePartsToHpt :: IfGblEnv -> Module -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
-addModIfacePartsToHpt gbl_env mod iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+addModIfacePartsToHpt :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToHpt gbl_env mod loc iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+ -- NB: this is the full 'HscEnv', not one purged by 'dontLeakTheHUG':
+ -- compiling the Core bindings to bytecode typechecks them, which may need
+ -- to look up other home modules, and those live in the HPT.
+ hsc_env <- getTopEnv
let
details = ModDetails
{ md_types = mkNameEnv new_decls
@@ -905,14 +909,20 @@ addModIfacePartsToHpt gbl_env mod iface (new_decls, new_insts, new_defaults, new
-- 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, if the interface has any.
+ --
+ -- See Note [Interface Files with Core Definitions]
+ mb_bytecode = loadIfaceByteCode hsc_env iface loc (md_types details)
+
warnPprTrace bad_boot "loadInterface" (ppr mod) $ do
hpt <- getHpt
when (not bad_boot) $ do
liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
- liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches)
+ liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) mb_bytecode
-addModIfacePartsToEps :: Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
-addModIfacePartsToEps mod loc iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+addModIfacePartsToEps :: Module -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToEps mod iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
purged_hsc_env <- getTopEnv
let
@@ -924,17 +934,6 @@ addModIfacePartsToEps mod loc iface (new_decls, new_insts, new_defaults, new_fam
& 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")
- -- 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_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
mhome_unit = ue_homeUnit (hsc_unit_env purged_hsc_env)
updateEps_ $ \ eps ->
@@ -944,7 +943,6 @@ addModIfacePartsToEps mod loc iface (new_decls, new_insts, new_defaults, new_fam
eps {
eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
eps_PTE = addDeclsToPTE (eps_PTE eps) new_decls,
- eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
eps_rule_base = extendRuleBaseList (eps_rule_base eps)
new_rules,
eps_complete_matches
=====================================
compiler/GHC/Linker/Loader.hs
=====================================
@@ -90,7 +90,7 @@ import GHC.Utils.TmpFs
import GHC.Unit.Env
import GHC.Unit.Home.ModInfo
-import GHC.Unit.External (ExternalPackageState (..))
+import GHC.Unit.Home.PackageTable (hptLoadedByteCode)
import GHC.Unit.Module
import GHC.Unit.Module.ModNodeKey
import GHC.Unit.Module.Graph
@@ -661,13 +661,18 @@ initLinkDepsOpts hsc_env = opts
Nothing -> findWholeCoreBindings hsc_env mod
Just bco -> return (Just bco)
+-- | Compile the Core bindings stored in the interface of a home module to
+-- bytecode, if the interface has any. Only used in one-shot mode, where home
+-- modules are loaded on demand into the 'HomePackageTable'.
+--
+-- See Note [Interface Files with Core Definitions]
findWholeCoreBindings :: HscEnv -> Module -> IO (Maybe Linkable)
findWholeCoreBindings hsc_env mod = do
_ <- initIfaceLoad hsc_env $
loadInterface (text "get_reachable_nodes" <+> parens (ppr mod))
mod ImportBySystem
- EPS {eps_iface_bytecode} <- hscEPS hsc_env
- sequence (lookupModuleEnv eps_iface_bytecode mod)
+ mb_action <- hptLoadedByteCode (hsc_HPT hsc_env) mod
+ sequence mb_action
findBytecodeLinkableMaybe :: HscEnv -> ModLocation -> IO (Maybe Linkable)
=====================================
compiler/GHC/Unit/External.hs
=====================================
@@ -36,8 +36,6 @@ import GHC.Types.Unique.DSet
import GHC.Utils.Fingerprint ( Fingerprint )
-import GHC.Linker.Types (Linkable)
-
import Data.IORef
@@ -74,7 +72,6 @@ initExternalPackageState = EPS
{ eps_PIT = emptyPackageIfaceTable
, eps_free_holes = emptyInstalledModuleEnv
, eps_PTE = emptyTypeEnv
- , eps_iface_bytecode = emptyModuleEnv
, eps_inst_env = emptyInstEnv
, eps_fam_inst_env = emptyFamInstEnv
, eps_rule_base = mkRuleBase builtinRules
@@ -135,12 +132,6 @@ data ExternalPackageState
-- interface files we have sucked in. The domain of
-- the mapping is external-package modules
- -- | If an interface was written with @-fwrite-if-simplified-core@, this
- -- will contain an IO action that compiles bytecode from core bindings.
- --
- -- See Note [Interface Files with Core Definitions]
- eps_iface_bytecode :: !(ModuleEnv (IO Linkable)),
-
eps_known_keys :: ModuleEnv (Fingerprint, KnownKeyNameMaps),
-- ^ Cache of the known-entity maps of all loaded 'GHC.Essentials'
-- modules, keyed by module and the corresponding interface ABI hash.
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -62,6 +62,7 @@ module GHC.Unit.Home.PackageTable
, hptLoadedAnnEnv
, hptLoadedCompleteMatches
, hptLoadedDefaults
+ , hptLoadedByteCode
-- ** More Traversal-based queries
, hptCollectDependencies
@@ -101,6 +102,7 @@ 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
@@ -154,7 +156,10 @@ data HomeLoaderState = HomeLoaderState
, hls_modules :: ModuleEnv ()
, hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
, hls_type_env :: !TypeEnv
- -- , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
+ , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
+ -- ^ Actions that compile the Core bindings stored in a loaded interface
+ -- to bytecode, for modules whose interface has Core bindings.
+ -- See Note [Interface Files with Core Definitions]
, hls_inst_env :: !InstEnv
, hls_fam_inst_env :: !FamInstEnv
, hls_mod_fam_inst_env :: !(ModuleEnv FamInstEnv)
@@ -171,7 +176,7 @@ emptyHomeLoaderState =
, hls_modules = emptyModuleEnv
, hls_is_boot = emptyInstalledModuleEnv
, hls_type_env = emptyTypeEnv
- -- , hls_iface_bytecode = emptyModuleEnv
+ , hls_iface_bytecode = emptyModuleEnv
, hls_inst_env = emptyInstEnv
, hls_fam_inst_env = emptyFamInstEnv
, hls_mod_fam_inst_env = emptyModuleEnv
@@ -234,6 +239,15 @@ hptLoadedCompleteMatches = queryOnDemandHpt [] hls_complete_matches
hptLoadedDefaults :: HomePackageTable -> IO (ModuleEnv DefaultEnv)
hptLoadedDefaults = queryOnDemandHpt emptyModuleEnv hls_defaults
+-- | The action that compiles the Core bindings of an on-demand loaded home
+-- module to bytecode, if its interface contains Core bindings.
+-- Always 'Nothing' for a 'HPT_Make' table.
+--
+-- See Note [Interface Files with Core Definitions]
+hptLoadedByteCode :: HomePackageTable -> Module -> IO (Maybe (IO Linkable))
+hptLoadedByteCode hpt mod =
+ queryOnDemandHpt Nothing (\ hls -> lookupModuleEnv (hls_iface_bytecode hls) mod) hpt
+
listHptIfaces :: HomePackageTable -> IO (DModuleNameEnv HomeModInfo)
listHptIfaces = \ case
HPT_Make{table} -> readIORef table
@@ -289,9 +303,9 @@ restrictHpt HPT_OneShot{} _ = pure ()
addListToHpt :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> IO ()
addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
-addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IO ()
-addOnDemandHomeModule HPT_Make{} _ _ _ = pure ()
-addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
+addOnDemandHomeModule HPT_Make{} _ _ _ _ = pure ()
+addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) mb_bytecode = do
atomicModifyIORef loader $ \hls ->
( if mn `elemModuleEnv` hls_modules hls
then hls -- If already loaded, don't add twice
@@ -309,6 +323,11 @@ addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new
addHomeModData hls = hls {
hls_modules = extendModuleEnv (hls_modules hls) mn (),
hls_type_env = extendNameEnvList (hls_type_env hls) new_decls,
+ -- Don't add an entry if the iface doesn't have Core bindings, so that
+ -- 'get_link_deps' knows that it should load object code.
+ hls_iface_bytecode = case mb_bytecode of
+ Nothing -> hls_iface_bytecode hls
+ Just action -> extendModuleEnv (hls_iface_bytecode hls) mn action,
hls_rule_base = extendRuleBaseList (hls_rule_base hls)
new_rules,
hls_complete_matches
=====================================
compiler/GHC/Unit/Module/WholeCoreBindings.hs
=====================================
@@ -84,21 +84,18 @@ settings.
2. In oneshot mode, which compiles individual modules without a shared home unit
graph, a previously compiled module is not reprocessed as described for make
mode above.
+ Instead, home modules are loaded on demand by 'loadInterface' into the
+ one-shot 'HomePackageTable' (its 'HomeLoaderState').
When 'get_link_deps' encounters a dependency on a local module, it requests
- its bytecode from the External Package State, who loads the interface
- on-demand.
+ its bytecode from there via 'findWholeCoreBindings', which loads the
+ interface on-demand.
- Since the EPS stores interfaces for all package dependencies in addition to
- local modules in oneshot mode, it has a substantial memory footprint.
- We try to curtail that by extracting important data into specialized fields
- in the EPS, and retaining only a few fields of 'ModIface' by overwriting the
- others with bottom values.
-
- In order to avoid keeping around all of the interface's components needed for
- compiling bytecode, we instead store an IO action in 'eps_iface_bytecode'.
+ When a home interface with Core bindings is loaded, we store an IO action
+ that compiles them to bytecode in 'hls_iface_bytecode', rather than
+ compiling eagerly.
When 'get_link_deps' evaluates this action, the result is not retained in the
- EPS, but stored in 'LoaderState', where it may eventually get evicted to free
- up the memory.
+ home package table, but stored in 'LoaderState', where it may eventually get
+ evicted to free up the memory.
This IO action retains the dehydrated Core bindings from the interface in its
closure.
Like the bytecode 'Linkable' stored in 'LoaderState', this is preferable to
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/ce01df3c694ce6addc428d208158c1b…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/ce01df3c694ce6addc428d208158c1b…
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] 2 commits: Add testcase for one-shot and bytecode
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
3f3a9049 by fendor at 2026-11-30T13:55:11+01:00
Add testcase for one-shot and bytecode
- - - - -
1f02fa8d by Hannes Siebenhandl at 2026-11-30T13:55:12+01:00
Experiment with separate table types for inOneShot mode
- - - - -
26 changed files:
- compiler/GHC.hs
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Core/Rules.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Main/Hsc.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Utils/Instantiate.hs
- compiler/GHC/Unit/Env.hs
- compiler/GHC/Unit/Home/Graph.hs
- compiler/GHC/Unit/Home/PackageTable.hs
- compiler/GHC/Unit/Module/Env.hs
- ghc/GHCi/Leak.hs
- testsuite/tests/bytecode/T25090/Makefile
- testsuite/tests/bytecode/T25090/all.T
- + testsuite/tests/driver/one-shot-boot/A.hs
- + testsuite/tests/driver/one-shot-boot/B.hs
- + testsuite/tests/driver/one-shot-boot/Fam.hs
- + testsuite/tests/driver/one-shot-boot/M.hs
- + testsuite/tests/driver/one-shot-boot/M.hs-boot
- + testsuite/tests/driver/one-shot-boot/Main.hs
- + testsuite/tests/driver/one-shot-boot/Makefile
- + testsuite/tests/driver/one-shot-boot/all.T
- + testsuite/tests/driver/one-shot-boot/one-shot-boot.stdout
Changes:
=====================================
compiler/GHC.hs
=====================================
@@ -442,13 +442,14 @@ import GHC.Types.PkgQual
import GHC.Unit
import GHC.Unit.Env as UnitEnv
import GHC.Unit.Finder
-import GHC.Unit.Module.ModIface
-import GHC.Unit.Module.ModGuts
+import GHC.Unit.Home.Graph qualified as HUG
+import GHC.Unit.Home.ModInfo
+import GHC.Unit.Home.PackageTable qualified as HPT
+import GHC.Unit.Module.Graph
import GHC.Unit.Module.ModDetails
+import GHC.Unit.Module.ModGuts
+import GHC.Unit.Module.ModIface
import GHC.Unit.Module.ModSummary
-import GHC.Unit.Module.Graph
-import GHC.Unit.Home.ModInfo
-import qualified GHC.Unit.Home.Graph as HUG
import Control.Applicative ((<|>))
import Control.Monad
@@ -693,14 +694,43 @@ setUnitDynFlagsNoCheck uid dflags1 = do
(unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags1 (hscUIC hsc_env) (hsc_all_home_unit_ids hsc_env)
updated_dflags <- liftIO $ updatePlatformConstants dflags1 mconstants
- let upd hue =
- hue
- { homeUnitEnv_units = unit_state
- , homeUnitEnv_dflags = updated_dflags
- , homeUnitEnv_home_unit = Just home_unit
- }
+ let
+ upd hue = do
+ let
+ warnOnNonEmptyTable =
+ whenM (not <$> HPT.isHptEmpty (homeUnitEnv_hpt hue)) $ do
+ logInfo logger
+ ( text "Changed the ghc mode" <+> ppr (ghcMode $ homeUnitEnv_dflags hue) <+> text "to" <+> ppr (ghcMode updated_dflags) $$
+ text "The home package table was not empty!" $$
+ text "The table was cleared any way."
+ )
+ the_hpt <-
+ case (HPT.isOneShotMode (homeUnitEnv_hpt hue), ghcMode updated_dflags) of
+ (True, OneShot) ->
+ pure $ homeUnitEnv_hpt hue
+ (True, CompManager) -> do
+ warnOnNonEmptyTable
+ HPT.emptyHomePackageTable
+ (True, MkDepend) -> do
+ warnOnNonEmptyTable
+ HPT.emptyHomePackageTable
+ (False, OneShot) -> do
+ warnOnNonEmptyTable
+ HPT.emptyOnDemandHomePackageTable
+ (False, CompManager) ->
+ pure $ homeUnitEnv_hpt hue
+ (False, MkDepend) ->
+ pure $ homeUnitEnv_hpt hue
+ pure hue
+ { homeUnitEnv_units = unit_state
+ , homeUnitEnv_dflags = updated_dflags
+ , homeUnitEnv_home_unit = Just home_unit
+ , homeUnitEnv_hpt = the_hpt
+ }
+
+
- let unit_env = UnitEnv.ue_updateHomeUnitEnv upd uid (hsc_unit_env hsc_env)
+ unit_env <- liftIO $ UnitEnv.ue_adjustHomeUnitEnvA upd uid (hsc_unit_env hsc_env)
let dflags = updated_dflags
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -102,7 +102,7 @@ core2core hsc_env guts@(ModGuts { mg_module = mod
logger = hsc_logger hsc_env
unit_env = hsc_unit_env hsc_env
extra_vars = interactiveInScope (hsc_IC hsc_env)
- home_pkg_rules = hugRulesBelow hsc_env (moduleUnitId mod)
+ home_pkg_rules = hugRulesBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) (moduleUnitId mod)
(GWIB { gwib_mod = moduleName mod, gwib_isBoot = NotBoot })
name_ppr_ctx = mkNamePprCtx ptc unit_env rdr_env
ptc = initPromotionTickContext dflags
=====================================
compiler/GHC/Core/Rules.hs
=====================================
@@ -401,7 +401,7 @@ lookupRuleBase = lookupUFM
unionRuleBase :: RuleBase -> RuleBase -> RuleBase
unionRuleBase
- = plusUFM
+ = plusUFM_C (++)
pprRuleBase :: RuleBase -> SDoc
pprRuleBase rules = pprUFM rules $ \rss ->
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -99,6 +99,7 @@ import Data.IORef
import qualified Data.Set as Set
import GHC.Types.Name.Reader (ExactRdrName(..))
import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import qualified GHC.Unit.Home.PackageTable as HPT
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env hsc = do
@@ -259,26 +260,26 @@ hscUIC hsc_env = ue_uic (hsc_unit_env hsc_env)
-- | Find all rules in modules that are in the transitive closure of the given
-- module.
-hugRulesBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO RuleBase
-hugRulesBelow hsc_env uid mn = foldr (flip extendRuleBaseList) emptyRuleBase <$>
- hugSomeThingsBelowUs (md_rules . hm_details) False hsc_env uid mn
+hugRulesBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO RuleBase
+hugRulesBelow mg hug uid mn = foldr (flip extendRuleBaseList) emptyRuleBase <$>
+ hugSomeThingsBelowUs (md_rules . hm_details) False mg hug uid mn
-- | Get annotations from all modules "below" this one (in the dependency
-- sense) within the home units. If the module is @Nothing@, returns /all/
-- annotations in the home units.
-hugAnnsBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO AnnEnv
-hugAnnsBelow hsc_env uid mn = foldr (flip extendAnnEnvList) emptyAnnEnv <$>
- hugSomeThingsBelowUs (md_anns . hm_details) False hsc_env uid mn
+hugAnnsBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO AnnEnv
+hugAnnsBelow mg hug uid mn = foldr (flip extendAnnEnvList) emptyAnnEnv <$>
+ hugSomeThingsBelowUs (md_anns . hm_details) False mg hug uid mn
-- | Find all COMPLETE pragmas in modules that are in the transitive closure of the
-- given module.
-hugCompleteSigsBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO CompleteMatches
-hugCompleteSigsBelow hsc uid mn = foldr (++) [] <$>
- hugSomeThingsBelowUs (md_complete_matches . hm_details) False hsc uid mn
+hugCompleteSigsBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO CompleteMatches
+hugCompleteSigsBelow mg hug uid mn = foldr (++) [] <$>
+ hugSomeThingsBelowUs (md_complete_matches . hm_details) False mg hug uid mn
-- | Find instances visible from the given set of imports
-hugInstancesBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst])
-hugInstancesBelow hsc_env uid mnwib = do
+hugInstancesBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst])
+hugInstancesBelow mg hug uid mnwib = do
let mn = mkModule uid (gwib_mod mnwib)
(insts, famInsts) <-
unzip . concat <$>
@@ -289,7 +290,8 @@ hugInstancesBelow hsc_env uid mnwib = do
then []
else [(md_insts details, md_fam_insts details)])
True -- Include -hi-boot
- hsc_env
+ mg
+ hug
uid
mnwib
return (foldl' unionInstEnv emptyInstEnv insts, concat famInsts)
@@ -297,17 +299,18 @@ hugInstancesBelow hsc_env uid mnwib = do
-- | Get things from modules in the transitive closure of the given module.
--
-- Note: Don't expose this function. This is a footgun if exposed!
-hugSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO [[a]]
+hugSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO [[a]]
-- An explicit check to see if we are in one-shot mode to avoid poking the ModuleGraph thunk
-- These things are currently stored in the EPS for home packages. (See #25795 for
-- progress in removing these kind of checks; and making these functions of
-- `UnitEnv` rather than `HscEnv`)
-- See Note [The ModuleGraph]
-hugSomeThingsBelowUs _ _ hsc_env _ _ | isOneShot (ghcMode (hsc_dflags hsc_env)) = return []
-hugSomeThingsBelowUs extract include_hi_boot hsc_env uid mn
- = let hug = hsc_HUG hsc_env
- mg = hsc_mod_graph hsc_env
- in
+hugSomeThingsBelowUs extract include_hi_boot mg hug uid mn =
+ -- If the first hpt is a one-shot table, we don't recurse into it.
+ -- TODO @fendor: I guess that's nonsense to a certain degree
+ if HPT.isOneShotMode $ homeUnitEnv_hpt $ unitEnv_lookup uid hug
+ then pure []
+ else
sequence
[ things
-- "Finding each non-hi-boot module below me" maybe could be cached (well,
@@ -347,7 +350,7 @@ prepareAnnotations hsc_env mb_guts = do
-- entries regardless of dependency ordering.
get_mod mg = (moduleUnitId (mg_module mg), GWIB (moduleName (mg_module mg)) NotBoot)
home_pkg_anns <- fromMaybe (hugAllAnns (hsc_unit_env hsc_env))
- $ uncurry (hugAnnsBelow hsc_env)
+ $ uncurry (hugAnnsBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env))
. get_mod <$> mb_guts
more_home_pkg_anns <- HomePackageTable.hptLoadedAnnEnv $ hsc_HPT hsc_env
let
=====================================
compiler/GHC/Driver/Main/Hsc.hs
=====================================
@@ -107,7 +107,10 @@ import System.IO
newHscEnv :: FilePath -> DynFlags -> IO HscEnv
newHscEnv top_dir dflags = do
- hpt <- emptyHomePackageTable
+ hpt <- case ghcMode dflags of
+ OneShot -> emptyOnDemandHomePackageTable
+ CompManager -> emptyHomePackageTable
+ MkDepend -> emptyHomePackageTable
newHscEnvWithHUG top_dir dflags (homeUnitId_ dflags) (home_unit_graph hpt)
where
home_unit_graph hpt = HUG.unitEnv_singleton
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -100,66 +100,65 @@ import GHC.Builtin.PrimOps.Ids
import GHC.Builtin.WiredIn.Prim
import GHC.Builtin.WiredIn.Ids( seqId )
+import GHC.Core (CoreRule)
+import GHC.Core.FamInstEnv
+import GHC.Core.InstEnv
import GHC.Core.Rules
import GHC.Core.TyCon
-import GHC.Core.InstEnv
-import GHC.Core.FamInstEnv
-import GHC.Parser.Annotation( noLocA, noAnn )
+import GHC.Parser.Annotation (noAnn, noLocA)
import GHC.Types.Annotations
+import GHC.Types.Avail
+import GHC.Types.DefaultEnv (DefaultEnv)
+import GHC.Types.Fixity
+import GHC.Types.Fixity.Env
import GHC.Types.Id
import GHC.Types.Name
import GHC.Types.Name.Cache
import GHC.Types.Name.Env
import GHC.Types.Name.Reader
-import GHC.Types.Avail
-import GHC.Types.Fixity
-import GHC.Types.Fixity.Env
+import GHC.Types.PkgQual
+import GHC.Types.SafeHaskell
import GHC.Types.SourceError
import GHC.Types.SourceFile
-import GHC.Types.SafeHaskell
-import GHC.Types.TypeEnv
-import GHC.Types.Unique.DSet
-import GHC.Types.Unique.Map( listToUniqMap )
-import GHC.Types.Unique.FM( UniqFM, listToUFM, lookupUFM, elemUFM )
+import GHC.Types.SourceText
import GHC.Types.SrcLoc
import GHC.Types.TyThing
-import GHC.Types.PkgQual
-import GHC.Types.SourceText
+import GHC.Types.TypeEnv
+import GHC.Types.Unique.DSet
+import GHC.Types.Unique.FM (UniqFM, elemUFM, listToUFM, lookupUFM)
+import GHC.Types.Unique.Map (listToUniqMap)
+import GHC.Unit.Env
import GHC.Unit.External
+import GHC.Unit.Finder
+import GHC.Unit.Home
+import GHC.Unit.Home.Graph qualified as HUG
+import GHC.Unit.Home.ModInfo (HomeModInfo (..), emptyHomeModInfoLinkable)
+import GHC.Unit.Home.PackageTable
+import GHC.Unit.Home.PackageTable qualified as HomePackageTable
import GHC.Unit.Module
+import GHC.Unit.Module.Deps
import GHC.Unit.Module.Graph
-import GHC.Unit.Module.Warnings
+import GHC.Unit.Module.ModDetails (ModDetails (..))
import GHC.Unit.Module.ModIface
-import GHC.Unit.Module.Deps
+import GHC.Unit.Module.Warnings
import GHC.Unit.State
-import GHC.Unit.Home
-import qualified GHC.Unit.Home.Graph as HUG
-import GHC.Unit.Home.PackageTable
-import GHC.Unit.Finder
-import GHC.Unit.Env
import GHC.Stack( callStack )
import GHC.Data.Maybe
import Language.Haskell.Syntax.Lit (StringLiteral(..))
+import Control.Applicative ((<|>))
import Control.Monad
-import qualified Data.Foldable as Foldable
+import Data.Foldable qualified as Foldable
import Data.Function ((&))
-import Data.Map ( toList )
-import qualified Data.Set as Set
-import System.FilePath
+import Data.Map (toList)
+import Data.Set qualified as Set
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 ((<|>))
+import System.FilePath
{- *********************************************************************
@@ -799,8 +798,8 @@ loadInterface doc_str mod from
-- READ THE MODULE IN
; hpt <- getHpt
- ; hls <- liftIO (hptLoaderState hpt)
- ; read_result <- case wantHiBootFile mhome_unit hls mod from of
+ ; is_boot_map <- liftIO (hptLoadedIsBoot hpt)
+ ; read_result <- case wantHiBootFile mhome_unit is_boot_map mod from of
Failed err -> return (Failed err)
Succeeded hi_boot_file -> do
hsc_env <- getTopEnv
@@ -834,9 +833,9 @@ loadInterface doc_str mod from
; 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))
+ (text "Attempting to load 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
+ addModIfacePartsToHpt gbl_env mod iface tcParts
else dontLeakTheHUG $ do
-- Load the new ModIface into the External Package State
--
@@ -858,7 +857,7 @@ loadInterface doc_str mod from
(moduleUnitId mod `Set.notMember` hsc_all_home_unit_ids hsc_env)
(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
+ addModIfacePartsToEps mod loc iface tcParts
; -- invoke plugins with *full* interface, not final_iface, to ensure
-- that plugins have access to declarations, etc.
@@ -868,37 +867,36 @@ loadInterface doc_str mod from
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)
+ ignore_prags <- goptM Opt_IgnoreInterfacePragmas
+ new_decls <- tcIfaceDecls ignore_prags (mi_decls iface)
+ new_insts <- mapM tcIfaceInst (mi_insts iface)
+ new_defaults <- tcIfaceDefaults mod (mi_defaults iface)
+ new_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
+ new_rules <- tcIfaceRules ignore_prags (mi_rules iface)
+ new_anns <- tcIfaceAnnotations (mi_anns iface)
+ new_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
+ ( new_decls
+ , new_insts
+ , new_defaults
+ , new_fam_insts
+ , new_rules
+ , new_anns
+ , new_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
+addModIfacePartsToHpt :: IfGblEnv -> Module -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToHpt gbl_env mod iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
let
details = ModDetails
- { md_types = mkNameEnv new_eps_decls
+ { md_types = mkNameEnv new_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
+ , md_defaults = new_defaults
+ , md_insts = mkInstEnv new_insts
+ , md_fam_insts = new_fam_insts
+ , md_rules = new_rules
+ , md_anns = new_anns
+ , md_complete_matches = new_complete_matches
}
bad_boot = mi_boot iface == IsBoot
@@ -909,16 +907,12 @@ addModIfacePartsToHpt gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_e
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 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
+ when (not bad_boot) $ do
+ liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
+ liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches)
-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
+addModIfacePartsToEps :: Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToEps mod loc iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
purged_hsc_env <- getTopEnv
let
@@ -930,19 +924,12 @@ addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_e
& 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)
+ | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_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.
@@ -950,43 +937,39 @@ addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_e
= old
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
- }
+ updateEps_ $ \ eps ->
+ if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface
+ then eps
+ else
+ eps {
+ eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
+ eps_PTE = addDeclsToPTE (eps_PTE eps) new_decls,
+ eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
+ eps_rule_base = extendRuleBaseList (eps_rule_base eps)
+ new_rules,
+ eps_complete_matches
+ = eps_complete_matches eps ++ new_complete_matches,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps)
+ new_insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
+ new_fam_insts,
+ eps_ann_env = extendAnnEnvList (eps_ann_env eps)
+ new_anns,
+ eps_mod_fam_inst_env
+ = let
+ fam_inst_env =
+ extendFamInstEnvList emptyFamInstEnv
+ new_fam_insts
+ in
+ extendModuleEnv (eps_mod_fam_inst_env eps)
+ mod
+ fam_inst_env,
+ eps_stats = addEpsInStats (eps_stats eps)
+ (length new_decls)
+ (length new_insts)
+ (length new_rules),
+ eps_defaults = extendModuleEnv (eps_defaults eps) mod new_defaults
+ }
{- Note [Loading your own hi-boot file]
@@ -1204,10 +1187,10 @@ moduleFreeHolesPrecise doc_str mod
return (Succeeded (renameFreeHoles ifhs insts))
Failed err -> return (Failed err)
-wantHiBootFile :: Maybe HomeUnit -> HomeLoaderState -> Module -> WhereFrom
+wantHiBootFile :: Maybe HomeUnit -> InstalledModuleEnv ModuleNameWithIsBoot -> Module -> WhereFrom
-> MaybeErr MissingInterfaceError IsBootInterface
-- Figure out whether we want Foo.hi or Foo.hi-boot
-wantHiBootFile mhome_unit hls mod from
+wantHiBootFile mhome_unit is_boot_map mod from
= case from of
ImportByUser usr_boot
| usr_boot == IsBoot && notHomeModuleMaybe mhome_unit mod
@@ -1226,9 +1209,9 @@ wantHiBootFile mhome_unit hls mod from
-- We never import boot modules from other packages!
| otherwise
- -> case hlsIsBoot hls (toUnitId <$> mod) of
- Just is_boot ->
- Succeeded is_boot
+ -> case lookupInstalledModuleEnv is_boot_map (toUnitId <$> mod) of
+ Just mnib ->
+ Succeeded $ gwib_isBoot mnib
Nothing ->
Succeeded NotBoot
-- The boot-ness of the requested interface,
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -427,10 +427,9 @@ checkVersions hsc_env mod_summary iface self_recomp
-- (in which case we are done with this module) or it'll fail (in which
-- case we'll compile the module from scratch anyhow).
- when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- ; hpt <- getHpt
- ; liftIO $ hlsSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface))
- }
+ ; hpt <- getHpt
+ ; liftIO $ hptSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface))
+
; recomp <- checkList [checkModUsage (hsc_FC hsc_env) u
| u <- mi_sr_usages self_recomp]
; case recomp of (NeedsRecompile reason) -> return $ OutOfDateItem reason (Just iface) ; _ -> do {
=====================================
compiler/GHC/IfaceToCore.hs
=====================================
@@ -633,12 +633,12 @@ tcHiBootIface hsc_src mod
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
do { hpt <- getHpt
- ; hls <- liftIO $ hptLoaderState hpt
- ; case hlsIsBoot hls (toUnitId <$> mod) of
+ ; is_boot_map <- liftIO $ hptLoadedIsBoot hpt
+ ; case lookupInstalledModuleEnv is_boot_map (toUnitId <$> mod) of
-- The typical case
Nothing -> return NoSelfBoot
-- error cases
- Just is_boot -> case is_boot of
+ Just mnib -> case gwib_isBoot mnib of
IsBoot ->
let diag = Can'tFindInterface err
(LookingForHiBoot mod)
=====================================
compiler/GHC/Tc/Module.hs
=====================================
@@ -191,7 +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)
+import GHC.Unit.Home.PackageTable (hptSetBootInfo)
{-
************************************************************************
@@ -501,21 +501,19 @@ tcRnImports hsc_env import_decls
-- modules batch (@--make@) compiled before this one, but
-- which are not below this one.
; (home_insts, home_fam_insts) <- liftIO $
- hugInstancesBelow hsc_env unitId mnwib
+ hugInstancesBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) unitId mnwib
-- We use 'unsafeInterleaveIO' to avoid redundant memory allocations
-- See Note [Lazily loading COMPLETE pragmas] from GHC.HsToCore.Monad
-- and see https://gitlab.haskell.org/ghc/ghc/-/merge_requests/14274#note_620545
; completeSigsBelow <- liftIO $ unsafeInterleaveIO $
- hugCompleteSigsBelow hsc_env unitId mnwib
+ hugCompleteSigsBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) unitId mnwib
- -- Record boot-file info in the EPS, so that it's
+ -- Record boot-file info in the HPT, so that it's
-- visible to loadHiBootInterface in tcRnSrcDecls,
-- and any other incrementally-performed imports
- ; when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- ; hpt <- getHpt
- ; liftIO $ hlsSetBootInfo hpt (imp_boot_mods imports)
- }
+ ; hpt <- getHpt
+ ; liftIO $ hptSetBootInfo hpt (imp_boot_mods imports)
-- Update the gbl env
; updGblEnv ( \ gbl ->
=====================================
compiler/GHC/Tc/Utils/Instantiate.hs
=====================================
@@ -947,13 +947,6 @@ 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/Unit/Env.hs
=====================================
@@ -52,6 +52,7 @@ module GHC.Unit.Env
, ue_unitHomeUnit
, ue_unitHomeUnit_maybe
, ue_updateHomeUnitEnv
+ , ue_adjustHomeUnitEnvA
, ue_all_home_unit_ids
, ue_unsafeHomeUnit
@@ -360,6 +361,13 @@ ue_updateHomeUnitEnv f uid e = e
{ ue_home_unit_graph = HUG.unitEnv_adjust f uid $ ue_home_unit_graph e
}
+ue_adjustHomeUnitEnvA :: Applicative f => (HomeUnitEnv -> f HomeUnitEnv) -> UnitId -> UnitEnv -> f UnitEnv
+ue_adjustHomeUnitEnvA f uid e =
+ let
+ hugA = HUG.unitEnv_adjustA f uid $ ue_home_unit_graph e
+ in
+ (\ hug -> e { ue_home_unit_graph = hug }) <$> hugA
+
ue_all_home_unit_ids :: UnitEnv -> Set.Set UnitId
ue_all_home_unit_ids = HUG.allUnits . ue_home_unit_graph
=====================================
compiler/GHC/Unit/Home/Graph.hs
=====================================
@@ -61,6 +61,8 @@ module GHC.Unit.Home.Graph
, unitEnv_foldWithKey
, unitEnv_singleton
, unitEnv_adjust
+ , unitEnv_adjustA
+ , unitEnv_alterF
, unitEnv_keys
, unitEnv_insert
, unitEnv_new
@@ -320,6 +322,17 @@ unitEnv_adjust f uid unitEnv = unitEnv
{ unitEnv_graph = Map.adjust f uid (unitEnv_graph unitEnv)
}
+unitEnv_adjustA :: Applicative f => (v -> f v) -> UnitEnvGraphKey -> UnitEnvGraph v -> f (UnitEnvGraph v)
+unitEnv_adjustA f uid unitEnv =
+ unitEnv_alterF go uid unitEnv
+ where
+ go Nothing = pure Nothing
+ go (Just v) = Just <$> f v
+
+unitEnv_alterF :: Functor f => (Maybe v -> f (Maybe v)) -> UnitEnvGraphKey -> UnitEnvGraph v -> f (UnitEnvGraph v)
+unitEnv_alterF f uid unitEnv =
+ UnitEnvGraph <$> Map.alterF f uid (unitEnv_graph unitEnv)
+
unitEnv_singleton :: UnitEnvGraphKey -> v -> UnitEnvGraph v
unitEnv_singleton active m = UnitEnvGraph
{ unitEnv_graph = Map.singleton active m
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -21,13 +21,18 @@
-- Or, do you really need a function to traverse all modules in the HPT? It is
-- often better to keep the computation internal to this module, such as in
-- 'hptCollectObjects'...
+{-# OPTIONS_GHC -Wall -Wincomplete-record-selectors #-}
module GHC.Unit.Home.PackageTable
(
- HomePackageTable(..)
+ HomePackageTable
, emptyHomePackageTable
+ , emptyOnDemandHomePackageTable
- , HomeLoaderState -- TODO: should this be opaque? Probably
- , emptyHomeLoaderState
+ , isOneShotMode
+ , isHptEmpty
+
+ -- , HomeLoaderState -- TODO: should this be opaque? Probably
+ -- , emptyHomeLoaderState
-- * Lookups in the HPT
, lookupHpt
@@ -42,13 +47,12 @@ module GHC.Unit.Home.PackageTable
, restrictHpt
-- * Queries about home modules
+ , listHptIfaces
, hptCompleteSigs
, hptAllInstances
, hptAllFamInstances
, hptAllAnnotations
- , hlsIsModuleNameWithBoot
- , hlsIsBoot
- , hlsSetBootInfo
+ , hptSetBootInfo
, hptLoadedIsBoot
, hptLoadedTypeEnv
, hptLoadedInstEnv
@@ -78,9 +82,8 @@ module GHC.Unit.Home.PackageTable
--
-- In GHC itself these should be avoided, and other uses should justify why
-- it is not sufficient to go through the intended insert-only API.
- , hptInternalTableRef
+ -- , hptInternalTableRef
, hptInternalTableFromRef
- , hptLoaderState
-- * Legacy API
--
-- | This API is deprecated and meant to be removed.
@@ -98,7 +101,6 @@ 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
@@ -117,24 +119,19 @@ import GHC.Types.DefaultEnv (DefaultEnv)
import GHC.Core
-- | Helps us find information about modules in the home package
-data HomePackageTable = HPT {
+data HomePackageTable
+ = HPT_Make { table :: {-# UNPACK #-} !(IORef (DModuleNameEnv HomeModInfo)) }
+ | HPT_OneShot { loader :: {-# UNPACK #-} !(IORef HomeLoaderState) }
- 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).
- -- Moreover, the HPT invariant allows mutability in this table without compromising thread safety or soundness.
- -- To recall:
- -- A query to the HPT should depend only on data relevant to that query, such that
- -- there being more or less unrelated entries in the HPT does not influence the result in any way.
- --
- -- Note that the HPT increases monotonically, except at certain barrier
- -- points like when 'restrictHpt' is called. At these barriers, it is safe
- -- to temporarily violate the HPT monotonicity.
- --
- -- The elements of this table may be updated (e.g. on rehydration).
- loader :: IORef HomeLoaderState
- }
+isOneShotMode :: HomePackageTable -> Bool
+isOneShotMode = \ case
+ HPT_OneShot{} -> True
+ HPT_Make{} -> False
+
+isHptEmpty :: HomePackageTable -> IO Bool
+isHptEmpty = \ case
+ HPT_OneShot{loader} -> null . hls_table <$> readIORef loader
+ HPT_Make{table} -> isNullUDFM <$> readIORef table
-- | Create a new 'HomePackageTable'.
--
@@ -145,14 +142,19 @@ emptyHomePackageTable :: IO HomePackageTable
-- romes:todo: use a MutableArray directly?
emptyHomePackageTable = do
table <- newIORef emptyUDFM
+ return HPT_Make{table}
+
+emptyOnDemandHomePackageTable :: IO HomePackageTable
+emptyOnDemandHomePackageTable = do
loader <- newIORef emptyHomeLoaderState
- return HPT{table, loader}
+ return HPT_OneShot{loader}
data HomeLoaderState = HomeLoaderState
- { hls_modules :: ModuleEnv ()
+ { hls_table :: DModuleNameEnv HomeModInfo
+ , hls_modules :: ModuleEnv ()
, hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
, hls_type_env :: !TypeEnv
- , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
+ -- , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
, hls_inst_env :: !InstEnv
, hls_fam_inst_env :: !FamInstEnv
, hls_mod_fam_inst_env :: !(ModuleEnv FamInstEnv)
@@ -165,10 +167,11 @@ data HomeLoaderState = HomeLoaderState
emptyHomeLoaderState :: HomeLoaderState
emptyHomeLoaderState =
HomeLoaderState
- { hls_modules = emptyModuleEnv
+ { hls_table = emptyUDFM
+ , hls_modules = emptyModuleEnv
, hls_is_boot = emptyInstalledModuleEnv
, hls_type_env = emptyTypeEnv
- , hls_iface_bytecode = emptyModuleEnv
+ -- , hls_iface_bytecode = emptyModuleEnv
, hls_inst_env = emptyInstEnv
, hls_fam_inst_env = emptyFamInstEnv
, hls_mod_fam_inst_env = emptyModuleEnv
@@ -184,46 +187,57 @@ emptyHomeLoaderState =
-- | Lookup the 'HomeModInfo' of a module in the HPT, given its name.
lookupHpt :: HomePackageTable -> ModuleName -> IO (Maybe HomeModInfo)
-lookupHpt HPT{table=hpt} mn = (`lookupUDFM` mn) <$!> readIORef hpt
+lookupHpt HPT_Make{table=hpt} mn = (`lookupUDFM` mn) <$!> readIORef hpt
+lookupHpt HPT_OneShot{loader=hpt} mn = (`lookupUDFM` mn) . hls_table <$!> readIORef hpt
-- | Lookup the 'HomeModInfo' of a 'Module' in the HPT.
lookupHptByModule :: HomePackageTable -> Module -> IO (Maybe HomeModInfo)
-lookupHptByModule hpt mod
+lookupHptByModule hpt modl
= -- The HPT is indexed by ModuleName, not Module,
-- we must check for a hit on the right Module
- lookupHpt hpt (moduleName mod) >>= pure . \case
- Just hm | mi_module (hm_iface hm) == mod -> Just hm
+ lookupHpt hpt (moduleName modl) >>= pure . \case
+ Just hm | mi_module (hm_iface hm) == modl -> Just hm
_otherwise -> Nothing
-hptLoaderState :: HomePackageTable -> IO HomeLoaderState
-hptLoaderState = readIORef . loader
+queryOnDemandHpt :: a -> (HomeLoaderState -> a) -> HomePackageTable -> IO a
+queryOnDemandHpt a f hpt =
+ case hpt of
+ HPT_Make{} ->
+ pure a
+ HPT_OneShot{loader} ->
+ f <$> readIORef loader
hptLoadedIsBoot :: HomePackageTable -> IO (InstalledModuleEnv ModuleNameWithIsBoot)
-hptLoadedIsBoot hpt = hls_is_boot <$> readIORef (loader hpt)
+hptLoadedIsBoot = queryOnDemandHpt emptyInstalledModuleEnv hls_is_boot
hptLoadedTypeEnv :: HomePackageTable -> IO TypeEnv
-hptLoadedTypeEnv hpt = hls_type_env <$> readIORef (loader hpt)
+hptLoadedTypeEnv = queryOnDemandHpt emptyTypeEnv hls_type_env
hptLoadedInstEnv :: HomePackageTable -> IO InstEnv
-hptLoadedInstEnv hpt = hls_inst_env <$> readIORef (loader hpt)
+hptLoadedInstEnv = queryOnDemandHpt emptyInstEnv hls_inst_env
hptLoadedFamInstEnv :: HomePackageTable -> IO FamInstEnv
-hptLoadedFamInstEnv hpt = hls_fam_inst_env <$> readIORef (loader hpt)
+hptLoadedFamInstEnv = queryOnDemandHpt emptyFamInstEnv hls_fam_inst_env
hptLoadedModFamInstEnv :: HomePackageTable -> IO (ModuleEnv FamInstEnv)
-hptLoadedModFamInstEnv hpt = hls_mod_fam_inst_env <$> readIORef (loader hpt)
+hptLoadedModFamInstEnv = queryOnDemandHpt emptyModuleEnv hls_mod_fam_inst_env
hptLoadedRuleBase :: HomePackageTable -> IO RuleBase
-hptLoadedRuleBase hpt = hls_rule_base <$> readIORef (loader hpt)
+hptLoadedRuleBase = queryOnDemandHpt emptyRuleBase hls_rule_base
hptLoadedAnnEnv :: HomePackageTable -> IO AnnEnv
-hptLoadedAnnEnv hpt = hls_ann_env <$> readIORef (loader hpt)
+hptLoadedAnnEnv = queryOnDemandHpt emptyAnnEnv hls_ann_env
hptLoadedCompleteMatches :: HomePackageTable -> IO CompleteMatches
-hptLoadedCompleteMatches hpt = hls_complete_matches <$> readIORef (loader hpt)
+hptLoadedCompleteMatches = queryOnDemandHpt [] hls_complete_matches
hptLoadedDefaults :: HomePackageTable -> IO (ModuleEnv DefaultEnv)
-hptLoadedDefaults hpt = hls_defaults <$> readIORef (loader hpt)
+hptLoadedDefaults = queryOnDemandHpt emptyModuleEnv hls_defaults
+
+listHptIfaces :: HomePackageTable -> IO (DModuleNameEnv HomeModInfo)
+listHptIfaces = \ case
+ HPT_Make{table} -> readIORef table
+ HPT_OneShot{loader} -> hls_table <$> readIORef loader
--------------------------------------------------------------------------------
-- * Extending the HPT
@@ -244,10 +258,12 @@ addHomeModInfoToHpt hmi hpt = addToHpt hpt (moduleName (mi_module (hm_iface hmi)
{-# DEPRECATED addToHpt "Deprecated in favour of 'addHomeModInfoToHpt', as the module at which a 'HomeModInfo' is inserted should always be derived from the 'HomeModInfo' itself." #-}
-- After deprecation cycle, move `addToHpt` to a `where` clause inside `addHomeModInfoToHpt`.
addToHpt :: HomePackageTable -> ModuleName -> HomeModInfo -> IO ()
-addToHpt HPT{table=hptr} mn hmi = do
+addToHpt HPT_Make{table=hptr} mn hmi = do
atomicModifyIORef' hptr (\hpt -> (addToUDFM hpt mn hmi, ()))
-- If the key already existed in the map, this insertion is overwriting
-- the HMI of a previously loaded module (likely in rehydration).
+addToHpt HPT_OneShot{loader=hptr} mn hmi = do
+ atomicModifyIORef' hptr (\hpt -> (hpt { hls_table = addToUDFM (hls_table hpt) mn hmi }, ()))
-- | 'addHomeModInfoToHpt' for multiple module infos.
addHomeModInfosToHpt :: HomePackageTable -> [HomeModInfo] -> IO ()
@@ -262,19 +278,21 @@ addHomeModInfosToHpt hpt = mapM_ (flip addHomeModInfoToHpt hpt)
-- called at barrier points, such as the end of upsweep, when all threads are
-- done and we want to clean up failed entries.
restrictHpt :: HomePackageTable -> [HomeModInfo] -> IO ()
-restrictHpt HPT{table=hptr} hmis =
+restrictHpt HPT_Make{table=hptr} hmis =
let key_set = map (getKey . getUnique . hmi_mod) hmis
hmi_mod hmi = moduleName (mi_module (hm_iface hmi))
in atomicModifyIORef' hptr (\hpt -> (udfmRestrictKeysSet hpt (W64.fromList key_set), ()))
+restrictHpt HPT_OneShot{} _ = pure ()
{-# DEPRECATED addListToHpt "Deprecated in favour of 'addHomeModInfosToHpt', as the module at which a 'HomeModInfo' is inserted should always be derived from the 'HomeModInfo' itself." #-}
-- After deprecation cycle, remove.
addListToHpt :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> IO ()
addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
-addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
-addOnDemandHomeModule hpt mn 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 ->
+addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IO ()
+addOnDemandHomeModule HPT_Make{} _ _ _ = pure ()
+addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+ atomicModifyIORef loader $ \hls ->
( if mn `elemModuleEnv` hls_modules hls
then hls -- If already loaded, don't add twice
else
@@ -285,41 +303,39 @@ addOnDemandHomeModule hpt mn bad_boot (new_hls_decls, new_hls_insts, new_hls_def
)
where
addHomeModTypeEnv hls = hls
- { hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls
+ { hls_type_env = extendNameEnvList (hls_type_env hls) new_decls
}
addHomeModData hls = hls {
- hls_modules = extendModuleEnv (hls_modules hls) mn (),
- 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_modules = extendModuleEnv (hls_modules hls) mn (),
+ hls_type_env = extendNameEnvList (hls_type_env hls) new_decls,
hls_rule_base = extendRuleBaseList (hls_rule_base hls)
- new_hls_rules,
+ new_rules,
hls_complete_matches
- = hls_complete_matches hls ++ new_hls_complete_matches,
+ = hls_complete_matches hls ++ new_complete_matches,
hls_inst_env = extendInstEnvList (hls_inst_env hls)
- new_hls_insts,
+ new_insts,
hls_fam_inst_env = extendFamInstEnvList (hls_fam_inst_env hls)
- new_hls_fam_insts,
+ new_fam_insts,
hls_ann_env = extendAnnEnvList (hls_ann_env hls)
- new_hls_anns,
+ new_anns,
hls_mod_fam_inst_env
=
let
fam_inst_env =
extendFamInstEnvList emptyFamInstEnv
- new_hls_fam_insts
+ new_fam_insts
in
extendModuleEnv (hls_mod_fam_inst_env hls)
mn
fam_inst_env,
- hls_defaults = extendModuleEnv (hls_defaults hls) mn new_hls_defaults
+ hls_defaults = extendModuleEnv (hls_defaults hls) mn new_defaults
}
-hlsSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
-hlsSetBootInfo hpt is_boot_env =
- atomicModifyIORef' (loader hpt) $ \ hls ->
+hptSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
+hptSetBootInfo HPT_Make{} _ = pure ()
+hptSetBootInfo HPT_OneShot{loader} is_boot_env =
+ atomicModifyIORef' loader $ \ hls ->
(hls { hls_is_boot = is_boot_env }, ())
----------------------------------------------------------------------------------
@@ -352,12 +368,6 @@ 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
--------------------------------------------------------------------------------
@@ -370,7 +380,11 @@ hlsIsModuleNameWithBoot hls mn = lookupInstalledModuleEnv (hls_is_boot hls) mn
-- currently takes all dependencies only to then filter them with an ad-hoc transitive closure check.
-- See #25639
hptCollectDependencies :: HomePackageTable -> IO (Set.Set (IfaceImportLevel, UnitId))
-hptCollectDependencies HPT{table} = do
+hptCollectDependencies HPT_OneShot{loader} = do
+ hpt <- readIORef loader
+ return $
+ foldr (Set.union . dep_direct_pkgs . mi_deps . hm_iface) Set.empty (hls_table hpt)
+hptCollectDependencies HPT_Make{table} = do
hpt <- readIORef table
return $
foldr (Set.union . dep_direct_pkgs . mi_deps . hm_iface) Set.empty hpt
@@ -380,7 +394,11 @@ hptCollectDependencies HPT{table} = do
--
-- $O(n)$ in the number of modules in the HPT.
hptCollectHomeModInfo :: HomePackageTable -> IO [HomeModInfo]
-hptCollectHomeModInfo HPT{table} = do
+hptCollectHomeModInfo HPT_OneShot{loader} = do
+ hpt <- readIORef loader
+ return $
+ foldr (:) [] (hls_table hpt)
+hptCollectHomeModInfo HPT_Make{table} = do
hpt <- readIORef table
return $
foldr (:) [] hpt
@@ -398,7 +416,13 @@ hptCollectHomeModInfo HPT{table} = do
-- unit map in failed lookups.
pprHPT :: HomePackageTable -> IO SDoc
-- A bit arbitrary for now
-pprHPT HPT{table=hptr} = do
+pprHPT HPT_OneShot{loader=hptr} = do
+ hpt <- readIORef hptr
+ return $!
+ pprUDFM (hls_table hpt) $ \hms ->
+ vcat [ ppr (mi_module (hm_iface hm))
+ | hm <- hms ]
+pprHPT HPT_Make{table=hptr} = do
hpt <- readIORef hptr
return $!
pprUDFM hpt $ \hms ->
@@ -437,7 +461,12 @@ pprHPT HPT{table=hptr} = do
-- If this function is ever exposed from the HPT module, make sure the
-- argument function doesn't introduce leaks.
concatHpt :: (HomeModInfo -> [a]) -> HomePackageTable -> IO [a]
-concatHpt f HPT{table} = do
+concatHpt f HPT_OneShot{loader} = do
+ hpt <- readIORef loader
+ return $ concat . eltsUDFM . mapMaybeUDFM g $ hls_table hpt
+ where
+ g hmi = case f hmi of { [] -> Nothing; as -> Just as }
+concatHpt f HPT_Make{table} = do
hpt <- readIORef table
return $ concat . eltsUDFM . mapMaybeUDFM g $ hpt
where
@@ -449,15 +478,15 @@ concatHpt f HPT{table} = do
-- | Gets the internal 'IORef' which holds the 'HomeModInfo's of this HPT.
-- Use with care.
-hptInternalTableRef :: HomePackageTable -> IORef (DModuleNameEnv HomeModInfo)
-hptInternalTableRef = table
+-- hptInternalTableRef :: HomePackageTable -> IORef (DModuleNameEnv HomeModInfo)
+-- hptInternalTableRef = \ case
+-- HPT_Make{table} -> table
+-- HPT_OneShot{} -> -- TODO: @fendor how does this make sense?
-- | Construct a HomePackageTable from the IORef.
-- 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,
- loader
+ return HPT_Make {
+ table = ref
}
=====================================
compiler/GHC/Unit/Module/Env.hs
=====================================
@@ -249,7 +249,7 @@ lookupModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> Maybe elt
lookupModuleNameEnv = lookupUFM
unionModuleNameEnv :: ModuleNameEnv elt -> ModuleNameEnv elt -> ModuleNameEnv elt
-unionModuleNameEnv = unionModuleNameEnv
+unionModuleNameEnv = plusUFM
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
-- Has deterministic folds and can be deterministically converted to a list
=====================================
ghc/GHCi/Leak.hs
=====================================
@@ -7,7 +7,6 @@ module GHCi.Leak
import Control.Monad
import Data.Bits
-import Data.IORef
import Foreign.Ptr (ptrToIntPtr, intPtrToPtr)
import GHC
import GHC.Ptr (Ptr (..))
@@ -43,7 +42,7 @@ data LeakModIndicators = LeakModIndicators
getLeakIndicators :: HscEnv -> IO LeakIndicators
getLeakIndicators hsc_env =
fmap LeakIndicators $ do
- hpt <- readIORef $ hptInternalTableRef $ hsc_HPT hsc_env
+ hpt <- listHptIfaces $ hsc_HPT hsc_env
forM (eltsUDFM hpt) $ \hmi@HomeModInfo{..} -> do
leakMod <- mkWeakPtr hmi Nothing
leakIface <- mkWeakPtr hm_iface Nothing
=====================================
testsuite/tests/bytecode/T25090/Makefile
=====================================
@@ -16,6 +16,22 @@ T25090a:
'$(TEST_HC)' -fbyte-code-and-object-code -fprefer-byte-code A.o -o exe
./exe
+# Like T25090a, but without .gbc files: the bytecode for the splice has to be
+# compiled from the Core stored in the interface files
+# (-fwrite-if-simplified-core). See Note [Interface Files with Core Definitions].
+T25090c:
+ '$(TEST_HC)' -c -fwrite-if-simplified-core C.hs-boot
+ '$(TEST_HC)' -c -fwrite-if-simplified-core B.hs
+ '$(TEST_HC)' -c -fwrite-if-simplified-core C.hs
+ echo 'corrupt' > B.o
+ echo 'corrupt' > C.o
+ echo 'corrupt' > C.o-boot
+ '$(TEST_HC)' -c -fwrite-if-simplified-core D.hs
+ echo 'corrupt' > D.o
+ '$(TEST_HC)' -c -fwrite-if-simplified-core -fprefer-byte-code A.hs
+ '$(TEST_HC)' A.o -o exe
+ ./exe
+
T25090b:
'$(TEST_HC)' -fbyte-code-and-object-code -fprefer-byte-code A -o exe -v0
./exe
=====================================
testsuite/tests/bytecode/T25090/all.T
=====================================
@@ -4,7 +4,7 @@
# the warning is added to the expected stderr for debugged builds.
def test_T25090(name):
assert_warn_spec = {'stderr': 'T25090-debug.stderr'}
- extra_specs = assert_warn_spec if name == 'T25090a' and compiler_debugged() else {}
+ extra_specs = assert_warn_spec if name in ('T25090a', 'T25090c') and compiler_debugged() else {}
return test(name,
[extra_files(['A.hs', 'B.hs', 'C.hs-boot', 'C.hs', 'D.hs']),
req_th,
@@ -16,3 +16,4 @@ def test_T25090(name):
test_T25090('T25090a')
test_T25090('T25090b')
+test_T25090('T25090c')
=====================================
testsuite/tests/driver/one-shot-boot/A.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE TypeFamilies #-}
+module A where
+
+import Fam
+import {-# SOURCE #-} M (T)
+
+-- This instance mentions 'T' from M's boot file.
+type instance F T = Int
=====================================
testsuite/tests/driver/one-shot-boot/B.hs
=====================================
@@ -0,0 +1,10 @@
+{-# LANGUAGE TypeFamilies #-}
+module B where
+
+import Fam
+
+-- A second family-instance module for 'F', so that compiling M has to check
+-- the consistency of A's and B's instances. That check forces 'T', which
+-- makes GHC load M.hi-boot while compiling M itself.
+-- See Note [Loading your own hi-boot file] in GHC.Iface.Load.
+type instance F Bool = Char
=====================================
testsuite/tests/driver/one-shot-boot/Fam.hs
=====================================
@@ -0,0 +1,4 @@
+{-# LANGUAGE TypeFamilies #-}
+module Fam where
+
+type family F a
=====================================
testsuite/tests/driver/one-shot-boot/M.hs
=====================================
@@ -0,0 +1,17 @@
+{-# LANGUAGE TypeFamilies #-}
+module M where
+
+import Fam
+import A ()
+import B ()
+
+data T = MkT Int
+
+-- Also declared in M.hs-boot: loading M.hi-boot while compiling M must not
+-- cause a duplicate instance error.
+instance Show T where
+ show (MkT n) = "MkT " ++ show n
+
+-- Not part of M.hs-boot. Needs A's instance of 'F' to typecheck.
+onlyInM :: F T
+onlyInM = 42
=====================================
testsuite/tests/driver/one-shot-boot/M.hs-boot
=====================================
@@ -0,0 +1,5 @@
+module M where
+
+data T
+
+instance Show T
=====================================
testsuite/tests/driver/one-shot-boot/Main.hs
=====================================
@@ -0,0 +1,8 @@
+module Main where
+
+import M
+
+main :: IO ()
+main = do
+ print (onlyInM :: Int)
+ print (MkT 1)
=====================================
testsuite/tests/driver/one-shot-boot/Makefile
=====================================
@@ -0,0 +1,28 @@
+TOP=../../..
+include $(TOP)/mk/boilerplate.mk
+include $(TOP)/mk/test.mk
+
+# One-shot compilation of a SOURCE-import cycle where type family instances
+# mention the type from the boot file. Every module is compiled by its own
+# invocation of GHC.
+OneShotBootFamInst:
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c Fam.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs-boot
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c A.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c B.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c Main.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) Fam.o A.o B.o M.o Main.o -o main
+ ./main
+
+# Like OneShotBootFamInst, but M and Main are compiled by the same invocation.
+# Compiling M loads M.hi-boot (see Note [Loading your own hi-boot file]); that
+# must not make Main see the boot interface of M instead of the real one.
+OneShotBootSameInvocation:
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c Fam.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs-boot
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c A.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c B.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs Main.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) Fam.o A.o B.o M.o Main.o -o main
+ ./main
=====================================
testsuite/tests/driver/one-shot-boot/all.T
=====================================
@@ -0,0 +1,14 @@
+# Compiling M loads M.hi-boot, which triggers a warnPprTrace in debug builds.
+# See Note [Loading your own hi-boot file] in GHC.Iface.Load.
+def test_one_shot_boot(name):
+ return test(name,
+ [extra_files(['Fam.hs', 'M.hs-boot', 'A.hs', 'B.hs', 'M.hs', 'Main.hs']),
+ js_skip,
+ when(compiler_debugged(), ignore_stderr),
+ use_specs(dict(stdout = 'one-shot-boot.stdout')),
+ ],
+ makefile_test,
+ [])
+
+test_one_shot_boot('OneShotBootFamInst')
+test_one_shot_boot('OneShotBootSameInvocation')
=====================================
testsuite/tests/driver/one-shot-boot/one-shot-boot.stdout
=====================================
@@ -0,0 +1,2 @@
+42
+MkT 1
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1a30ac00178d94bb55f7dfd32e396e…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1a30ac00178d94bb55f7dfd32e396e…
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] Experiment with separate table types for inOneShot mode
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
1a30ac00 by Hannes Siebenhandl at 2026-11-30T13:49:04+01:00
Experiment with separate table types for inOneShot mode
- - - - -
8 changed files:
- compiler/GHC.hs
- compiler/GHC/Core/Rules.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Tc/Utils/Instantiate.hs
- compiler/GHC/Unit/Env.hs
- compiler/GHC/Unit/Home/Graph.hs
- compiler/GHC/Unit/Home/PackageTable.hs
- compiler/GHC/Unit/Module/Env.hs
Changes:
=====================================
compiler/GHC.hs
=====================================
@@ -442,13 +442,14 @@ import GHC.Types.PkgQual
import GHC.Unit
import GHC.Unit.Env as UnitEnv
import GHC.Unit.Finder
-import GHC.Unit.Module.ModIface
-import GHC.Unit.Module.ModGuts
+import GHC.Unit.Home.Graph qualified as HUG
+import GHC.Unit.Home.ModInfo
+import GHC.Unit.Home.PackageTable qualified as HPT
+import GHC.Unit.Module.Graph
import GHC.Unit.Module.ModDetails
+import GHC.Unit.Module.ModGuts
+import GHC.Unit.Module.ModIface
import GHC.Unit.Module.ModSummary
-import GHC.Unit.Module.Graph
-import GHC.Unit.Home.ModInfo
-import qualified GHC.Unit.Home.Graph as HUG
import Control.Applicative ((<|>))
import Control.Monad
@@ -693,14 +694,41 @@ setUnitDynFlagsNoCheck uid dflags1 = do
(unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags1 (hscUIC hsc_env) (hsc_all_home_unit_ids hsc_env)
updated_dflags <- liftIO $ updatePlatformConstants dflags1 mconstants
- let upd hue =
- hue
- { homeUnitEnv_units = unit_state
- , homeUnitEnv_dflags = updated_dflags
- , homeUnitEnv_home_unit = Just home_unit
- }
+ let
+ upd hue = do
+ let
+ warnOnNonEmptyTable = do
+ logInfo logger
+ (text "Changed the ghc mode" <+> ppr (ghcMode $ homeUnitEnv_dflags hue) <+> text "to" <+> ppr (ghcMode updated_dflags) $$
+ text "The home package table was not empty!"
+ )
+ the_hpt <-
+ case (HPT.isOneShotMode (homeUnitEnv_hpt hue), ghcMode updated_dflags) of
+ (True, OneShot) ->
+ pure $ homeUnitEnv_hpt hue
+ (True, CompManager) -> do
+ warnOnNonEmptyTable
+ HPT.emptyHomePackageTable
+ (True, MkDepend) -> do
+ warnOnNonEmptyTable
+ HPT.emptyHomePackageTable
+ (False, OneShot) -> do
+ warnOnNonEmptyTable
+ HPT.emptyOnDemandHomePackageTable
+ (False, CompManager) ->
+ pure $ homeUnitEnv_hpt hue
+ (False, MkDepend) ->
+ pure $ homeUnitEnv_hpt hue
+ pure hue
+ { homeUnitEnv_units = unit_state
+ , homeUnitEnv_dflags = updated_dflags
+ , homeUnitEnv_home_unit = Just home_unit
+ , homeUnitEnv_hpt = the_hpt
+ }
+
+
- let unit_env = UnitEnv.ue_updateHomeUnitEnv upd uid (hsc_unit_env hsc_env)
+ unit_env <- liftIO $ UnitEnv.ue_adjustHomeUnitEnvA upd uid (hsc_unit_env hsc_env)
let dflags = updated_dflags
=====================================
compiler/GHC/Core/Rules.hs
=====================================
@@ -401,7 +401,7 @@ lookupRuleBase = lookupUFM
unionRuleBase :: RuleBase -> RuleBase -> RuleBase
unionRuleBase
- = plusUFM
+ = plusUFM_C (++)
pprRuleBase :: RuleBase -> SDoc
pprRuleBase rules = pprUFM rules $ \rss ->
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -833,7 +833,7 @@ loadInterface doc_str mod from
; 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))
+ (text "Attempting to load 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 iface tcParts
else dontLeakTheHUG $ do
@@ -857,7 +857,7 @@ loadInterface doc_str mod from
(moduleUnitId mod `Set.notMember` hsc_all_home_unit_ids hsc_env)
(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
+ addModIfacePartsToEps mod loc iface tcParts
; -- invoke plugins with *full* interface, not final_iface, to ensure
-- that plugins have access to declarations, etc.
@@ -907,11 +907,12 @@ addModIfacePartsToHpt gbl_env mod iface (new_decls, new_insts, new_defaults, new
warnPprTrace bad_boot "loadInterface" (ppr mod) $ do
hpt <- getHpt
- liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
+ when (not bad_boot) $ do
+ liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches)
-addModIfacePartsToEps :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
-addModIfacePartsToEps gbl_env mod loc iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+addModIfacePartsToEps :: Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToEps mod loc iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
purged_hsc_env <- getTopEnv
let
@@ -923,13 +924,6 @@ addModIfacePartsToEps gbl_env mod loc iface (new_decls, new_insts, new_defaults,
& 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.
--
@@ -943,43 +937,39 @@ addModIfacePartsToEps gbl_env mod loc iface (new_decls, new_insts, new_defaults,
= old
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_decls }
- else
- eps {
- eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
- eps_PTE = addDeclsToPTE (eps_PTE eps) new_decls,
- eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
- eps_rule_base = extendRuleBaseList (eps_rule_base eps)
- new_rules,
- eps_complete_matches
- = eps_complete_matches eps ++ new_complete_matches,
- eps_inst_env = extendInstEnvList (eps_inst_env eps)
- new_insts,
- eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
- new_fam_insts,
- eps_ann_env = extendAnnEnvList (eps_ann_env eps)
- new_anns,
- eps_mod_fam_inst_env
- = let
- fam_inst_env =
- extendFamInstEnvList emptyFamInstEnv
- new_fam_insts
- in
- extendModuleEnv (eps_mod_fam_inst_env eps)
- mod
- fam_inst_env,
- eps_stats = addEpsInStats (eps_stats eps)
- (length new_decls)
- (length new_insts)
- (length new_rules),
- eps_defaults = extendModuleEnv (eps_defaults eps) mod new_defaults
- }
+ updateEps_ $ \ eps ->
+ if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface
+ then eps
+ else
+ eps {
+ eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
+ eps_PTE = addDeclsToPTE (eps_PTE eps) new_decls,
+ eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
+ eps_rule_base = extendRuleBaseList (eps_rule_base eps)
+ new_rules,
+ eps_complete_matches
+ = eps_complete_matches eps ++ new_complete_matches,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps)
+ new_insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
+ new_fam_insts,
+ eps_ann_env = extendAnnEnvList (eps_ann_env eps)
+ new_anns,
+ eps_mod_fam_inst_env
+ = let
+ fam_inst_env =
+ extendFamInstEnvList emptyFamInstEnv
+ new_fam_insts
+ in
+ extendModuleEnv (eps_mod_fam_inst_env eps)
+ mod
+ fam_inst_env,
+ eps_stats = addEpsInStats (eps_stats eps)
+ (length new_decls)
+ (length new_insts)
+ (length new_rules),
+ eps_defaults = extendModuleEnv (eps_defaults eps) mod new_defaults
+ }
{- Note [Loading your own hi-boot file]
=====================================
compiler/GHC/Tc/Utils/Instantiate.hs
=====================================
@@ -947,13 +947,6 @@ 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/Unit/Env.hs
=====================================
@@ -52,6 +52,7 @@ module GHC.Unit.Env
, ue_unitHomeUnit
, ue_unitHomeUnit_maybe
, ue_updateHomeUnitEnv
+ , ue_adjustHomeUnitEnvA
, ue_all_home_unit_ids
, ue_unsafeHomeUnit
@@ -360,6 +361,13 @@ ue_updateHomeUnitEnv f uid e = e
{ ue_home_unit_graph = HUG.unitEnv_adjust f uid $ ue_home_unit_graph e
}
+ue_adjustHomeUnitEnvA :: Applicative f => (HomeUnitEnv -> f HomeUnitEnv) -> UnitId -> UnitEnv -> f UnitEnv
+ue_adjustHomeUnitEnvA f uid e =
+ let
+ hugA = HUG.unitEnv_adjustA f uid $ ue_home_unit_graph e
+ in
+ (\ hug -> e { ue_home_unit_graph = hug }) <$> hugA
+
ue_all_home_unit_ids :: UnitEnv -> Set.Set UnitId
ue_all_home_unit_ids = HUG.allUnits . ue_home_unit_graph
=====================================
compiler/GHC/Unit/Home/Graph.hs
=====================================
@@ -61,6 +61,8 @@ module GHC.Unit.Home.Graph
, unitEnv_foldWithKey
, unitEnv_singleton
, unitEnv_adjust
+ , unitEnv_adjustA
+ , unitEnv_alterF
, unitEnv_keys
, unitEnv_insert
, unitEnv_new
@@ -320,6 +322,17 @@ unitEnv_adjust f uid unitEnv = unitEnv
{ unitEnv_graph = Map.adjust f uid (unitEnv_graph unitEnv)
}
+unitEnv_adjustA :: Applicative f => (v -> f v) -> UnitEnvGraphKey -> UnitEnvGraph v -> f (UnitEnvGraph v)
+unitEnv_adjustA f uid unitEnv =
+ unitEnv_alterF go uid unitEnv
+ where
+ go Nothing = pure Nothing
+ go (Just v) = Just <$> f v
+
+unitEnv_alterF :: Functor f => (Maybe v -> f (Maybe v)) -> UnitEnvGraphKey -> UnitEnvGraph v -> f (UnitEnvGraph v)
+unitEnv_alterF f uid unitEnv =
+ UnitEnvGraph <$> Map.alterF f uid (unitEnv_graph unitEnv)
+
unitEnv_singleton :: UnitEnvGraphKey -> v -> UnitEnvGraph v
unitEnv_singleton active m = UnitEnvGraph
{ unitEnv_graph = Map.singleton active m
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -24,11 +24,12 @@
{-# OPTIONS_GHC -Wall -Wincomplete-record-selectors #-}
module GHC.Unit.Home.PackageTable
(
- HomePackageTable(..)
+ HomePackageTable
, emptyHomePackageTable
, emptyOnDemandHomePackageTable
, isOneShotMode
+ , isHptEmpty
-- , HomeLoaderState -- TODO: should this be opaque? Probably
-- , emptyHomeLoaderState
@@ -51,8 +52,6 @@ module GHC.Unit.Home.PackageTable
, hptAllInstances
, hptAllFamInstances
, hptAllAnnotations
- , hlsIsModuleNameWithBoot
- , hlsIsBoot
, hptSetBootInfo
, hptLoadedIsBoot
, hptLoadedTypeEnv
@@ -129,6 +128,11 @@ isOneShotMode = \ case
HPT_OneShot{} -> True
HPT_Make{} -> False
+isHptEmpty :: HomePackageTable -> IO Bool
+isHptEmpty = \ case
+ HPT_OneShot{loader} -> null . hls_table <$> readIORef loader
+ HPT_Make{table} -> isNullUDFM <$> readIORef table
+
-- | Create a new 'HomePackageTable'.
--
-- Be careful not to share it across e.g. different units, since it uses a
@@ -364,12 +368,6 @@ 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
--------------------------------------------------------------------------------
=====================================
compiler/GHC/Unit/Module/Env.hs
=====================================
@@ -249,7 +249,7 @@ lookupModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> Maybe elt
lookupModuleNameEnv = lookupUFM
unionModuleNameEnv :: ModuleNameEnv elt -> ModuleNameEnv elt -> ModuleNameEnv elt
-unionModuleNameEnv = unionModuleNameEnv
+unionModuleNameEnv = plusUFM
-- | 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/1a30ac00178d94bb55f7dfd32e396e5…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1a30ac00178d94bb55f7dfd32e396e5…
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] Add testcase for one-shot and bytecode
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
ec0da2ed by fendor at 2026-11-30T13:24:11+01:00
Add testcase for one-shot and bytecode
- - - - -
11 changed files:
- testsuite/tests/bytecode/T25090/Makefile
- testsuite/tests/bytecode/T25090/all.T
- + testsuite/tests/driver/one-shot-boot/A.hs
- + testsuite/tests/driver/one-shot-boot/B.hs
- + testsuite/tests/driver/one-shot-boot/Fam.hs
- + testsuite/tests/driver/one-shot-boot/M.hs
- + testsuite/tests/driver/one-shot-boot/M.hs-boot
- + testsuite/tests/driver/one-shot-boot/Main.hs
- + testsuite/tests/driver/one-shot-boot/Makefile
- + testsuite/tests/driver/one-shot-boot/all.T
- + testsuite/tests/driver/one-shot-boot/one-shot-boot.stdout
Changes:
=====================================
testsuite/tests/bytecode/T25090/Makefile
=====================================
@@ -16,6 +16,22 @@ T25090a:
'$(TEST_HC)' -fbyte-code-and-object-code -fprefer-byte-code A.o -o exe
./exe
+# Like T25090a, but without .gbc files: the bytecode for the splice has to be
+# compiled from the Core stored in the interface files
+# (-fwrite-if-simplified-core). See Note [Interface Files with Core Definitions].
+T25090c:
+ '$(TEST_HC)' -c -fwrite-if-simplified-core C.hs-boot
+ '$(TEST_HC)' -c -fwrite-if-simplified-core B.hs
+ '$(TEST_HC)' -c -fwrite-if-simplified-core C.hs
+ echo 'corrupt' > B.o
+ echo 'corrupt' > C.o
+ echo 'corrupt' > C.o-boot
+ '$(TEST_HC)' -c -fwrite-if-simplified-core D.hs
+ echo 'corrupt' > D.o
+ '$(TEST_HC)' -c -fwrite-if-simplified-core -fprefer-byte-code A.hs
+ '$(TEST_HC)' A.o -o exe
+ ./exe
+
T25090b:
'$(TEST_HC)' -fbyte-code-and-object-code -fprefer-byte-code A -o exe -v0
./exe
=====================================
testsuite/tests/bytecode/T25090/all.T
=====================================
@@ -4,7 +4,7 @@
# the warning is added to the expected stderr for debugged builds.
def test_T25090(name):
assert_warn_spec = {'stderr': 'T25090-debug.stderr'}
- extra_specs = assert_warn_spec if name == 'T25090a' and compiler_debugged() else {}
+ extra_specs = assert_warn_spec if name in ('T25090a', 'T25090c') and compiler_debugged() else {}
return test(name,
[extra_files(['A.hs', 'B.hs', 'C.hs-boot', 'C.hs', 'D.hs']),
req_th,
@@ -16,3 +16,4 @@ def test_T25090(name):
test_T25090('T25090a')
test_T25090('T25090b')
+test_T25090('T25090c')
=====================================
testsuite/tests/driver/one-shot-boot/A.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE TypeFamilies #-}
+module A where
+
+import Fam
+import {-# SOURCE #-} M (T)
+
+-- This instance mentions 'T' from M's boot file.
+type instance F T = Int
=====================================
testsuite/tests/driver/one-shot-boot/B.hs
=====================================
@@ -0,0 +1,10 @@
+{-# LANGUAGE TypeFamilies #-}
+module B where
+
+import Fam
+
+-- A second family-instance module for 'F', so that compiling M has to check
+-- the consistency of A's and B's instances. That check forces 'T', which
+-- makes GHC load M.hi-boot while compiling M itself.
+-- See Note [Loading your own hi-boot file] in GHC.Iface.Load.
+type instance F Bool = Char
=====================================
testsuite/tests/driver/one-shot-boot/Fam.hs
=====================================
@@ -0,0 +1,4 @@
+{-# LANGUAGE TypeFamilies #-}
+module Fam where
+
+type family F a
=====================================
testsuite/tests/driver/one-shot-boot/M.hs
=====================================
@@ -0,0 +1,17 @@
+{-# LANGUAGE TypeFamilies #-}
+module M where
+
+import Fam
+import A ()
+import B ()
+
+data T = MkT Int
+
+-- Also declared in M.hs-boot: loading M.hi-boot while compiling M must not
+-- cause a duplicate instance error.
+instance Show T where
+ show (MkT n) = "MkT " ++ show n
+
+-- Not part of M.hs-boot. Needs A's instance of 'F' to typecheck.
+onlyInM :: F T
+onlyInM = 42
=====================================
testsuite/tests/driver/one-shot-boot/M.hs-boot
=====================================
@@ -0,0 +1,5 @@
+module M where
+
+data T
+
+instance Show T
=====================================
testsuite/tests/driver/one-shot-boot/Main.hs
=====================================
@@ -0,0 +1,8 @@
+module Main where
+
+import M
+
+main :: IO ()
+main = do
+ print (onlyInM :: Int)
+ print (MkT 1)
=====================================
testsuite/tests/driver/one-shot-boot/Makefile
=====================================
@@ -0,0 +1,28 @@
+TOP=../../..
+include $(TOP)/mk/boilerplate.mk
+include $(TOP)/mk/test.mk
+
+# One-shot compilation of a SOURCE-import cycle where type family instances
+# mention the type from the boot file. Every module is compiled by its own
+# invocation of GHC.
+OneShotBootFamInst:
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c Fam.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs-boot
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c A.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c B.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c Main.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) Fam.o A.o B.o M.o Main.o -o main
+ ./main
+
+# Like OneShotBootFamInst, but M and Main are compiled by the same invocation.
+# Compiling M loads M.hi-boot (see Note [Loading your own hi-boot file]); that
+# must not make Main see the boot interface of M instead of the real one.
+OneShotBootSameInvocation:
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c Fam.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs-boot
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c A.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c B.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) -c M.hs Main.hs
+ '$(TEST_HC)' $(TEST_HC_OPTS) Fam.o A.o B.o M.o Main.o -o main
+ ./main
=====================================
testsuite/tests/driver/one-shot-boot/all.T
=====================================
@@ -0,0 +1,14 @@
+# Compiling M loads M.hi-boot, which triggers a warnPprTrace in debug builds.
+# See Note [Loading your own hi-boot file] in GHC.Iface.Load.
+def test_one_shot_boot(name):
+ return test(name,
+ [extra_files(['Fam.hs', 'M.hs-boot', 'A.hs', 'B.hs', 'M.hs', 'Main.hs']),
+ js_skip,
+ when(compiler_debugged(), ignore_stderr),
+ use_specs(dict(stdout = 'one-shot-boot.stdout')),
+ ],
+ makefile_test,
+ [])
+
+test_one_shot_boot('OneShotBootFamInst')
+test_one_shot_boot('OneShotBootSameInvocation')
=====================================
testsuite/tests/driver/one-shot-boot/one-shot-boot.stdout
=====================================
@@ -0,0 +1,2 @@
+42
+MkT 1
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/ec0da2ed23f9f91cd7db674ce619ec2…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/ec0da2ed23f9f91cd7db674ce619ec2…
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
30 Nov '26
Wen Kokke pushed new branch wip/wenkokke/typecase at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/wenkokke/typecase
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] Experiment with separate table types for inOneShot mode
by Hannes Siebenhandl (@fendor) 30 Nov '26
by Hannes Siebenhandl (@fendor) 30 Nov '26
30 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
c00e2758 by Hannes Siebenhandl at 2026-11-30T12:42:34+01:00
Experiment with separate table types for inOneShot mode
- - - - -
9 changed files:
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Main/Hsc.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Unit/Home/PackageTable.hs
- ghc/GHCi/Leak.hs
Changes:
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -102,7 +102,7 @@ core2core hsc_env guts@(ModGuts { mg_module = mod
logger = hsc_logger hsc_env
unit_env = hsc_unit_env hsc_env
extra_vars = interactiveInScope (hsc_IC hsc_env)
- home_pkg_rules = hugRulesBelow hsc_env (moduleUnitId mod)
+ home_pkg_rules = hugRulesBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) (moduleUnitId mod)
(GWIB { gwib_mod = moduleName mod, gwib_isBoot = NotBoot })
name_ppr_ctx = mkNamePprCtx ptc unit_env rdr_env
ptc = initPromotionTickContext dflags
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -99,6 +99,7 @@ import Data.IORef
import qualified Data.Set as Set
import GHC.Types.Name.Reader (ExactRdrName(..))
import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import qualified GHC.Unit.Home.PackageTable as HPT
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env hsc = do
@@ -259,26 +260,26 @@ hscUIC hsc_env = ue_uic (hsc_unit_env hsc_env)
-- | Find all rules in modules that are in the transitive closure of the given
-- module.
-hugRulesBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO RuleBase
-hugRulesBelow hsc_env uid mn = foldr (flip extendRuleBaseList) emptyRuleBase <$>
- hugSomeThingsBelowUs (md_rules . hm_details) False hsc_env uid mn
+hugRulesBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO RuleBase
+hugRulesBelow mg hug uid mn = foldr (flip extendRuleBaseList) emptyRuleBase <$>
+ hugSomeThingsBelowUs (md_rules . hm_details) False mg hug uid mn
-- | Get annotations from all modules "below" this one (in the dependency
-- sense) within the home units. If the module is @Nothing@, returns /all/
-- annotations in the home units.
-hugAnnsBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO AnnEnv
-hugAnnsBelow hsc_env uid mn = foldr (flip extendAnnEnvList) emptyAnnEnv <$>
- hugSomeThingsBelowUs (md_anns . hm_details) False hsc_env uid mn
+hugAnnsBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO AnnEnv
+hugAnnsBelow mg hug uid mn = foldr (flip extendAnnEnvList) emptyAnnEnv <$>
+ hugSomeThingsBelowUs (md_anns . hm_details) False mg hug uid mn
-- | Find all COMPLETE pragmas in modules that are in the transitive closure of the
-- given module.
-hugCompleteSigsBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO CompleteMatches
-hugCompleteSigsBelow hsc uid mn = foldr (++) [] <$>
- hugSomeThingsBelowUs (md_complete_matches . hm_details) False hsc uid mn
+hugCompleteSigsBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO CompleteMatches
+hugCompleteSigsBelow mg hug uid mn = foldr (++) [] <$>
+ hugSomeThingsBelowUs (md_complete_matches . hm_details) False mg hug uid mn
-- | Find instances visible from the given set of imports
-hugInstancesBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst])
-hugInstancesBelow hsc_env uid mnwib = do
+hugInstancesBelow :: ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst])
+hugInstancesBelow mg hug uid mnwib = do
let mn = mkModule uid (gwib_mod mnwib)
(insts, famInsts) <-
unzip . concat <$>
@@ -289,7 +290,8 @@ hugInstancesBelow hsc_env uid mnwib = do
then []
else [(md_insts details, md_fam_insts details)])
True -- Include -hi-boot
- hsc_env
+ mg
+ hug
uid
mnwib
return (foldl' unionInstEnv emptyInstEnv insts, concat famInsts)
@@ -297,17 +299,18 @@ hugInstancesBelow hsc_env uid mnwib = do
-- | Get things from modules in the transitive closure of the given module.
--
-- Note: Don't expose this function. This is a footgun if exposed!
-hugSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO [[a]]
+hugSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> ModuleGraph -> HomeUnitGraph -> UnitId -> ModuleNameWithIsBoot -> IO [[a]]
-- An explicit check to see if we are in one-shot mode to avoid poking the ModuleGraph thunk
-- These things are currently stored in the EPS for home packages. (See #25795 for
-- progress in removing these kind of checks; and making these functions of
-- `UnitEnv` rather than `HscEnv`)
-- See Note [The ModuleGraph]
-hugSomeThingsBelowUs _ _ hsc_env _ _ | isOneShot (ghcMode (hsc_dflags hsc_env)) = return []
-hugSomeThingsBelowUs extract include_hi_boot hsc_env uid mn
- = let hug = hsc_HUG hsc_env
- mg = hsc_mod_graph hsc_env
- in
+hugSomeThingsBelowUs extract include_hi_boot mg hug uid mn =
+ -- If the first hpt is a one-shot table, we don't recurse into it.
+ -- TODO @fendor: I guess that's nonsense to a certain degree
+ if HPT.isOneShotMode $ homeUnitEnv_hpt $ unitEnv_lookup uid hug
+ then pure []
+ else
sequence
[ things
-- "Finding each non-hi-boot module below me" maybe could be cached (well,
@@ -347,7 +350,7 @@ prepareAnnotations hsc_env mb_guts = do
-- entries regardless of dependency ordering.
get_mod mg = (moduleUnitId (mg_module mg), GWIB (moduleName (mg_module mg)) NotBoot)
home_pkg_anns <- fromMaybe (hugAllAnns (hsc_unit_env hsc_env))
- $ uncurry (hugAnnsBelow hsc_env)
+ $ uncurry (hugAnnsBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env))
. get_mod <$> mb_guts
more_home_pkg_anns <- HomePackageTable.hptLoadedAnnEnv $ hsc_HPT hsc_env
let
=====================================
compiler/GHC/Driver/Main/Hsc.hs
=====================================
@@ -107,7 +107,10 @@ import System.IO
newHscEnv :: FilePath -> DynFlags -> IO HscEnv
newHscEnv top_dir dflags = do
- hpt <- emptyHomePackageTable
+ hpt <- case ghcMode dflags of
+ OneShot -> emptyOnDemandHomePackageTable
+ CompManager -> emptyHomePackageTable
+ MkDepend -> emptyHomePackageTable
newHscEnvWithHUG top_dir dflags (homeUnitId_ dflags) (home_unit_graph hpt)
where
home_unit_graph hpt = HUG.unitEnv_singleton
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -100,66 +100,65 @@ import GHC.Builtin.PrimOps.Ids
import GHC.Builtin.WiredIn.Prim
import GHC.Builtin.WiredIn.Ids( seqId )
+import GHC.Core (CoreRule)
+import GHC.Core.FamInstEnv
+import GHC.Core.InstEnv
import GHC.Core.Rules
import GHC.Core.TyCon
-import GHC.Core.InstEnv
-import GHC.Core.FamInstEnv
-import GHC.Parser.Annotation( noLocA, noAnn )
+import GHC.Parser.Annotation (noAnn, noLocA)
import GHC.Types.Annotations
+import GHC.Types.Avail
+import GHC.Types.DefaultEnv (DefaultEnv)
+import GHC.Types.Fixity
+import GHC.Types.Fixity.Env
import GHC.Types.Id
import GHC.Types.Name
import GHC.Types.Name.Cache
import GHC.Types.Name.Env
import GHC.Types.Name.Reader
-import GHC.Types.Avail
-import GHC.Types.Fixity
-import GHC.Types.Fixity.Env
+import GHC.Types.PkgQual
+import GHC.Types.SafeHaskell
import GHC.Types.SourceError
import GHC.Types.SourceFile
-import GHC.Types.SafeHaskell
-import GHC.Types.TypeEnv
-import GHC.Types.Unique.DSet
-import GHC.Types.Unique.Map( listToUniqMap )
-import GHC.Types.Unique.FM( UniqFM, listToUFM, lookupUFM, elemUFM )
+import GHC.Types.SourceText
import GHC.Types.SrcLoc
import GHC.Types.TyThing
-import GHC.Types.PkgQual
-import GHC.Types.SourceText
+import GHC.Types.TypeEnv
+import GHC.Types.Unique.DSet
+import GHC.Types.Unique.FM (UniqFM, elemUFM, listToUFM, lookupUFM)
+import GHC.Types.Unique.Map (listToUniqMap)
+import GHC.Unit.Env
import GHC.Unit.External
+import GHC.Unit.Finder
+import GHC.Unit.Home
+import GHC.Unit.Home.Graph qualified as HUG
+import GHC.Unit.Home.ModInfo (HomeModInfo (..), emptyHomeModInfoLinkable)
+import GHC.Unit.Home.PackageTable
+import GHC.Unit.Home.PackageTable qualified as HomePackageTable
import GHC.Unit.Module
+import GHC.Unit.Module.Deps
import GHC.Unit.Module.Graph
-import GHC.Unit.Module.Warnings
+import GHC.Unit.Module.ModDetails (ModDetails (..))
import GHC.Unit.Module.ModIface
-import GHC.Unit.Module.Deps
+import GHC.Unit.Module.Warnings
import GHC.Unit.State
-import GHC.Unit.Home
-import qualified GHC.Unit.Home.Graph as HUG
-import GHC.Unit.Home.PackageTable
-import GHC.Unit.Finder
-import GHC.Unit.Env
import GHC.Stack( callStack )
import GHC.Data.Maybe
import Language.Haskell.Syntax.Lit (StringLiteral(..))
+import Control.Applicative ((<|>))
import Control.Monad
-import qualified Data.Foldable as Foldable
+import Data.Foldable qualified as Foldable
import Data.Function ((&))
-import Data.Map ( toList )
-import qualified Data.Set as Set
-import System.FilePath
+import Data.Map (toList)
+import Data.Set qualified as Set
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 ((<|>))
+import System.FilePath
{- *********************************************************************
@@ -799,8 +798,8 @@ loadInterface doc_str mod from
-- READ THE MODULE IN
; hpt <- getHpt
- ; hls <- liftIO (hptLoaderState hpt)
- ; read_result <- case wantHiBootFile mhome_unit hls mod from of
+ ; is_boot_map <- liftIO (hptLoadedIsBoot hpt)
+ ; read_result <- case wantHiBootFile mhome_unit is_boot_map mod from of
Failed err -> return (Failed err)
Succeeded hi_boot_file -> do
hsc_env <- getTopEnv
@@ -836,7 +835,7 @@ loadInterface doc_str mod from
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
+ addModIfacePartsToHpt gbl_env mod iface tcParts
else dontLeakTheHUG $ do
-- Load the new ModIface into the External Package State
--
@@ -868,37 +867,36 @@ loadInterface doc_str mod from
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)
+ ignore_prags <- goptM Opt_IgnoreInterfacePragmas
+ new_decls <- tcIfaceDecls ignore_prags (mi_decls iface)
+ new_insts <- mapM tcIfaceInst (mi_insts iface)
+ new_defaults <- tcIfaceDefaults mod (mi_defaults iface)
+ new_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
+ new_rules <- tcIfaceRules ignore_prags (mi_rules iface)
+ new_anns <- tcIfaceAnnotations (mi_anns iface)
+ new_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
+ ( new_decls
+ , new_insts
+ , new_defaults
+ , new_fam_insts
+ , new_rules
+ , new_anns
+ , new_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
+addModIfacePartsToHpt :: IfGblEnv -> Module -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToHpt gbl_env mod iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
let
details = ModDetails
- { md_types = mkNameEnv new_eps_decls
+ { md_types = mkNameEnv new_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
+ , md_defaults = new_defaults
+ , md_insts = mkInstEnv new_insts
+ , md_fam_insts = new_fam_insts
+ , md_rules = new_rules
+ , md_anns = new_anns
+ , md_complete_matches = new_complete_matches
}
bad_boot = mi_boot iface == IsBoot
@@ -909,16 +907,11 @@ addModIfacePartsToHpt gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_e
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 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
+ liftIO $ addOnDemandHomeModule hpt mod bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches)
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
+addModIfacePartsToEps gbl_env mod loc iface (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
purged_hsc_env <- getTopEnv
let
@@ -942,7 +935,7 @@ addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_e
--
-- See Note [Interface Files with Core Definitions]
add_bytecode old
- | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls)
+ | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_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.
@@ -956,36 +949,36 @@ addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_e
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 }
+ then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_decls }
else
eps {
eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
- eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
+ eps_PTE = addDeclsToPTE (eps_PTE eps) new_decls,
eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
eps_rule_base = extendRuleBaseList (eps_rule_base eps)
- new_eps_rules,
+ new_rules,
eps_complete_matches
- = eps_complete_matches eps ++ new_eps_complete_matches,
+ = eps_complete_matches eps ++ new_complete_matches,
eps_inst_env = extendInstEnvList (eps_inst_env eps)
- new_eps_insts,
+ new_insts,
eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
- new_eps_fam_insts,
+ new_fam_insts,
eps_ann_env = extendAnnEnvList (eps_ann_env eps)
- new_eps_anns,
+ new_anns,
eps_mod_fam_inst_env
= let
fam_inst_env =
extendFamInstEnvList emptyFamInstEnv
- new_eps_fam_insts
+ new_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
+ (length new_decls)
+ (length new_insts)
+ (length new_rules),
+ eps_defaults = extendModuleEnv (eps_defaults eps) mod new_defaults
}
@@ -1204,10 +1197,10 @@ moduleFreeHolesPrecise doc_str mod
return (Succeeded (renameFreeHoles ifhs insts))
Failed err -> return (Failed err)
-wantHiBootFile :: Maybe HomeUnit -> HomeLoaderState -> Module -> WhereFrom
+wantHiBootFile :: Maybe HomeUnit -> InstalledModuleEnv ModuleNameWithIsBoot -> Module -> WhereFrom
-> MaybeErr MissingInterfaceError IsBootInterface
-- Figure out whether we want Foo.hi or Foo.hi-boot
-wantHiBootFile mhome_unit hls mod from
+wantHiBootFile mhome_unit is_boot_map mod from
= case from of
ImportByUser usr_boot
| usr_boot == IsBoot && notHomeModuleMaybe mhome_unit mod
@@ -1226,9 +1219,9 @@ wantHiBootFile mhome_unit hls mod from
-- We never import boot modules from other packages!
| otherwise
- -> case hlsIsBoot hls (toUnitId <$> mod) of
- Just is_boot ->
- Succeeded is_boot
+ -> case lookupInstalledModuleEnv is_boot_map (toUnitId <$> mod) of
+ Just mnib ->
+ Succeeded $ gwib_isBoot mnib
Nothing ->
Succeeded NotBoot
-- The boot-ness of the requested interface,
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -427,10 +427,9 @@ checkVersions hsc_env mod_summary iface self_recomp
-- (in which case we are done with this module) or it'll fail (in which
-- case we'll compile the module from scratch anyhow).
- when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- ; hpt <- getHpt
- ; liftIO $ hlsSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface))
- }
+ ; hpt <- getHpt
+ ; liftIO $ hptSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface))
+
; recomp <- checkList [checkModUsage (hsc_FC hsc_env) u
| u <- mi_sr_usages self_recomp]
; case recomp of (NeedsRecompile reason) -> return $ OutOfDateItem reason (Just iface) ; _ -> do {
=====================================
compiler/GHC/IfaceToCore.hs
=====================================
@@ -633,12 +633,12 @@ tcHiBootIface hsc_src mod
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
do { hpt <- getHpt
- ; hls <- liftIO $ hptLoaderState hpt
- ; case hlsIsBoot hls (toUnitId <$> mod) of
+ ; is_boot_map <- liftIO $ hptLoadedIsBoot hpt
+ ; case lookupInstalledModuleEnv is_boot_map (toUnitId <$> mod) of
-- The typical case
Nothing -> return NoSelfBoot
-- error cases
- Just is_boot -> case is_boot of
+ Just mnib -> case gwib_isBoot mnib of
IsBoot ->
let diag = Can'tFindInterface err
(LookingForHiBoot mod)
=====================================
compiler/GHC/Tc/Module.hs
=====================================
@@ -191,7 +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)
+import GHC.Unit.Home.PackageTable (hptSetBootInfo)
{-
************************************************************************
@@ -501,21 +501,19 @@ tcRnImports hsc_env import_decls
-- modules batch (@--make@) compiled before this one, but
-- which are not below this one.
; (home_insts, home_fam_insts) <- liftIO $
- hugInstancesBelow hsc_env unitId mnwib
+ hugInstancesBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) unitId mnwib
-- We use 'unsafeInterleaveIO' to avoid redundant memory allocations
-- See Note [Lazily loading COMPLETE pragmas] from GHC.HsToCore.Monad
-- and see https://gitlab.haskell.org/ghc/ghc/-/merge_requests/14274#note_620545
; completeSigsBelow <- liftIO $ unsafeInterleaveIO $
- hugCompleteSigsBelow hsc_env unitId mnwib
+ hugCompleteSigsBelow (hsc_mod_graph hsc_env) (hsc_HUG hsc_env) unitId mnwib
- -- Record boot-file info in the EPS, so that it's
+ -- Record boot-file info in the HPT, so that it's
-- visible to loadHiBootInterface in tcRnSrcDecls,
-- and any other incrementally-performed imports
- ; when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- ; hpt <- getHpt
- ; liftIO $ hlsSetBootInfo hpt (imp_boot_mods imports)
- }
+ ; hpt <- getHpt
+ ; liftIO $ hptSetBootInfo hpt (imp_boot_mods imports)
-- Update the gbl env
; updGblEnv ( \ gbl ->
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -21,13 +21,17 @@
-- Or, do you really need a function to traverse all modules in the HPT? It is
-- often better to keep the computation internal to this module, such as in
-- 'hptCollectObjects'...
+{-# OPTIONS_GHC -Wall -Wincomplete-record-selectors #-}
module GHC.Unit.Home.PackageTable
(
HomePackageTable(..)
, emptyHomePackageTable
+ , emptyOnDemandHomePackageTable
- , HomeLoaderState -- TODO: should this be opaque? Probably
- , emptyHomeLoaderState
+ , isOneShotMode
+
+ -- , HomeLoaderState -- TODO: should this be opaque? Probably
+ -- , emptyHomeLoaderState
-- * Lookups in the HPT
, lookupHpt
@@ -42,13 +46,14 @@ module GHC.Unit.Home.PackageTable
, restrictHpt
-- * Queries about home modules
+ , listHptIfaces
, hptCompleteSigs
, hptAllInstances
, hptAllFamInstances
, hptAllAnnotations
, hlsIsModuleNameWithBoot
, hlsIsBoot
- , hlsSetBootInfo
+ , hptSetBootInfo
, hptLoadedIsBoot
, hptLoadedTypeEnv
, hptLoadedInstEnv
@@ -78,9 +83,8 @@ module GHC.Unit.Home.PackageTable
--
-- In GHC itself these should be avoided, and other uses should justify why
-- it is not sufficient to go through the intended insert-only API.
- , hptInternalTableRef
+ -- , hptInternalTableRef
, hptInternalTableFromRef
- , hptLoaderState
-- * Legacy API
--
-- | This API is deprecated and meant to be removed.
@@ -98,7 +102,6 @@ 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
@@ -117,24 +120,14 @@ import GHC.Types.DefaultEnv (DefaultEnv)
import GHC.Core
-- | Helps us find information about modules in the home package
-data HomePackageTable = HPT {
+data HomePackageTable
+ = HPT_Make { table :: {-# UNPACK #-} !(IORef (DModuleNameEnv HomeModInfo)) }
+ | HPT_OneShot { loader :: {-# UNPACK #-} !(IORef HomeLoaderState) }
- 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).
- -- Moreover, the HPT invariant allows mutability in this table without compromising thread safety or soundness.
- -- To recall:
- -- A query to the HPT should depend only on data relevant to that query, such that
- -- there being more or less unrelated entries in the HPT does not influence the result in any way.
- --
- -- Note that the HPT increases monotonically, except at certain barrier
- -- points like when 'restrictHpt' is called. At these barriers, it is safe
- -- to temporarily violate the HPT monotonicity.
- --
- -- The elements of this table may be updated (e.g. on rehydration).
- loader :: IORef HomeLoaderState
- }
+isOneShotMode :: HomePackageTable -> Bool
+isOneShotMode = \ case
+ HPT_OneShot{} -> True
+ HPT_Make{} -> False
-- | Create a new 'HomePackageTable'.
--
@@ -145,14 +138,19 @@ emptyHomePackageTable :: IO HomePackageTable
-- romes:todo: use a MutableArray directly?
emptyHomePackageTable = do
table <- newIORef emptyUDFM
+ return HPT_Make{table}
+
+emptyOnDemandHomePackageTable :: IO HomePackageTable
+emptyOnDemandHomePackageTable = do
loader <- newIORef emptyHomeLoaderState
- return HPT{table, loader}
+ return HPT_OneShot{loader}
data HomeLoaderState = HomeLoaderState
- { hls_modules :: ModuleEnv ()
+ { hls_table :: DModuleNameEnv HomeModInfo
+ , hls_modules :: ModuleEnv ()
, hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
, hls_type_env :: !TypeEnv
- , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
+ -- , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
, hls_inst_env :: !InstEnv
, hls_fam_inst_env :: !FamInstEnv
, hls_mod_fam_inst_env :: !(ModuleEnv FamInstEnv)
@@ -165,10 +163,11 @@ data HomeLoaderState = HomeLoaderState
emptyHomeLoaderState :: HomeLoaderState
emptyHomeLoaderState =
HomeLoaderState
- { hls_modules = emptyModuleEnv
+ { hls_table = emptyUDFM
+ , hls_modules = emptyModuleEnv
, hls_is_boot = emptyInstalledModuleEnv
, hls_type_env = emptyTypeEnv
- , hls_iface_bytecode = emptyModuleEnv
+ -- , hls_iface_bytecode = emptyModuleEnv
, hls_inst_env = emptyInstEnv
, hls_fam_inst_env = emptyFamInstEnv
, hls_mod_fam_inst_env = emptyModuleEnv
@@ -184,46 +183,57 @@ emptyHomeLoaderState =
-- | Lookup the 'HomeModInfo' of a module in the HPT, given its name.
lookupHpt :: HomePackageTable -> ModuleName -> IO (Maybe HomeModInfo)
-lookupHpt HPT{table=hpt} mn = (`lookupUDFM` mn) <$!> readIORef hpt
+lookupHpt HPT_Make{table=hpt} mn = (`lookupUDFM` mn) <$!> readIORef hpt
+lookupHpt HPT_OneShot{loader=hpt} mn = (`lookupUDFM` mn) . hls_table <$!> readIORef hpt
-- | Lookup the 'HomeModInfo' of a 'Module' in the HPT.
lookupHptByModule :: HomePackageTable -> Module -> IO (Maybe HomeModInfo)
-lookupHptByModule hpt mod
+lookupHptByModule hpt modl
= -- The HPT is indexed by ModuleName, not Module,
-- we must check for a hit on the right Module
- lookupHpt hpt (moduleName mod) >>= pure . \case
- Just hm | mi_module (hm_iface hm) == mod -> Just hm
+ lookupHpt hpt (moduleName modl) >>= pure . \case
+ Just hm | mi_module (hm_iface hm) == modl -> Just hm
_otherwise -> Nothing
-hptLoaderState :: HomePackageTable -> IO HomeLoaderState
-hptLoaderState = readIORef . loader
+queryOnDemandHpt :: a -> (HomeLoaderState -> a) -> HomePackageTable -> IO a
+queryOnDemandHpt a f hpt =
+ case hpt of
+ HPT_Make{} ->
+ pure a
+ HPT_OneShot{loader} ->
+ f <$> readIORef loader
hptLoadedIsBoot :: HomePackageTable -> IO (InstalledModuleEnv ModuleNameWithIsBoot)
-hptLoadedIsBoot hpt = hls_is_boot <$> readIORef (loader hpt)
+hptLoadedIsBoot = queryOnDemandHpt emptyInstalledModuleEnv hls_is_boot
hptLoadedTypeEnv :: HomePackageTable -> IO TypeEnv
-hptLoadedTypeEnv hpt = hls_type_env <$> readIORef (loader hpt)
+hptLoadedTypeEnv = queryOnDemandHpt emptyTypeEnv hls_type_env
hptLoadedInstEnv :: HomePackageTable -> IO InstEnv
-hptLoadedInstEnv hpt = hls_inst_env <$> readIORef (loader hpt)
+hptLoadedInstEnv = queryOnDemandHpt emptyInstEnv hls_inst_env
hptLoadedFamInstEnv :: HomePackageTable -> IO FamInstEnv
-hptLoadedFamInstEnv hpt = hls_fam_inst_env <$> readIORef (loader hpt)
+hptLoadedFamInstEnv = queryOnDemandHpt emptyFamInstEnv hls_fam_inst_env
hptLoadedModFamInstEnv :: HomePackageTable -> IO (ModuleEnv FamInstEnv)
-hptLoadedModFamInstEnv hpt = hls_mod_fam_inst_env <$> readIORef (loader hpt)
+hptLoadedModFamInstEnv = queryOnDemandHpt emptyModuleEnv hls_mod_fam_inst_env
hptLoadedRuleBase :: HomePackageTable -> IO RuleBase
-hptLoadedRuleBase hpt = hls_rule_base <$> readIORef (loader hpt)
+hptLoadedRuleBase = queryOnDemandHpt emptyRuleBase hls_rule_base
hptLoadedAnnEnv :: HomePackageTable -> IO AnnEnv
-hptLoadedAnnEnv hpt = hls_ann_env <$> readIORef (loader hpt)
+hptLoadedAnnEnv = queryOnDemandHpt emptyAnnEnv hls_ann_env
hptLoadedCompleteMatches :: HomePackageTable -> IO CompleteMatches
-hptLoadedCompleteMatches hpt = hls_complete_matches <$> readIORef (loader hpt)
+hptLoadedCompleteMatches = queryOnDemandHpt [] hls_complete_matches
hptLoadedDefaults :: HomePackageTable -> IO (ModuleEnv DefaultEnv)
-hptLoadedDefaults hpt = hls_defaults <$> readIORef (loader hpt)
+hptLoadedDefaults = queryOnDemandHpt emptyModuleEnv hls_defaults
+
+listHptIfaces :: HomePackageTable -> IO (DModuleNameEnv HomeModInfo)
+listHptIfaces = \ case
+ HPT_Make{table} -> readIORef table
+ HPT_OneShot{loader} -> hls_table <$> readIORef loader
--------------------------------------------------------------------------------
-- * Extending the HPT
@@ -244,10 +254,12 @@ addHomeModInfoToHpt hmi hpt = addToHpt hpt (moduleName (mi_module (hm_iface hmi)
{-# DEPRECATED addToHpt "Deprecated in favour of 'addHomeModInfoToHpt', as the module at which a 'HomeModInfo' is inserted should always be derived from the 'HomeModInfo' itself." #-}
-- After deprecation cycle, move `addToHpt` to a `where` clause inside `addHomeModInfoToHpt`.
addToHpt :: HomePackageTable -> ModuleName -> HomeModInfo -> IO ()
-addToHpt HPT{table=hptr} mn hmi = do
+addToHpt HPT_Make{table=hptr} mn hmi = do
atomicModifyIORef' hptr (\hpt -> (addToUDFM hpt mn hmi, ()))
-- If the key already existed in the map, this insertion is overwriting
-- the HMI of a previously loaded module (likely in rehydration).
+addToHpt HPT_OneShot{loader=hptr} mn hmi = do
+ atomicModifyIORef' hptr (\hpt -> (hpt { hls_table = addToUDFM (hls_table hpt) mn hmi }, ()))
-- | 'addHomeModInfoToHpt' for multiple module infos.
addHomeModInfosToHpt :: HomePackageTable -> [HomeModInfo] -> IO ()
@@ -262,19 +274,21 @@ addHomeModInfosToHpt hpt = mapM_ (flip addHomeModInfoToHpt hpt)
-- called at barrier points, such as the end of upsweep, when all threads are
-- done and we want to clean up failed entries.
restrictHpt :: HomePackageTable -> [HomeModInfo] -> IO ()
-restrictHpt HPT{table=hptr} hmis =
+restrictHpt HPT_Make{table=hptr} hmis =
let key_set = map (getKey . getUnique . hmi_mod) hmis
hmi_mod hmi = moduleName (mi_module (hm_iface hmi))
in atomicModifyIORef' hptr (\hpt -> (udfmRestrictKeysSet hpt (W64.fromList key_set), ()))
+restrictHpt HPT_OneShot{} _ = pure ()
{-# DEPRECATED addListToHpt "Deprecated in favour of 'addHomeModInfosToHpt', as the module at which a 'HomeModInfo' is inserted should always be derived from the 'HomeModInfo' itself." #-}
-- After deprecation cycle, remove.
addListToHpt :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> IO ()
addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
-addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
-addOnDemandHomeModule hpt mn 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 ->
+addOnDemandHomeModule :: HomePackageTable -> Module -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IO ()
+addOnDemandHomeModule HPT_Make{} _ _ _ = pure ()
+addOnDemandHomeModule HPT_OneShot{loader} mn bad_boot (new_decls, new_insts, new_defaults, new_fam_insts, new_rules, new_anns, new_complete_matches) = do
+ atomicModifyIORef loader $ \hls ->
( if mn `elemModuleEnv` hls_modules hls
then hls -- If already loaded, don't add twice
else
@@ -285,41 +299,39 @@ addOnDemandHomeModule hpt mn bad_boot (new_hls_decls, new_hls_insts, new_hls_def
)
where
addHomeModTypeEnv hls = hls
- { hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls
+ { hls_type_env = extendNameEnvList (hls_type_env hls) new_decls
}
addHomeModData hls = hls {
- hls_modules = extendModuleEnv (hls_modules hls) mn (),
- 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_modules = extendModuleEnv (hls_modules hls) mn (),
+ hls_type_env = extendNameEnvList (hls_type_env hls) new_decls,
hls_rule_base = extendRuleBaseList (hls_rule_base hls)
- new_hls_rules,
+ new_rules,
hls_complete_matches
- = hls_complete_matches hls ++ new_hls_complete_matches,
+ = hls_complete_matches hls ++ new_complete_matches,
hls_inst_env = extendInstEnvList (hls_inst_env hls)
- new_hls_insts,
+ new_insts,
hls_fam_inst_env = extendFamInstEnvList (hls_fam_inst_env hls)
- new_hls_fam_insts,
+ new_fam_insts,
hls_ann_env = extendAnnEnvList (hls_ann_env hls)
- new_hls_anns,
+ new_anns,
hls_mod_fam_inst_env
=
let
fam_inst_env =
extendFamInstEnvList emptyFamInstEnv
- new_hls_fam_insts
+ new_fam_insts
in
extendModuleEnv (hls_mod_fam_inst_env hls)
mn
fam_inst_env,
- hls_defaults = extendModuleEnv (hls_defaults hls) mn new_hls_defaults
+ hls_defaults = extendModuleEnv (hls_defaults hls) mn new_defaults
}
-hlsSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
-hlsSetBootInfo hpt is_boot_env =
- atomicModifyIORef' (loader hpt) $ \ hls ->
+hptSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
+hptSetBootInfo HPT_Make{} _ = pure ()
+hptSetBootInfo HPT_OneShot{loader} is_boot_env =
+ atomicModifyIORef' loader $ \ hls ->
(hls { hls_is_boot = is_boot_env }, ())
----------------------------------------------------------------------------------
@@ -370,7 +382,11 @@ hlsIsModuleNameWithBoot hls mn = lookupInstalledModuleEnv (hls_is_boot hls) mn
-- currently takes all dependencies only to then filter them with an ad-hoc transitive closure check.
-- See #25639
hptCollectDependencies :: HomePackageTable -> IO (Set.Set (IfaceImportLevel, UnitId))
-hptCollectDependencies HPT{table} = do
+hptCollectDependencies HPT_OneShot{loader} = do
+ hpt <- readIORef loader
+ return $
+ foldr (Set.union . dep_direct_pkgs . mi_deps . hm_iface) Set.empty (hls_table hpt)
+hptCollectDependencies HPT_Make{table} = do
hpt <- readIORef table
return $
foldr (Set.union . dep_direct_pkgs . mi_deps . hm_iface) Set.empty hpt
@@ -380,7 +396,11 @@ hptCollectDependencies HPT{table} = do
--
-- $O(n)$ in the number of modules in the HPT.
hptCollectHomeModInfo :: HomePackageTable -> IO [HomeModInfo]
-hptCollectHomeModInfo HPT{table} = do
+hptCollectHomeModInfo HPT_OneShot{loader} = do
+ hpt <- readIORef loader
+ return $
+ foldr (:) [] (hls_table hpt)
+hptCollectHomeModInfo HPT_Make{table} = do
hpt <- readIORef table
return $
foldr (:) [] hpt
@@ -398,7 +418,13 @@ hptCollectHomeModInfo HPT{table} = do
-- unit map in failed lookups.
pprHPT :: HomePackageTable -> IO SDoc
-- A bit arbitrary for now
-pprHPT HPT{table=hptr} = do
+pprHPT HPT_OneShot{loader=hptr} = do
+ hpt <- readIORef hptr
+ return $!
+ pprUDFM (hls_table hpt) $ \hms ->
+ vcat [ ppr (mi_module (hm_iface hm))
+ | hm <- hms ]
+pprHPT HPT_Make{table=hptr} = do
hpt <- readIORef hptr
return $!
pprUDFM hpt $ \hms ->
@@ -437,7 +463,12 @@ pprHPT HPT{table=hptr} = do
-- If this function is ever exposed from the HPT module, make sure the
-- argument function doesn't introduce leaks.
concatHpt :: (HomeModInfo -> [a]) -> HomePackageTable -> IO [a]
-concatHpt f HPT{table} = do
+concatHpt f HPT_OneShot{loader} = do
+ hpt <- readIORef loader
+ return $ concat . eltsUDFM . mapMaybeUDFM g $ hls_table hpt
+ where
+ g hmi = case f hmi of { [] -> Nothing; as -> Just as }
+concatHpt f HPT_Make{table} = do
hpt <- readIORef table
return $ concat . eltsUDFM . mapMaybeUDFM g $ hpt
where
@@ -449,15 +480,15 @@ concatHpt f HPT{table} = do
-- | Gets the internal 'IORef' which holds the 'HomeModInfo's of this HPT.
-- Use with care.
-hptInternalTableRef :: HomePackageTable -> IORef (DModuleNameEnv HomeModInfo)
-hptInternalTableRef = table
+-- hptInternalTableRef :: HomePackageTable -> IORef (DModuleNameEnv HomeModInfo)
+-- hptInternalTableRef = \ case
+-- HPT_Make{table} -> table
+-- HPT_OneShot{} -> -- TODO: @fendor how does this make sense?
-- | Construct a HomePackageTable from the IORef.
-- 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,
- loader
+ return HPT_Make {
+ table = ref
}
=====================================
ghc/GHCi/Leak.hs
=====================================
@@ -7,7 +7,6 @@ module GHCi.Leak
import Control.Monad
import Data.Bits
-import Data.IORef
import Foreign.Ptr (ptrToIntPtr, intPtrToPtr)
import GHC
import GHC.Ptr (Ptr (..))
@@ -43,7 +42,7 @@ data LeakModIndicators = LeakModIndicators
getLeakIndicators :: HscEnv -> IO LeakIndicators
getLeakIndicators hsc_env =
fmap LeakIndicators $ do
- hpt <- readIORef $ hptInternalTableRef $ hsc_HPT hsc_env
+ hpt <- listHptIfaces $ hsc_HPT hsc_env
forM (eltsUDFM hpt) $ \hmi@HomeModInfo{..} -> do
leakMod <- mkWeakPtr hmi Nothing
leakIface <- mkWeakPtr hm_iface Nothing
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/c00e2758112af1126cdcc1d51cae870…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/c00e2758112af1126cdcc1d51cae870…
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/global-break-action] 2 commits: Global break action which uses a per-thread context map
by Rodrigo Mesquita (@alt-romes) 30 Nov '26
by Rodrigo Mesquita (@alt-romes) 30 Nov '26
30 Nov '26
Rodrigo Mesquita pushed to branch wip/romes/global-break-action at Glasgow Haskell Compiler / GHC
Commits:
b6308b7b by Rodrigo Mesquita at 2026-11-30T11:36:42+00:00
Global break action which uses a per-thread context map
Previously, everytime an expression was run in the interpreter (`sandboxIO`):
1) the RTS global variable `rts_breakpoint_io_action`, which is run
anytime any thread hits a breakpoint, got set to a new action that:
a) Wrote the breakpoint hit by the thread to the `statusMVar`
b) Blocked waiting on a newly created MVar `breakMVar` for a `resumeStmt` to
signal it.
2) Start the expression evaluation on a new "sandbox" thread
3) Block waiting on `statusMVar` for a breakpoint to be hit, and we'd
return the read `EvalBreak`
4) Set the `rts_breakpoint_io_action` to a no-op which prints "Ignored breakpoint..."
At some later point, we could `resumeStmt` with the `EvalBreak` context
by signaling the `breakMVar` on which the thread that hit the breakpoint
is blocked.
However, if you consider an expression which forks off threads which hit
breakpoints, surprising things may happen:
main = do
-- the `worker` code has a breakpoint
mapM (forkIO . worker) [1..10]
forever $ threadDelay 10000000
Interpreting this program, we'll do (1,2,3), and all workers will hit
their breakpoint and run `rts_breakpoint_io_action`. Here's a first
issue:
1. The first worker succeeds in `putMVar statusMVar`
2. The interpreter will read `takeMVar statusMVar` (3) and then (4)
3. The remaining workers are hitting the breakpoint concurrently:
- Some may block trying to `putMVar statusMVar`
- Some may run the no-op action which discards the breakpoint
Depending on whether the remaining workers hit the breakpoint or (4)
happens first, some workers will skip their breakpoint.
Now, let's pretend all workers can block on `putMVar statusMVar`. Since
the interpreter will take the breakpoints one by one, and resume them
one by one, it seemingly works. However, that's only fine when we assume
only one expression is evaluated at once. As soon as multiple
expressions can be evaluated at once (a desireable property of a
debugger, as well as something that can already happen today in some
scenarios (see `break049`)), it becomes madness:
The second issue comes the global break action being swapped by a second
evaluation and threads from the first evaluation running the "wrong" action.
Consider:
1. eval `expr_A` installs a break action that puts on `statusMVar_A`
2. `expr_A` forks off a few threads, they're running in the background
3. eval `expr_B` sets the break action to put on `statusMVar_B`
4. the `expr_A` forked threads hit a breakpoint and put `statusMVar_B`
5. `expr_B` returns with a breakpoint of `expr_A`, `resume expr_B` would
resume `expr_A`, etc...
A third issue with having a single MVar for all threads of an execution
is that there is no way to have fine-grained control over which threads
are resumed and which are stopped. This is often necessary to debug
multi-threaded programs too.
Therefore, it is imperative that the global break action does not
capture a global single MVar when many expressions with many
corresponding threads can be running in the interpreter/debugger at
once, if we want to support debugging multi-threaded programs at all.
---
This commit fixes these foundational issues by making the global break
action truly global (i.e. never modified and never capturing any locals).
The global break action is installed once in `sandboxIO` and never
removed (`withBreakAciton` and `noBreakAction` were killed). Subsequent
runs of `sandboxIO` re-rewrite the same break action (a no-op).
When any thread hits the global break action, it looks its `ThreadId` up
in the global per-thread context mapping, returning a `ResumeContext`
which contains that thread's `breakMVar` (now `resumeBreakVar`) and
`statusMVar` (now `resumeEvalStatus`). Each thread blocks on its own
MVar and replies on its own TVar. There is no longer one global status
nor break MVar.
To resume a thread by its `ThreadId`, we can simply fetch its
`ResumeContext` and signal the corresponding `resumeBreakMVar`
To wait for a result or for a breakpoint in a specific thread, we do
`readThreadEvalStatus`. To wait for any breakpoint hit in any thread at
all, we have `readAnyThreadEvalBreak`.
Some evaluations will only care to look at their own result and breaks
(so they run with `readAllBreaks` `= False`); and the main thread of an
evaluation should not be read by other evaluations. In short, only
threads forked off by the main thread of evaluations get read with
`readAnyThreadEvalBreak`. If two evaluations fork off threads in the
background, `readAnyThreadEvalBreak` may return threads from any of
them. There is no just way to distinguish their "parents" at runtime.
For instance, `compileParsedExprRemote` should run an expression until
completion without any existing threads interfering with its execution,
so it runs with `readAllBreaks = False`. Otherwise, by default, running
`main` on the REPL, we'll want to stop at any break any forked thread
hits, just like we did before.
P.S. Currently, we need to keep track of the "main expression thread"
being currently evaluated to fetch its result, but, when `evalStmt`
becomes asynchronous by returning the `ThreadId` of the "sandbox"
thread, the whole `evaluationMainThreadGlobalVar` hack can be deleted.
---
New tests observing behavior that we don't want to break (which I broke
at some point while developing this patch):
- break032: we don't stop at breakpoints in TH
- break033: :continue after -fbreak-on-exception doesn't hit exception breakpoint
- break034: test :abandon doesn't hang with -fbreak-on-error
- conc033: also run with the external interpreter
- ForceInterrupt(Ext): ^C during :force interrupts the forced expression
- break043: :continue of a forked thread reads main thread breaks/results too
- break046: evaluating expr while stopped doesn't change what :continue resumes
- break048: evaluating expr while forked thread is stopped doesn't hit again current breakpoint
New tests that failed before this commit:
- T3171(ext)nosandbox: T3171 with -fno-ghci-sandbox (T3171extnosandbox still fails)
- break050(ext): ^C during :continue of a forked thread interrupts that thread
Fixed ext-interp bc. resumeStmt now does unsafeUnmask, just like
sandboxIO, so the UserInterrupt reaches the resume.
- break049: breakpoints in forked threads don't get mixed up with other evaluations
This test demonstrates one way multi-threaded debugging can go wrong
bc the global break action used to capture a break MVar for a
specific thread that is shared by all threads (described above as
"the second issue"). Here is the annotated execution of the test
*before this commit*:
```haskell
ghci> main
Stopped in Main.inMain, break049.hs:30:12-18
_result :: IO () = _
[break049.hs:30:12-18] ghci> :force slow
-- ANN: the breakpoint we're ignoring on :force is the worker's
-- breakpoint, and it's just discarded
*** Ignoring breakpoint [break049.hs:27:14-20]
slow = 5
[break049.hs:30:12-18] ghci> :cmd return ""
-- ANN: we :continue `main`, but the worker should still be blocked
-- so `main` should block.
[break049.hs:30:12-18] ghci> :continue
-- ANN: however, it completes; recall the worker break was ignored
-- instead of stopping there
main done
-- ANN: after this commit, the worker break wouldn't have been read
-- by `:force`, and we'd see it when resuming `:main`, and
-- `:continue` here would resume the worker and only then main would
-- complete.
ghci> :continue
-- ANN: bc this is ghci before the commit, we see:
not stopped at a breakpoint
ghci>
```
- break042: main forks workers and all workers hit a breakpoint
This test witnesses "the first issue" described above, where the
workers hit breaks after the global break action was already removed
and so are lost.
Fixes #28124
- - - - -
31f4f82e by Rodrigo Mesquita at 2026-11-30T11:36:42+00:00
ci: unset CI_COMMIT_MESSAGE to avoid Windows environment length limits
The previous commit consistently made the Windows runner fail with:
> find: The environment is too large for exec().
GitLab sets these environment variables by default, but we never read
them. Just unset them at the start.
- - - - -
53 changed files:
- .gitlab/ci.sh
- + changelog.d/28124
- compiler/GHC/Driver/Config.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Tc/Gen/Splice.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Run.hs
- + libraries/ghci/GHCi/Run/Breakpoints.hs
- libraries/ghci/ghci.cabal.in
- rts/Interpreter.c
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/ghci.debugger/scripts/Makefile
- testsuite/tests/ghci.debugger/scripts/T14690.stdout
- testsuite/tests/ghci.debugger/scripts/all.T
- testsuite/tests/ghci.debugger/scripts/break024.stdout
- + testsuite/tests/ghci.debugger/scripts/break032.hs
- + testsuite/tests/ghci.debugger/scripts/break032.script
- + testsuite/tests/ghci.debugger/scripts/break032.stdout
- + testsuite/tests/ghci.debugger/scripts/break033.hs
- + testsuite/tests/ghci.debugger/scripts/break033.script
- + testsuite/tests/ghci.debugger/scripts/break033.stdout
- + testsuite/tests/ghci.debugger/scripts/break034.hs
- + testsuite/tests/ghci.debugger/scripts/break034.script
- + testsuite/tests/ghci.debugger/scripts/break034.stdout
- + testsuite/tests/ghci.debugger/scripts/break042.hs
- + testsuite/tests/ghci.debugger/scripts/break042.script
- + testsuite/tests/ghci.debugger/scripts/break042.stderr
- + testsuite/tests/ghci.debugger/scripts/break042.stdout
- + testsuite/tests/ghci.debugger/scripts/break043.hs
- + testsuite/tests/ghci.debugger/scripts/break043.script
- + testsuite/tests/ghci.debugger/scripts/break043.stdout
- + testsuite/tests/ghci.debugger/scripts/break046.hs
- + testsuite/tests/ghci.debugger/scripts/break046.script
- + testsuite/tests/ghci.debugger/scripts/break046.stdout
- + testsuite/tests/ghci.debugger/scripts/break048.hs
- + testsuite/tests/ghci.debugger/scripts/break048.script
- + testsuite/tests/ghci.debugger/scripts/break048.stdout
- + testsuite/tests/ghci.debugger/scripts/break049.hs
- + testsuite/tests/ghci.debugger/scripts/break049.script
- + testsuite/tests/ghci.debugger/scripts/break049.stdout
- + testsuite/tests/ghci.debugger/scripts/break050.hs
- + testsuite/tests/ghci.debugger/scripts/break050.script
- + testsuite/tests/ghci.debugger/scripts/break050.stdout
- + testsuite/tests/ghci.debugger/scripts/break050ext.stdout
- + testsuite/tests/ghci/should_run/ForceInterrupt.script
- + testsuite/tests/ghci/should_run/ForceInterrupt.stdout
- + testsuite/tests/ghci/should_run/ForceInterruptExt.stdout
- testsuite/tests/ghci/should_run/Makefile
- + testsuite/tests/ghci/should_run/T3171extnosandbox.stdout
- + testsuite/tests/ghci/should_run/T3171nosandbox.stdout
- testsuite/tests/ghci/should_run/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/04b20eca3f17529a0cdb2814053aa0…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/04b20eca3f17529a0cdb2814053aa0…
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