[Git][ghc/ghc][wip/case-bndr-unf] 4 commits: Lambda and case binders have vanilla IdInfo (#27965)
by Simon Peyton Jones (ļ¼ simonpj) 20 Nov '26
by Simon Peyton Jones (ļ¼ simonpj) 20 Nov '26
20 Nov '26
Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC
Commits:
3f621a5e by Simon Peyton Jones at 2026-11-20T17:44:35+00:00
Lambda and case binders have vanilla IdInfo (#27965)
Lambda binders, case binders, and case-alternative binders should never
have RULES, a (non-default) inline pragma, or a stable unfolding.
See new Note [Core binder IdInfo invariants] in GHC.Core, which
lays out the invariants.
This patch
* Makes Core Lint check the invariant, using the new predicate
GHC.Types.Id.lamBndrInfoOK.
* Fixes the desugarer, which violated it. For a strict binding
let !x = rhs in body
we generate
let x = rhs in case x of x { DEFAULT -> body }
re-using x (shadowed) as the case binder; see Note [Desugar Strict binds].
But the case binder inherited x's IdInfo, including, say, a NOINLINE
pragma (e.g. `res1` in GHC.Internal.Control.Monad.ST.Lazy.Imp). Now
GHC.HsToCore.Utils.seqVar gives the case binder vanilla IdInfo.
This was not just a matter of taste. For example
h fm s = let {-# NOINLINE res1 #-}
!res1 = fm s
!(f, s') = res1
in (f+1, s')
The NOINLINE case binder becomes a NOINLINE alias `let res3 = res2`,
which is never inlined, and survives (as a silly join point) into the
final code.
* Fixes the Simplifier, which could violate it when duplicating a
StrictBind continuation, which makes a join point
let x = <> in b ==> join j x = b in j <>
If x has such IdInfo, we now use a fresh binder for the join point
let x = <> in b ==> join j x' = let x = x' in b in j <>
See (DSB1) in Note [Duplicating StrictBind].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
6e1246f1 by Simon Peyton Jones at 2026-11-20T17:44:42+00:00
Add varIsHNF, and use it in move_transit_vars
`varIsHNF v` is the same as `exprIsHNF (Var v)`, but avoids building the
Var only to take it apart. The (Var v) case of exprIsHNFlike now uses
the shared varIsHNFlike, so the two cannot drift apart.
In GHC.Core.Opt.WorkWrap.Utils.move_transit_vars we had the guard
isUnliftedType var_ty || exprIsHNF (Var var)
but exprIsHNF is already True of variables of (definitely) unlifted type,
so the isUnliftedType test was redundant. Now it is just (varIsHNF var).
Also make `exprIsHNFlike` treat an application with no value arguments, such as
`f @Int`, exactly like the bare variable `f`, by going through varIsHNFlike.
Otherwise no change in behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7c8fffa3 by Simon Peyton Jones at 2026-11-20T17:44:54+00:00
Use SimplClo for the argument of ApplyToVal
This patch renames SimplSR to SimplClo (a "closure"), and uses it not
only as the range of the Simplifier's substitution, but also as the
argument of an ApplyToVal continuation. ApplyToVal used to have three
fields
sc_env :: StaticEnv
sc_arg :: CoreExpr
sc_cast :: MOutCoercion
but now has just
sc_dup :: DupFlag
sc_arg :: SimplClo
An un-simplified argument is (ContEx env arg mco), and an already-simplified
one is (DoneEx arg _). See Note [The argument of ApplyToVal] in
GHC.Core.Opt.Simplify.Utils.
The main payoff is that, since the substitution maps an Id to a SimplClo,
beta-reduction can substitute the argument for the lambda binder without
further ado. Accordingly, preInlineUnconditionally is split into
* preInlineLetUnconditionally, for let-bindings
* preInlineBetaUnconditionally, for beta-redexes, which takes a SimplClo
The latter omits some checks that cannot fire for lambda binders.
Other notes
* The new (ContEx env arg mco) form makes it easy to push a cast into an
argument (mkCloCastMCo), whether or not it has been simplified.
See Note [The MOutCoercion field of ContEx].
* `preInlineUnconditionally` gets split into two variants, one for
let-bindings and one for beta-reduction (which takes a `SimplClo`).
There is a little bit of duplication here, but not much.
* Fixes #27962. The simplifier was previously dropping a cast when dealing
with runRW#. The new `SimplClo` makes that bug much harder to allow.
* Fixes #27963. contOutArgs, which supplies the arguments for Plan (BEFORE)
rule matching, ignored the sc_cast field of ApplyToVal. So in
(f |> co) n ==> f (n |> co1) -- co1 in sc_cast
a rule for `f` saw `f n` rather than `f (n |> co1)`, and failed to match
(the rule matcher checks the types of template variables). If f's
unfolding is active, f may then be inlined, and the rule is lost for
good. Now contOutArgs uses simplCloExpr, which includes the pending cast.
Almost no change in behaviour, except for the #27963 bug-fix.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
981e6bed by Simon Peyton Jones at 2026-11-20T17:45:08+00:00
Add splitThunkCpr
This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form
of "thunk splitting" for strict bindings that have CPR information.
See Note [Thunk splitting] in WorkWrap.hs
It catches a previously-unrecognised optimisation opportunity, and it's
only a few lines of code, but it's a bit of a corner case so I don't expect
a big impact in practice.
- - - - -
27 changed files:
- + changelog.d/T27962
- + changelog.d/T27963
- compiler/GHC/Core.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Opt/CprAnal.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/WorkWrap.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Core/Ppr.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/CoreToStg/Prep.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Id.hs
- compiler/GHC/Utils/Monad.hs
- testsuite/tests/simplCore/should_compile/T15445.stderr
- + testsuite/tests/simplCore/should_compile/T27962.hs
- + testsuite/tests/simplCore/should_compile/T27963.hs
- + testsuite/tests/simplCore/should_compile/T27963.stderr
- + testsuite/tests/simplCore/should_compile/T27965.hs
- + testsuite/tests/simplCore/should_compile/T27965a.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
changelog.d/T27962
=====================================
@@ -0,0 +1,7 @@
+section: compiler
+issues: #27962
+mrs: !16869
+synopsis:
+ Fix a Lint error when using `runRW#` and `coerce` together
+description:
+ Just an internal compiler bug, of long standing.
=====================================
changelog.d/T27963
=====================================
@@ -0,0 +1,7 @@
+section: compiler
+issues: #27963
+mrs: !16869
+synopsis:
+ Fix a rather obscure interaction of `coerce` and RULES
+description:
+ A `coerce` could prevent a RULE firing.
=====================================
compiler/GHC/Core.hs
=====================================
@@ -1494,6 +1494,157 @@ same way as above, otherwise the analysis would not be conservative wrt. the
lenient semantics (which includes the strict one). It is also much harder to
explain and maintain, as it turned out.
+Note [Core binder IdInfo invariants]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+We allow the following IdInfo on different sorts of Core binders.
+See the fields in GHC.Types.Id.Info.IdInfo:
+
+We classify binders into
+ * let-binders let x=rhs in body
+ * lambda binders (\x. e)
+ * case binders case e of x { ... }
+ * case-alternative binders case e of _ { K x y -> ... }
+
+ Let Lambda Case/case-alt
+ ---------------------------------------------
+ Occurrence Yes Yes Yes
+
+ InlinePrag Yes No No
+ Strictness (DmdSig) Yes No No
+ CPR info (CprSig) Yes No No
+ CAF Yes No No
+ Arity Yes No No
+ Call-arity Yes No No
+ Rules (RuleInfo) Yes No No
+ Unfolding Yes No(CBI1) evaldUnfolding only (CBI2)
+ Demand info Yes Yes Yes
+ One-shot No Yes No
+ ------------------------------------------------
+
+The predicate `GHC.Types.Id.lamBndrInfoOK` checks the Lambda and Case columns
+of this table (except one-shot info), and Core Lint applies it to every
+non-let binder (`lintIdBndr`).
+
+Generally, lambda binders have only IdInfo that describes their /use/
+(e.g. occ-info, demand info) not their /definition/. See esp (CBI1).
+
+Case and case-alternative binders are similar because again they lack a definition,
+and because they can /become/ a lambda binder when `mkDupableAlt` abstracts over them.
+
+Places that must take care to maintain these invariants (#27965):
+
+* Places that turn a let into a case, do so by calling `GHC.Core.Utils.mkCaseFromLet`,
+ which in turn calls `GHC.Types.Id.mkCaseBndrFromLetBndr`, or by calling the latter
+ directly:
+
+ - The desugarer, when desugaring a strict binding let !x = rhs in body,
+ generates case x of x { DEFAULT -> body }; the case binder must not inherit
+ x's IdInfo. See `GHC.HsToCore.Utils.seqVar`.
+
+ - `GHC.Core.Utils.bindNonRec` (used by `mkCoreLet`, and hence by the
+ Simplifier's `wrapFloats`), which turns let x = rhs in body into
+ case rhs of x { DEFAULT -> body } when `rhs` is unlifted and not
+ ok-for-speculation. Here `x` may well have a let-unfolding,
+ e.g. one made by `makeTrivial`.
+
+ - `GHC.Core.Opt.SpecConstr.mkSeqs`, which builds
+ case arg of arg' { DEFAULT -> rhs }
+ where `arg` may be an imported Id with an unfolding.
+
+ - `GHC.CoreToStg.Prep.wrapBinds` turns a let-binding into a case-binding.
+
+* The Simplifier, when it uses a StrictBind continuation for a strict
+ let-binding let x = rhs in body. When duplicating `StrictBind`,
+ `mkDupableContWithDmds` may turn `x` into the lambda binder of a join
+ point, so it uses `mkLamBndrFromLetBndr` to do so.
+ See (SB3) in Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration.
+
+
+(CBI1) Based on #17530 and #21496 we never attach unfoldings of any kind to lambda
+ binders, not even `evaldUnfolding`.
+
+ It's just too easy for the call site to change and invalidate the unfolding.
+ E.g. the caller of the lambda drops a seq (e.g. because the lambda is strict
+ in its binder) which in turn makes the OtherCon[] unfolding a lie. So
+ unfoldings on lambda binders can never really be trusted when on lambda
+ binders if there is the chance of the call site to change. So it's easiest to
+ just never attach any to lambda binders to begin with, as well as stripping
+ them off if we e.g. float out an expression while abstracting over some
+ arguments.
+
+(CBI2) See Note [Evaluated-ness on case binders]
+
+(CBI3) Note that /occurrences/ may have IdInfo that is not present on the binder.
+ Notably, consider case e of r { Just x -> ..r...; Nothing -> ...r... }
+ The occurrence of `r` in the (Just x) branch will have an unfolding `Just x`,
+ and similarly in the `Nothing` branch. But the /binder/ of `r` has only
+ `evaldUnfolding` See Note [Evaluated-ness on case binders]
+
+Note [Evaluated-ness on case binders]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The binding site of an Id in a case expression (case-binder or case alternative) may
+carry an `OtherCon []` (aka `evaldUnfolding`). meaning "this variable is certainly
+evaluated". Specifically:
+
+* Case binders are always evaluated. `GHC.Core.Opt.Simplify.Iteration.simplAlts` and
+ CorePrep add `evaldUnfolding` to every case binder.
+
+* Case-alternative binders for strict constructor fields
+ data T = MkT !Int Int
+ case x of MkT y z -> ...
+ `y` gets an evaldUnfolding.
+
+ This is done by `GHC.Core.Utils.dataConRepFSInstPat` (used by the interface-file loader,
+ among others), `GHC.Core.SimpleOpt`, the Simplifier (`adjustFieldsIdInfo`), and
+ worker/wrapper (for the argument and CPR result binders it makes;
+ see Note [Record evaluated-ness in worker/wrapper] in GHC.Core.Opt.WorkWrap.Utils).
+
+Why is this information on the /binder/? Within the Simplifier it is not
+needed: in each case alternative the Simplifier adds a more precise unfolding
+for the case binder (and evaluated-ness for strict-field binders) to its
+in-scope set, and refreshes every occurrence from that. But many other passes
+rebuild variable occurrences /from the binder/: substitution-based passes
+(SimpleOpt, Specialise, SpecConstr, CSE), SetLevels/FloatOut, the binder swap in
+the occurrence analyser, CoreTidy, and CorePrep. After such a pass, an
+occurrence knows that the variable is evaluated only if the binder does.
+
+That knowledge is used, mainly via `exprIsHNF`/`varIsHNF` (not by
+`exprOkForSpeculation`; see Note [exprOkForSpeculation and evaluated variables]
+in GHC.Core.Utils), by:
+
+* CorePrep: deciding whether a let-binding is a value (allocate directly) or
+ a thunk, e.g. `let x = Box y` where `y` is a strict field.
+ See Note [Pin evaluatedness on floats] in GHC.CoreToStg.Prep. CorePrep runs
+ just after CoreTidy, which propagates binder IdInfo to occurrences.
+
+* SetLevels/FloatOut: floating single-alternative cases out of loops, when the
+ scrutinee is evaluated; see Note [Floating single-alternative cases] in
+ GHC.Core.Opt.SetLevels. Also the call-by-value marks given to abstracted
+ variables (`GHC.Types.Id.transferPolyIdInfo`).
+
+* Worker/wrapper: `move_transit_vars` avoids an unboxed 1-tuple for a single
+ evaluated transit variable (test T18109); and the CPR result binders of the
+ wrapper remain evaluated (tests T13077a, #13027). The latter matters because
+ unboxed-tuple alternatives take a fast path in the Simplifier's
+ `adjustFieldsIdInfo`, and so get evaluated-ness only from the binder.
+
+* SimpleOpt: eliminating a case on an evaluated variable, and `mkFieldSeqFloats`.
+
+* Minor heuristic uses: FloatIn (the late FloatIn runs after FloatOut and CSE
+ with no Simplifier in between) and occurrences created by CSE or the binder
+ swap, until the next Simplifier run.
+
+Core Lint does /not/ depend on this information. Nor does anything in STG or
+tag inference.
+
+Removing the information from the binders would require these passes to track
+evaluated-ness in an environment instead (as SpecConstr already does with its
+ValueEnv), which they currently don't. So we allow an OtherCon unfolding (and
+only that) on case binders and case-alternative binders:
+see the table in Note [Core binder IdInfo invariants]
+
+
+
************************************************************************
* *
In/Out type synonyms
@@ -1843,16 +1994,6 @@ floatBinders (FloatTick {}) = []
The @Unfolding@ type is declared here to avoid numerous loops
-Note [Never put `OtherCon` unfoldings on lambda binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Based on #21496 we never attach unfoldings of any kind to lambda binders.
-It's just too easy for the call site to change and invalidate the unfolding.
-E.g. the caller of the lambda drops a seq (e.g. because the lambda is strict in it's binder)
-which in turn makes the OtherCon[] unfolding a lie.
-So unfoldings on lambda binders can never really be trusted when on lambda binders if there
-is the chance of the call site to change. So it's easiest to just never attach any
-to lambda binders to begin with, as well as stripping them off if we e.g. float out
-and expression while abstracting over some arguments.
-}
-- | Records the /unfolding/ of an identifier, which is approximately the form the
=====================================
compiler/GHC/Core/Lint.hs
=====================================
@@ -1858,6 +1858,15 @@ lintIdBndr top_lvl bind_site id thing_inside
hang (text "Lambda binder" <+> quotes (ppr id) <+> text "has an unfolding")
2 (ppr unf)
+ -- Check that lambda, case, and case-alternative binders have
+ -- only the IdInfo permitted by the table in
+ -- Note [Core binder IdInfo invariants] in GHC.Core
+ ; checkL (is_let_bind || lamBndrInfoOK id) $
+ hang (text "Non-let binder" <+> quotes (ppr id)
+ <+> text "has IdInfo that only a let-binder may have")
+ 2 (vcat [ text "Binding site:" <+> text (show_site bind_site)
+ , text "IdInfo:" <+> ppr (idInfo id) ])
+
; addLoc (IdTy id) (lintValueType id_ty)
; addInScopeId id thing_inside }
@@ -1869,6 +1878,12 @@ lintIdBndr top_lvl bind_site id thing_inside
LetBind -> True
_ -> False
+ show_site :: BindingSite -> String
+ show_site LambdaBind = "lambda"
+ show_site CaseBind = "case binder"
+ show_site CasePatBind = "case alternative"
+ show_site LetBind = "let"
+
{-
%************************************************************************
%* *
=====================================
compiler/GHC/Core/Opt/CprAnal.hs
=====================================
@@ -343,7 +343,7 @@ cprTransform env id args
-- Any local binding, except for data structure bindings
-- See Note [Efficient Top sigs in SigEnv]
| Just sig <- lookupSigEnv env id
- = applyCprTy (getCprSig sig) (length args)
+ = applyCprTy (cprSigType sig) (length args)
-- See Note [CPR for data structures]
| Just rhs <- cprDataStructureUnfolding_maybe id
= fst $ cprAnal env rhs
@@ -362,7 +362,7 @@ cprTransform env id args
= cprTransformDataConWork env con args
-- Imported function
| otherwise
- = applyCprTy (getCprSig (idCprSig id)) (length args)
+ = applyCprTy (cprSigType (idCprSig id)) (length args)
-- | Precise, hand-written CPR transformers for select Ids
cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType
@@ -870,27 +870,42 @@ Does f have the CPR property? Well, no.
However, if the strictness analyser has figured out (in a previous
iteration) that it's strict, then we DON'T need to forget the CPR info.
Instead we can retain the CPR info and do the thunk-splitting transform
-(see WorkWrap.splitThunk).
+(see Note [Thunk splitting] esp (B) CPR-led thunk splitting).
This made a big difference to PrelBase.modInt, which had something like
modInt = \ x -> let r = ... -> I# v in
...body strict in r...
-r's RHS isn't a value yet; but modInt returns r in various branches, so
-if r doesn't have the CPR property then neither does modInt
+r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so
+if `r` doesn't have the CPR property then neither does `modInt`
+
Another case I found in practice (in Complex.magnitude), looks like this:
- let k = if ... then I# a else I# b
- in ... body strict in k ....
+ let k* = if ... then I# a else I# b
+ in ... body strict in k ....
(For this example, it doesn't matter whether k is returned as part of
the overall result; but it does matter that k's RHS has the CPR property.)
+
Left to itself, the simplifier will make a join point thus:
- let $j k = ...body strict in k...
- if ... then $j (I# a) else $j (I# b)
+ let $j k = ...body strict in k...
+ if ... then $j (I# a) else $j (I# b)
+
With thunk-splitting, we get instead
- let $j x = let k = I#x in ...body strict in k...
- in if ... then $j a else $j b
+ let k* = case (if ... then I# a else I# b) of I# z -> I# z
+ in ... body strict in k ....
+Now the simplifier should pull out the `case` to give
+ case (if ... then I# a else I# b) of I# z ->
+ let k = I# z in ... body strict in k ...
+Now case-of-if will give
+ let $j z = let k = I# z in ...body strict in k... in
+ if ... then $j a else $j b
This is much better; there's a good chance the I# won't get allocated.
+TL'DR: During CPR analysis we want to give `k` the CPR property in `body`.
+
+What if the type involved has more than one constructor? E.g.
+ let k* = if ... then Just a else Just b
+ in ... body strict in k ....
+That is good too: see (TS5) in Note [Thunk splitting]
-But what about botCpr? Consider
+Finally, what about botCpr? Consider
lvl = error "boom"
fac -1 = lvl
fac 0 = 1
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -28,7 +28,7 @@ module GHC.Core.Opt.Simplify.Env (
SimplEnvIS, checkSimplEnvIS, pprBadSimplEnvIS,
-- * Substitution results
- SimplSR(..), substId, lookupRecBndr,
+ SimplClo(..), simplCloExpr, substId, lookupRecBndr,
-- * Simplifying 'Id' binders
simplNonRecBndr, simplNonRecJoinBndr, simplRecBndrs, simplRecJoinBndrs,
@@ -61,7 +61,7 @@ import GHC.Core.Opt.Simplify.Monad
import GHC.Core.Rules.Config ( RuleOpts(..) )
import GHC.Core
import GHC.Core.Utils
-import GHC.Core.Subst( substExprSC )
+import GHC.Core.Subst( substExpr )
import GHC.Core.Unfold
import GHC.Core.TyCo.Subst (emptyIdSubstEnv, mkSubst)
import GHC.Core.Multiplicity( Scaled(..), mkMultMul )
@@ -470,18 +470,26 @@ pprSimplEnv env
ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
| otherwise = ppr v
-type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
+type SimplIdSubst = IdEnv SimplClo -- IdId |--> OutExpr
-- See Note [Extending the IdSubstEnv] in GHC.Core.Subst
--- | A substitution result.
-data SimplSR
+-- | A "closure" used in the Simplifier. It is used
+-- * as the range of the substitution, 'SimplIdSubst'
+-- * as the argument in an 'ApplyToVal' continuation
+-- Roughly: either an (InExpr, StaticEnv) pair for an
+-- as-yet-unsimplified expression
+-- or an OutExpr, for an already-simplified one
+-- It's a bit like thunk: we may "evaluate" the SimplClo in a ApplyToVal
+-- and thereby transform it from `ContEx` to `DoneEx`
+-- This happens in the `ApplyToVal` case of `mkDupableContWithDmds`
+-- See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils
+data SimplClo
= DoneEx OutExpr JoinPointHood
-- If x :-> DoneEx e ja is in the SimplIdSubst
-- then replace occurrences of x by e
-- and ja = Just a <=> x is a join-point of arity a
-- See Note [Join arity in SimplIdSubst]
-
| DoneId OutId
-- If x :-> DoneId v is in the SimplIdSubst
-- then replace occurrences of x by v
@@ -490,11 +498,11 @@ data SimplSR
| ContEx SimplEnv
InExpr
- MOutCoercion -- See Note [The sc_cast field of ApplyToVal]
+ MOutCoercion -- See Note [The MOutCoercion field of ContEx]
-- If x :-> ContEx static_env e mco is in the SimplISubst
-- then replace occurrences of x by (subst static_env e) |> mco
-instance Outputable SimplSR where
+instance Outputable SimplClo where
ppr (DoneId v) = text "DoneId" <+> ppr v
ppr (DoneEx e mj) = text "DoneEx" <> pp_mj <+> ppr e
where
@@ -637,7 +645,7 @@ reSimplifying :: SimplEnv -> Bool
reSimplifying (SimplEnv { seInlineDepth = n }) = n>0
---------------------
-extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
+extendIdSubst :: SimplEnv -> Id -> SimplClo -> SimplEnv
extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
= assertPpr (isId var && not (isCoVar var)) (ppr var) $
env { seIdSubst = extendVarEnv subst var res }
@@ -1032,7 +1040,7 @@ So we want to look up the inner X.g_34 in the substitution, where we'll
find that it has been substituted by b. (Or conceivably cloned.)
-}
-substId :: SimplEnv -> InId -> SimplSR
+substId :: SimplEnv -> InId -> SimplClo
-- Returns DoneEx only on a non-Var expression
substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
= case lookupVarEnv ids v of -- Note [Global Ids in the substitution]
@@ -1364,15 +1372,18 @@ getTCvSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv
getFullSubst :: InScopeSet -> SimplEnv -> Subst
getFullSubst in_scope (SimplEnv { seIdSubst = id_env, seTvSubst = tv_env, seCvSubst = cv_env })
- = mkSubst in_scope (mapVarEnv to_expr id_env) tv_env cv_env
+ = mkSubst in_scope (mapVarEnv (simplCloExpr in_scope) id_env) tv_env cv_env
+
+simplCloExpr :: InScopeSet -> SimplClo -> OutExpr
+-- Turn a SimplClo into an OutExpr, by applying the substitution
+-- (if any) and the pending cast (if any)
+simplCloExpr _ (DoneEx e _) = e
+simplCloExpr _ (DoneId v) = Var v
+simplCloExpr in_scope (ContEx env e mco) = mkCastMCo e' mco
where
- to_expr :: SimplSR -> CoreExpr
- -- A tiresome impedence-matcher
- to_expr (DoneEx e _) = e
- to_expr (DoneId v) = Var v
- to_expr (ContEx env e mco) = mkCastMCo e' mco
- where
- e' = GHC.Core.Subst.substExprSC (getFullSubst in_scope env) e
+ e' = GHC.Core.Subst.substExpr (getFullSubst in_scope env) e
+ -- NB: we use substExpr, not substExprSC: we want to get the benefit of
+ -- knowing what is evaluated etc, via the in-scope set
substTy :: HasDebugCallStack => SimplEnv -> Type -> Type
substTy env ty = Type.substTy (getTCvSubst env) ty
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -285,8 +285,8 @@ simplRecOrTopPair :: SimplEnv
-> SimplM (SimplFloats, SimplEnv)
simplRecOrTopPair env bind_cxt old_bndr new_bndr rhs
- | Just env' <- preInlineUnconditionally env (bindContextLevel bind_cxt)
- old_bndr (UnSimplified env) rhs MRefl
+ | Just env' <- preInlineLetUnconditionally env (bindContextLevel bind_cxt)
+ old_bndr rhs env
= {-#SCC "simplRecOrTopPair-pre-inline-uncond" #-}
simplTrace "SimplBindr:inline-uncond1" (ppr old_bndr) $
do { tick (PreInlineUnconditionally old_bndr)
@@ -1226,17 +1226,8 @@ simplExprF1 env (Tick t expr) cont = {-#SCC "simplTick" #-} simplTick env t exp
simplExprF1 env (Coercion co) cont = {-#SCC "simplCoercionF" #-} simplCoercionF env co cont
simplExprF1 env (Cast body co) cont
- = do { co1 <- {-#SCC "simplCast-simplCoercion" #-}
- simplCoercion env co
-
- ; let cont1 = {-#SCC "simplCast-addCoerce" #-}
- if isReflCo co1
- then cont -- See Note [Optimising reflexivity]
- else pushCast env co1 cont
- -- True <=> co1 is optimised
-
- ; {-#SCC "simplCast-simplExprF" #-}
- simplExprF env body cont1 }
+ = do { co1 <- simplCoercion env co
+ ; simplExprF env body (pushCast env co1 cont) }
simplExprF1 env (App fun arg) cont
= {-#SCC "simplExprF1-App" #-} case arg of
@@ -1264,9 +1255,9 @@ simplExprF1 env (App fun arg) cont
-- observed the quadratic behavior, so this extra entanglement
-- seems not worthwhile.
simplExprF env fun $
- ApplyToVal { sc_arg = arg, sc_env = UnSimplified env
+ ApplyToVal { sc_arg = ContEx env arg MRefl, sc_dup = NoDup
, sc_hole_ty = substTy env (exprType fun)
- , sc_cast = MRefl, sc_cont = cont }
+ , sc_cont = cont }
simplExprF1 env expr@(Lam {}) cont
= {-#SCC "simplExprF1-Lam" #-}
@@ -1301,7 +1292,7 @@ simplExprF1 env (Let (NonRec bndr rhs) body) cont
do { ty' <- simplType env ty
; simplExprF (extendTvSubst env bndr ty') body cont }
- | Just env' <- preInlineUnconditionally env NotTopLevel bndr (UnSimplified env) rhs MRefl
+ | Just env' <- preInlineLetUnconditionally env NotTopLevel bndr rhs env
-- Because of the let-can-float invariant, it's ok to
-- inline freely, or to drop the binding if it is dead.
= do { simplTrace "SimplBindr:inline-uncond2" (ppr bndr) $
@@ -1637,9 +1628,8 @@ rebuild_go env expr cont
ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
-> rebuild_go env (App expr (Type ty)) cont
- ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_cont = cont, sc_hole_ty = fun_ty }
- -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = fun_ty }
+ -> do { arg' <- simplArg env Nothing fun_ty arg
; rebuild_go env (App expr arg') cont }
completeBindX :: SimplEnv
@@ -1653,6 +1643,7 @@ completeBindX env from_what bndr rhs body cont
| FromBeta arg_levity <- from_what
, needsCaseBindingL arg_levity rhs -- Enforcing the let-can-float-invariant
= do { (env1, bndr1) <- simplNonRecBndr env bndr -- Lambda binders don't have rules
+ -- See Note [Core binder IdInfo invariants] in GHC.Core
; (floats, expr') <- simplNonRecBody env1 from_what body cont
-- Do not float floats past the Case binder below
; let expr'' = wrapFloats floats expr'
@@ -1686,69 +1677,12 @@ completeBindX env from_what bndr rhs body cont
; let all_floats = rhs_floats `addFloats` bind_float `addFloats` body_floats
; return ( all_floats, body' ) }
-{-
-************************************************************************
+
+{- *********************************************************************
* *
-\subsection{Lambdas}
+ Arguments
* *
-************************************************************************
--}
-
-{- Note [Optimising reflexivity]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-It's important (for compiler performance) to get rid of reflexivity as soon
-as it appears. See #11735, #14737, and #15019.
-
-In particular, we want to behave well on
-
- * e |> co1 |> co2
- where the two happen to cancel out entirely. That is quite common;
- e.g. a newtype wrapping and unwrapping cancel.
-
-
- * (f |> co) @t1 @t2 ... @tn x1 .. xm
- Here we will use pushCoTyArg and pushCoValArg successively, which
- build up SelCo stacks. Silly to do that if co is reflexive.
-
-However, we don't want to call isReflexiveCo too much, because it uses
-type equality which is expensive on big types (#14737 comment:7).
-
-A good compromise (determined experimentally) seems to be to call
-isReflexiveCo
- * when composing casts, and
- * at the end
-
-In investigating this I saw missed opportunities for on-the-fly
-coercion shrinkage. See #15090.
-
-Note [Avoid re-simplifying coercions]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-In some benchmarks (with deeply nested cases) we successively push
-casts onto the SimplCont. We don't want to call the coercion optimiser
-on each successive composition -- that's at least quadratic. So:
-
-* The CastIt constructor in SimplCont has a `sc_opt :: Bool` flag to
- record whether the coercion optimiser has been applied to the coercion.
-
-* In `simplCast`, when we see (Cast e co), we simplify `co` to get
- an OutCoercion, and built a CastIt with sc_opt=True.
-
- Actually not quite: if we are simplifying the result of inlining an
- unfolding (seInlineDepth > 0), then instead of /optimising/ it again,
- just /substitute/ which is cheaper. See `simplCoercion`.
-
-* In `pushCast` if we combine this new coercion with an existing one,
- we build a CastIt for (co1 ; co2) with sc_opt=False.
-
-* When unpacking a CastIt, in `rebuild`, we optimise the (presumably
- composed) coercion if sc_opt=False; this is done by `optOutCoercion`.
-
-* When duplicating a continuation in `mkDupableContWithDmds`, before
- duplicating a CastIt, optimise the coercion. Otherwise we'll end up
- optimising it separately in the duplicate copies.
-
-* See also Note [The sc_cast field of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
--}
+********************************************************************* -}
simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
-> Maybe ArgInfo -- ^ Just <=> This arg `ai` occurs in an app
@@ -1756,15 +1690,12 @@ simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
-- how `f` uses `ai`, affecting the Stop
-- continuation passed to 'simplExprC'
-> OutType -- ^ Type of the function applied to this arg
- -> StaticEnv -> CoreExpr -- ^ Expression with its static envt
- -> MOutCoercion -- Wrap this around the result
+ -> SimplClo -- ^ The argument
-> SimplM OutExpr
-simplArg _ _ _ (Simplified {}) arg mco
- = -- See Note [Avoid repeated simplification]
- case mco of
- MRefl -> return arg -- Vastly common case
- MCo co -> return (mkCast arg co)
-simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
+-- See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils
+simplArg _ _ _ (DoneEx arg _) = return arg -- See Note [Avoid repeated simplification]
+simplArg _ _ _ (DoneId v) = return (Var v)
+simplArg env mb_arg_info fun_ty (ContEx arg_se arg mco)
= do { let arg_env' = arg_se `setInScopeFromE` env
arg_ty = funArgTy fun_ty
stop = case mb_arg_info of
@@ -1773,13 +1704,12 @@ simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
cont = addCastMCo mco stop
; simplExprC arg_env' arg cont }
-{-
-************************************************************************
+
+{- *********************************************************************
* *
-\subsection{Lambdas}
+ Lambdas
* *
-************************************************************************
--}
+********************************************************************* -}
simplNonRecBody :: SimplEnv -> FromWhat
-> InExpr -> SimplCont
@@ -1806,13 +1736,9 @@ simpl_lam env bndr body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
-- Value beta-reduction
-- This works for /coercion/ lambdas too
-simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
- , sc_cast = arg_mco, sc_cont = cont
+simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_cont = cont
, sc_hole_ty = fun_ty})
- | Just env' <- preInlineUnconditionally env NotTopLevel bndr arg_se arg arg_mco
- , not (needsCaseBindingL arg_levity arg)
- -- Ok to test arg::InExpr in needsCaseBinding because
- -- exprOkForSpeculation is stable under simplification
+ | Just env' <- preInlineBetaUnconditionally env arg_levity bndr arg
= simplTrace "SimplBindr:inline-uncond3"
(ppr bndr <+> text ":=" <+> ppr arg) $
do { tick (BetaReduction bndr)
@@ -1823,14 +1749,14 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
= do { tick (BetaReduction bndr)
; let from_what = FromBeta arg_levity
- ; case (arg_se, arg_mco) of
- (UnSimplified arg_env, MRefl)
+ ; case arg of
+ ContEx arg_env arg_expr MRefl
-- Optimisation: when there is no wrapping coercion use simplNonRecE
-- so that the clever floating out of let-bindings can take place
-- in this round of the Simplifier
- -> simplNonRecE env from_what bndr (arg, arg_env) body cont
+ -> simplNonRecE env from_what bndr (arg_expr, arg_env) body cont
- _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ _ -> do { arg' <- simplArg env Nothing fun_ty arg
; completeBindX env from_what bndr arg' body cont }
}
where
@@ -1869,7 +1795,7 @@ simplLamBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
-- could have a stable unfolding;
-- see Historical Note [Case binders and join points]
-- But now it is much simpler! We now only remove unfoldings.
--- See Note [Never put `OtherCon` unfoldings on lambda binders]
+-- See (CBI1) in Note [Core binder IdInfo invariants]
simplLamBndr env bndr = simplBinder env (zapIdUnfolding bndr)
simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
@@ -1902,8 +1828,8 @@ simplNonRecE :: HasDebugCallStack
-- Otherwise it may or may not satisfy it.
simplNonRecE env from_what bndr (rhs, rhs_se) body cont
- | assert (isId bndr && not (isJoinId bndr) ) $
- is_strict_bind
+ | assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True
+ , useStrictBind env from_what bndr rhs
= -- Evaluate RHS strictly
simplExprF (rhs_se `setInScopeFromE` env) rhs
(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
@@ -1917,17 +1843,6 @@ simplNonRecE env from_what bndr (rhs, rhs_se) body cont
; (floats2, expr') <- simplNonRecBody env3 from_what body cont
; return (floats1 `addFloats` floats2, expr') }
- where
- is_strict_bind = case from_what of
- FromBeta Unlifted -> True
- -- If we are coming from a beta-reduction (FromBeta) we must
- -- establish the let-can-float invariant, so go via StrictBind
- -- If not, the invariant holds already, and it's optional.
-
- -- (FromBeta Lifted) or FromLet: look at the demand info
- _ -> seCaseCase env && isStrUsedDmd (idDemandInfo bndr)
-
-
------------------
simplRecE :: SimplEnv
-> [(InId, InExpr)]
@@ -1948,6 +1863,48 @@ simplRecE env pairs body cont
; (floats2, expr') <- simplExprF env2 body cont
; return (floats1 `addFloats` floats2, expr') }
+
+useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool
+-- Can we use a StrictBind continuation for this let-binding?
+-- See (SB3) in Note [StrictBind]
+useStrictBind env from_what bndr rhs
+ -- If we are coming from a beta-reduction (FromBeta) we must
+ -- establish the let-can-float invariant, so we must go via StrictBind
+ -- If not, the invariant holds already, and it's optional.
+ | FromBeta Unlifted <- from_what
+ = True
+
+ -- Not if the demand is non-strict
+ | not (isStrUsedDmd dmd_info)
+ = False
+
+ -- Not if the RHS is ok-for-spec; no benefit
+ | exprOkForSpeculation rhs
+ = False
+
+ -- Not if case-of-case is off
+ -- See (SB1) in Note [StrictBind]
+ | not (seCaseCase env)
+ = False
+
+ | FromBeta Lifted <- from_what
+ = True
+
+ -- Not for things with RULES or INLINE or NOINLINE
+ -- or with a strictnes or CPR signature -- all things we might lose
+ -- See (SB3) in Note [StrictBind]
+ | isStableUnfolding (unfoldingInfo info)
+ || not (isEmptyRuleInfo (ruleInfo info))
+ || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
+ = False
+
+ | otherwise
+ = True
+
+ where
+ info = idInfo bndr
+ dmd_info = demandInfo info
+
{- Note [Dark corner with representation polymorphism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In `simplNonRecE`, the call to `needsCaseBinding` or to `isStrictId` will fail
@@ -2262,11 +2219,14 @@ simplOutId env fun cont
| fun `hasKey` runRWKey
, ApplyToTy { sc_cont = cont1 } <- cont
, ApplyToTy { sc_cont = cont2, sc_arg_ty = hole_ty } <- cont1
- , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_cast = arg_mco
- , sc_env = arg_se, sc_hole_ty = fun_ty } <- cont2
+ , ApplyToVal { sc_cont = cont3, sc_arg = arg_clo, sc_hole_ty = fun_ty } <- cont2
-- Do this even if (contIsStop cont), or if seCaseCase is off.
-- See Note [No eta-expansion in runRW#]
- = do { let (_saf,arg_env) = mkAltEnv env arg_se
+ = do { let (arg_env, arg, arg_mco)
+ = case arg_clo of
+ ContEx se e mco -> (se `setInScopeFromE` env, e, mco)
+ DoneEx e _ -> (env, e, MRefl)
+ DoneId v -> (env, Var v, MRefl)
overall_res_ty = contResultType cont3
-- hole_ty is the type of the current runRW# application
@@ -2281,23 +2241,32 @@ simplOutId env fun cont
-- * If we don't do this we get a beta-redex every time, so the
-- simplifier keeps doing more iterations.
-- * Even more important: see Note [No eta-expansion in runRW#]
+ --
+ -- But only if there is no pending cast on the argument (#27962);
+ -- if there is, the general case below deals with it properly
; arg' <- case arg of
- Lam s body -> do { (env', s') <- simplBinder arg_env s
- ; body' <- simplExprC env' body inner_cont
- ; return (Lam s' body') }
- -- Important: do not try to eta-expand this lambda
- -- See Note [No eta-expansion in runRW#]
+ Lam s body
+ | MRefl <- arg_mco
+ -> do { (env', s') <- simplBinder arg_env s
+ ; body' <- simplExprC env' body inner_cont
+ ; return (Lam s' body') }
+ -- Important: do not try to eta-expand this lambda
+ -- See Note [No eta-expansion in runRW#]
_ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
; let (m,_,_) = splitFunTy fun_ty
env' = arg_env `addNewInScopeIds` [s']
hole_ty = mkVisFunTy m realWorldStatePrimTy new_runrw_res_ty
cont' = pushCastMCo env' arg_mco $
- ApplyToVal { sc_arg = Var s', sc_cast = MRefl
- , sc_env = Simplified OkDup
+ ApplyToVal { sc_arg = DoneId s'
+ , sc_dup = dup
, sc_cont = inner_cont
, sc_hole_ty = hole_ty }
-- cont' applies to s', then K
+ -- The argument (Var s') is small, but inner_cont may not be
+ -- dupable; see (AV2) in Note [The argument of ApplyToVal]
+ dup | contIsDupable inner_cont = OkDup
+ | otherwise = NoDup
; body' <- simplExprC env' arg cont'
; return (Lam s' body') }
@@ -2364,13 +2333,12 @@ rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_c
---------- Simplify value arguments --------------------
rebuildCall env fun_info
- (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_hole_ty = fun_ty, sc_cont = cont })
- | UnSimplified arg_env <- arg_se
+ (ApplyToVal { sc_arg = arg, sc_hole_ty = fun_ty, sc_cont = cont })
+ | ContEx arg_env arg_expr arg_mco <- arg
, isStrictArgInfo fun_info -- Strict arguments
, seCaseCase env -- But only when case-of-case is on.
-- See Note [Case-of-case and full laziness]
- = simplExprF (arg_env `setInScopeFromE` env) arg $
+ = simplExprF (arg_env `setInScopeFromE` env) arg_expr $
addCastMCo arg_mco $
StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
, sc_dup = NoDup
@@ -2382,7 +2350,7 @@ rebuildCall env fun_info
-- There is no benefit (unlike in a let-binding), and we'd
-- have to be very careful about bogus strictness through
-- floating a demanded let.
- = do { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
+ = do { arg' <- simplArg env (Just fun_info) fun_ty arg
; rebuildCall env (addValArgTo fun_info arg' fun_ty) cont }
---------- No further useful info, revert to generic rebuild ------------
@@ -2530,11 +2498,11 @@ Then
* We simplify BIG before trying the rule; but the rule does not fire
(forcing this simplification is why we have the RULE in this example)
* We inline f = \x. g x, in `simpl_lam`
- * So if `simpl_lam` did preInlineUnconditionally we get (g BIG)
+ * So if `simpl_lam` did preInlineBetaUnconditionally we get (g BIG)
* Now if g has a RULE we'll simplify BIG again, and this whole thing can
iterate.
* However, if `f` did not have a RULE, so that BIG has /not/ already been
- simplified, we /want/ to do preInlineUnconditionally in simpl_lam.
+ simplified, we /want/ to do preInlineBetaUnconditionally in simpl_lam.
So we go to some effort to avoid repeatedly simplifying the same thing.
Suppose we are in the Plan (AFTER) case of rule application, for a rule
@@ -2543,8 +2511,9 @@ and a call
f (e1,e2)
Then:
-* The (sc_env :: StaticEnv) field of ApplyToVal records if the argument
- has been evaluated. See Note [StaticEnv] in GHC.Core.Opt.Simplify.Utils.
+* The (sc_arg :: SimplClo) field of ApplyToVal records if the argument
+ has been simplified: it is a DoneEx if so, and a ContEx if not.
+ See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
* The rule fires returning
RuleMatch { rm_rhs = (\x y. ...x..), rm_args = [ e1, e2 ] }
@@ -2557,17 +2526,17 @@ Then:
is the reason that `RuleMatch` separates the two.
* `fireRuleAFTER` uses `pushOutArgs` to push [ e1, e2 ] back onto the
- continuation with sc_env=Simplified NoDup.
+ continuation as (DoneEx e1) and (DoneEx e2).
* Beta-reduction fires (in `simpl_lam`) for the \x.
* Suppose `x` occurs many times. Then we want to behave like `let x=e1 in ..`,
- but we use `simplArg`, which in turn uses that `sc_env` flag to avoid
+ but we use `simplArg`, which in turn uses the DoneEx to avoid
re-simplifying `e1`.
* Suppose `x` occurs just once or not at all; then the call to
- `preInlineUnconditionally` in `simpl_lam` will fire, and extend the
- substitution with
+ `preInlineBetaUnconditionally` in `simpl_lam` will fire, and extend the
+ substitution with the very same SimplClo
x :-> DoneEx e1
* At the /occurrence/ of `x`, the function `simplInId` calls `simplOutExpr`
@@ -2774,8 +2743,7 @@ trySeqRules in_env scrut rhs cont
, ValArg { as_arg = no_cast_scrut
, as_dmd = seqDmd
, as_hole_ty = res3_ty } ]
- rule_cont = ApplyToVal { sc_env = UnSimplified in_env, sc_arg = rhs
- , sc_cast = MRefl
+ rule_cont = ApplyToVal { sc_arg = ContEx in_env rhs MRefl, sc_dup = NoDup
, sc_cont = cont, sc_hole_ty = res4_ty }
out_args = [Type rhs_rep, Type scrut_ty, Type rhs_ty, no_cast_scrut]
@@ -3420,6 +3388,7 @@ simplAlts (saf,env0) scrut case_bndr alts cont'
; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
env2 = modifyInScope env1 case_bndr2
-- See Note [Case binder evaluated-ness]
+ -- and Note [Evaluated-ness on case binders] in GHC.Core
fam_envs = seFamEnvs env0
; (alt_env', scrut', case_bndr') <- improveSeq fam_envs (saf,env2) scrut
@@ -3879,8 +3848,8 @@ knownCon env scrut dc dc_args case_bndr alt_bndrs rhs cont
return ( emptyFloats env
, extendIdSubst env case_bndr (DoneEx scrut NotJoinPoint))
- | Just env' <- preInlineUnconditionally env NotTopLevel case_bndr
- (UnSimplified env) con_app MRefl
+ | Just env' <- preInlineLetUnconditionally env NotTopLevel case_bndr
+ con_app env
= return (emptyFloats env', env')
| otherwise
@@ -4043,7 +4012,7 @@ mkDupableContWithDmds env dmds (TickIt t cont)
mkDupableContWithDmds env _
cont1@(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
, sc_env = se, sc_cont = cont})
--- See Note [Duplicating StrictBind]
+-- See (SB2) in Note [StrictBind]
-- K[ let x = <> in b ] --> join j x = K[ b ]
-- j <>
= do { let sb_env = case se of
@@ -4052,7 +4021,10 @@ mkDupableContWithDmds env _
-- The contIsDupable caught the OkDup case, and
-- we never build a StrictBind with a NoDup in it.
- ; (sb_env1, bndr') <- simplBinder sb_env bndr
+ -- A lambda binder may have only occurrence and demand info;
+ -- see (SB3) in Note [StrictBind]
+ ; let lam_bndr = mkLamBndrFromLetBndr bndr
+ ; (sb_env1, bndr') <- simplBinder sb_env lam_bndr
; (floats1, join_inner) <- simplNonRecBody sb_env1 from_what body cont
-- No need to use mkDupableCont before simplNonRecBody; we
-- use cont once here, and then share the result if necessary
@@ -4060,7 +4032,10 @@ mkDupableContWithDmds env _
; let join_body = wrapFloats floats1 join_inner
res_ty = contResultType cont
- ; mkDupableStrictBind env bndr' join_body res_ty }
+ -- bndr' is about to become a lambda binder, so it must have suitable
+ -- IdInfo; simplNonRecE ensures this. See Note [Core binder IdInfo invariants]
+ ; assertPpr (lamBndrInfoOK bndr') (ppr bndr' $$ ppr (idInfo bndr')) $
+ mkDupableStrictBind env bndr' join_body res_ty }
mkDupableContWithDmds env _
(StrictArg { sc_fun = fun, sc_cont = cont
@@ -4111,8 +4086,7 @@ mkDupableContWithDmds env dmds
, sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) }
mkDupableContWithDmds env dmds
- (ApplyToVal { sc_arg = arg, sc_env = se, sc_cast = arg_mco
- , sc_cont = cont, sc_hole_ty = hole_ty })
+ (ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = hole_ty })
= -- e.g. [...hole...] (...arg...)
-- ==>
-- let a = ...arg...
@@ -4124,12 +4098,12 @@ mkDupableContWithDmds env dmds
expectNonEmpty dmds
; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
; let env' = env `setInScopeFromF` floats1
- ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
+ ; arg' <- simplArg env' Nothing hole_ty arg
; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
; let all_floats = floats1 `addLetFloats` let_floats2
; return ( all_floats
- , ApplyToVal { sc_arg = triv_arg, sc_env = Simplified OkDup
- , sc_cast = MRefl, sc_cont = cont', sc_hole_ty = hole_ty }) }
+ , ApplyToVal { sc_arg = DoneEx triv_arg NotJoinPoint, sc_dup = OkDup
+ , sc_cont = cont', sc_hole_ty = hole_ty }) }
mkDupableContWithDmds env _
(Select { sc_bndr = case_bndr, sc_alts = alts, sc_env = se, sc_cont = cont })
@@ -4253,7 +4227,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
| otherwise = v
-- No lambda binder has an unfolding, but (currently) case binders can,
- -- so we must zap them here.
+ -- so we must zap them here. But case binders never have a pragma,
+ -- stable unfolding or RULES, so there is no need to zap those.
+ -- See Note [Core binder IdInfo invariants] in GHC.Core
join_rhs = mkLams (map zapIdUnfolding final_bndrs) rhs_with_seqs
; join_bndr <- newJoinId filtered_binders rhs_ty'
@@ -4267,9 +4243,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
, alt') }
-- See Note [Duplicated env]
-{-
-Note [Do not add unfoldings to join points at birth]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [Do not add unfoldings to join points at birth]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15360)
case (case (case (case ...))) of
@@ -4340,7 +4315,7 @@ The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
- StrictBind body Stop
+ StrictBind body Stop))
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
@@ -4479,7 +4454,7 @@ hack and bit us in multiple small and not-so-small ways
Consider this
case (case .. ) of c {
- I# c# -> ....c....
+ I# c# -> ....c.... }
If we make a join point with c but not c# we get
$j = \c -> ....c....
@@ -4569,7 +4544,7 @@ There are two ways to make it duplicable.
; False -> jump $j r2 }
Notice that Plan B is very like the way we handle strict bindings;
- see Note [Duplicating StrictBind]. And Plan B is exactly what we'd
+ see Note [StrictBind]. And Plan B is exactly what we'd
get if we turned use a case expression to evaluate the strict arg:
case (case x of { True -> r1; False -> r2 }) of
@@ -4642,23 +4617,80 @@ Note [Inline small things to avoid creating a thunk] in
Simplify.Utils. But if we do inline them, the entire process will
repeat -- back to exponential behaviour.
-So we are careful to keep the demand-info on a2 and a3. Then they'll
-be /strict/ let-bindings, which will be dealt with by StrictBind.
-That's why contIsDupableWithDmds is careful to propagage demand
-info to the auxiliary bindings it creates. See the Demand argument
-to makeTrivial.
-
-Note [Duplicating StrictBind]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We make a StrictBind duplicable in a very similar way to
-that for case expressions. After all,
- let x* = e in b is similar to case e of x -> b
-
-So we potentially make a join-point for the body, thus:
- let x = <> in b ==> join j x = b
- in j <>
-
-Just like StrictArg in fact -- and indeed they share code.
+So we are careful to keep the demand-info on a2 and a3. Then they'll be
+/strict/ let-bindings, which will be dealt with by `StrictBind` (see
+Note [StrictBind]). That's why `contIsDupableWithDmds` is careful to
+propagate demand info to the auxiliary bindings it creates. See the
+`Demand` argument to `makeTrivial`.
+
+Note [StrictBind]
+~~~~~~~~~~~~~~~~~
+We use StrictBind when we find
+ let x! = rhs in body
+where the `x` is definitely demanded in body. When this happens we can
+float out case-expressions etc from inside `rhs`; e.g.
+ let { x! = case a of (p,q) -> rhs } in b
+-->
+ case a of (p,q) -> let x! = rhs in b
+
+We simplify `rhs` with a StrictBind continuation that continues with
+`body`
+
+(SB1) We only use StrictBind when case-of-case is on:
+ see Note [Case-of-case and full laziness]
+
+(SB2) We make a StrictBind /duplicable/ in a very similar way to
+ that for case expressions. After all,
+ let x! = e in b is similar to case e of x -> b
+
+ So we potentially make a join-point for the body, thus:
+ let x = <> in b ==> join j x = b
+ in j <>
+
+ Just like StrictArg in fact -- and indeed they share code.
+
+(SB3) When we duplicate a StrictBind (SB2), the binder `x` becomes a lambda
+ binder, and so must satisfy `lamBndrInfoOK`; see Note [Core binder IdInfo
+ invariants] in GHC.Core. But a let-binder `x` usually has IdInfo that a
+ lambda binder may not have (an unfolding, arity, a demand signature...).
+
+ So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use
+ `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence
+ info and the demand info.
+
+ However, if the let-binder has
+ * RULES
+ * a stable unfolding
+ * a non-default inlining activation
+ we'd permanently lose these things if we lambda-bind it. For example:
+ let {-# NOINLINE x #-}
+ x! = case y of { ... }
+ in blah
+ If we make a join point j x = blah, we have nowhere convenient to put that
+ NOINLINE. Ditto INLINE or RULES. It's unusual. But it happens; one example
+ is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp
+ {-# NOINLINE res1 #-}
+ !res1 = unST fm s
+
+ So in these cases we simply don't use StrictBind -- see `useStrictBind`. We
+ could imagine instead imposing these conditions only when we /duplicate/ the
+ StrictBind, rather than when we /create/ it, but that would require a bigger
+ refactor.
+
+ What if a thunk has a strictness signature, or CPR information? We
+ could make `useStrictBind` say False in these cases too, but that turns
+ out to be a net loss: keeping a thunk is worse than losing the strictness
+ information. Example, where f1,f2 are both strict:
+ let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 }
+ in body
+ Keeping it as-is would use CBV for calls of `f` in `body`. But
+ allowing StrictBind would give us
+ join j f* = body
+ in case x of { True -> j f1; False -> j f2 }
+ which avoids the thunk. It's a trade-off.
+
+ For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap,
+ especially (B) CPR-led thunk splitting.
Note [Join point abstraction] Historical note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -12,7 +12,8 @@ module GHC.Core.Opt.Simplify.Utils (
tryEtaExpandRhs, wantEtaExpansion,
-- Inlining,
- preInlineUnconditionally, postInlineUnconditionally,
+ preInlineLetUnconditionally, preInlineBetaUnconditionally,
+ postInlineUnconditionally,
activeRule,
getUnfoldingInRuleMatch,
updModeForStableUnfoldings, updModeForRuleLHS, updModeForRuleRHS,
@@ -174,16 +175,14 @@ data SimplCont
-- Invariant: never an identity coercion
, sc_opt :: Bool -- True <=> sc_co has had optCoercion applied to it
-- See Note [Avoid re-simplifying coercions]
- -- in GHC.Core.Opt.Simplify.Iteration
, sc_cont :: SimplCont }
| ApplyToVal -- (ApplyToVal arg K)[e] = K[ e arg ]
{ sc_hole_ty :: OutType -- Type of the function, presumably (forall a. blah)
-- See Note [The hole type in ApplyToTy]
- , sc_env :: StaticEnv -- See Note [StaticEnv]
- , sc_arg :: CoreExpr -- The argument
- , sc_cast :: MOutCoercion -- Wrap this OutCoercion around the (simplified) argument
- -- See Note [The sc_cast field of ApplyToVal]
+ , sc_dup :: DupFlag -- See Note [The argument of ApplyToVal]
+ , sc_arg :: SimplClo -- The argument
+ -- Invariant: if sc_arg is a ContEx, then sc_dup = NoDup
, sc_cont :: SimplCont }
| ApplyToTy -- (ApplyToTy ty K)[e] = K[ e ty ]
@@ -201,10 +200,11 @@ data SimplCont
-- The two strict forms have no DupFlag, because we never duplicate them
| StrictBind -- (StrictBind x b K)[e] = let x = e in K[b]
-- or, equivalently, = K[ (\x.b) e ]
+ -- See Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration
{ sc_from :: FromWhat
, sc_env :: StaticEnv -- See Note [StaticEnv]
-- The sc_env in StrictBind is never (Simplified NoDup)
- , sc_bndr :: Id
+ , sc_bndr :: Id -- See (SB3) in Note [StrictBind]
, sc_body :: CoreExpr
, sc_cont :: SimplCont }
@@ -252,49 +252,85 @@ perhapsSubstTy (UnSimplified env) ty = substTy env ty
{- Note [StaticEnv]
~~~~~~~~~~~~~~~~~~~
-Consider ApplyToVal, which has
- sc_env :: StaticEnv
- sc_arg :: CoreExpr
-Initially, `sc_arg` is an un-simplified InExpr, and `sc_env` is (UnSimplified env),
-where `env` gives meaning to the free variables of `sc_arg`; in particular, `env`
-may have substitutions that must apply to the argument.
-
-But sometimes we simplify the argument, and in that case, `sc_arg` is an OutExpr,
-the simplified argument, and `sc_env` is (Simplified NoDup) or (Simplified OkDup).
-The former is the safe, conservative option, but in `mkDupableCont` we want to make
-the continuation duplicable, so we make the argument small and tag it with
-(Simplified OkDup).
-
-We later simplify the argument, e.g. in `simplArg`. Then
- * If sc_env is Simplified, it's a no-op
- * If sc_env is (UnSimplified arg_env) we simplify `sc_arg` with
- - Its captured envt `arg_env`
+Consider Select, which has
+ sc_env :: StaticEnv
+ sc_bndr :: Id
+ sc_alts :: [CoreAlt]
+Initially, `sc_bndr` and `sc_alts` are un-simplified InThings, and `sc_env` is
+(UnSimplified env), where `env` gives meaning to their free variables; in
+particular, `env` may have substitutions that must apply to them.
+
+But sometimes (notably in `mkDupableCont`) we simplify them, and in that case
+`sc_bndr` and `sc_alts` are OutThings, and `sc_env` is (Simplified dup).
+
+When we finally simplify the alternatives (see `mkAltEnv`)
+ * If sc_env is Simplified, there is nothing to do
+ * If sc_env is (UnSimplified alt_env) we simplify them with
+ - Their captured envt `alt_env`
- but overriding its InScopeSet with the larger one at the
simplification point.
Why override the InScopeSet? Example:
- (let y = ey in f) ex
- By the time we simplify ex, 'y' will be in scope.
- All this is done in `simplArg`.
+ case (let y = ey in f) of alts
+ By the time we simplify alts, 'y' will be in scope.
Note that:
* In the Simplified case there is no environment, because the substitution has
already been applied.
-* We say sc_arg :: CoreExpr, rather than sc_arg :: InExpr or sc_arg :: OutExpr,
- because whether it is InExpr or OutExpr depends on `sc_env`
+* We say sc_alts :: [CoreAlt], rather than [InAlt] or [OutAlt],
+ because whether they are InAlts or OutAlts depends on `sc_env`
+
+* Same deal for StrictBind, where the StaticEnv scopes over sc_bndr and sc_body.
-* Same deal for Select, and StrictBind, but the StaticEnv scopes over
- * sc_bndr and sc_alts (for Select)
- * sc_bndr and sc_body (for StrictBind)
+* ApplyToVal is similar, but simpler: it uses a SimplClo instead.
+ See Note [The argument of ApplyToVal].
-* Even though the InScopeSet of an (UnSimplified se) is overridden in `simplArg`,
- that InScopeSet is not irrelevant: it should include all the free vars of
- applying the substitution to the InExpr. Reason: contHoleType uses perhapsSubstTy
- to apply the substitution to the expression, and that (rightly) gives ASSERT
- failures if the InScopeSet isn't big enough.
+* Even though the InScopeSet of an (UnSimplified se) is overridden, that
+ InScopeSet is not irrelevant: it should include all the free vars of
+ applying the substitution to the InThing. Reason: contHoleType uses
+ perhapsSubstTy to apply the substitution to the binder, and that
+ (rightly) gives ASSERT failures if the InScopeSet isn't big enough.
(SE1) If dup = OkToDup, then continuation k is also ok-to-dup
+
+Note [The argument of ApplyToVal]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ApplyToVal has
+ sc_dup :: DupFlag
+ sc_arg :: SimplClo
+
+Initially, `sc_arg` is (ContEx env arg MRefl), where `arg` is the un-simplified
+InExpr, and `env` gives meaning to the free variables of `arg`; in particular,
+`env` may have substitutions that must apply to the argument.
+
+But sometimes we simplify the argument, and in that case, `sc_arg` is
+(DoneEx arg' NotJoinPoint), where `arg'` is the simplified argument.
+
+The `sc_dup` flag says whether the continuation can be duplicated. NoDup is
+the safe, conservative option, but in `mkDupableCont` we want to make the
+continuation duplicable, so we make the argument small (and hence a DoneEx)
+and set `sc_dup` to OkDup. Invariants:
+
+ (AV1) If `sc_arg` is a ContEx, then `sc_dup` is NoDup.
+
+ (AV2) If `sc_dup` is OkDup then `sc_cont` is also ok-to-dup; see (SE1)
+ in Note [StaticEnv].
+
+We later simplify the argument, in `simplArg`. Then
+ * If `sc_arg` is a DoneEx (or DoneId), it's a no-op
+ * If `sc_arg` is (ContEx arg_env arg mco) we simplify `arg` with
+ - Its captured envt `arg_env`
+ - but overriding its InScopeSet with the larger one at the
+ simplification point.
+ Why override the InScopeSet? Example:
+ (let y = ey in f) ex
+ By the time we simplify ex, 'y' will be in scope.
+ Then we wrap the cast `mco` around the result.
+ See Note [The MOutCoercion field of ContEx].
+
+Using a SimplClo for the argument means that it can be substituted for a lambda
+binder, in `preInlineBetaUnconditionally`, without further ado.
-}
instance Outputable DupFlag where
@@ -312,9 +348,9 @@ instance Outputable SimplCont where
= (text "TickIt" <+> ppr t) $$ ppr cont
ppr (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
= (text "ApplyToTy" <+> pprParendType ty) $$ ppr cont
- ppr (ApplyToVal { sc_arg = arg, sc_env = env, sc_cont = cont, sc_hole_ty = hole_ty })
- = (hang (text "ApplyToVal" <> braces (ppr env) <+> text "hole-ty:" <+> pprParendType hole_ty)
- 2 (pprParendExpr arg))
+ ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont, sc_hole_ty = hole_ty })
+ = (hang (text "ApplyToVal" <> braces (ppr dup) <+> text "hole-ty:" <+> pprParendType hole_ty)
+ 2 (ppr arg))
$$ ppr cont
ppr (StrictBind { sc_bndr = b, sc_cont = cont })
= (text "StrictBind" <+> ppr b) $$ ppr cont
@@ -433,8 +469,8 @@ pushOutArgs fun_ty (arg:args) cont
= ApplyToTy { sc_hole_ty = fun_ty, sc_arg_ty = ty
, sc_cont = pushOutArgs (piResultTy fun_ty ty) args cont }
| otherwise
- = ApplyToVal { sc_hole_ty = fun_ty, sc_cast = MRefl
- , sc_arg = arg, sc_env = Simplified NoDup
+ = ApplyToVal { sc_hole_ty = fun_ty
+ , sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
, sc_cont = pushOutArgs (funResultTy fun_ty) args cont}
pushArgSpecs :: [ArgSpec] -- In normal, forward order
@@ -445,7 +481,7 @@ pushArgSpec :: ArgSpec -> SimplCont -> SimplCont
pushArgSpec (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }) cont
= ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont }
pushArgSpec (ValArg { as_arg = arg, as_hole_ty = hole_ty }) cont
- = ApplyToVal { sc_arg = arg, sc_env = Simplified NoDup, sc_cast = MRefl
+ = ApplyToVal { sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
, sc_hole_ty = hole_ty, sc_cont = cont }
argSpecArg :: ArgSpec -> OutExpr
@@ -496,7 +532,12 @@ contIsStop _ = False
contIsDupable :: SimplCont -> Bool
contIsDupable (Stop {}) = True
contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k
-contIsDupable (ApplyToVal { sc_env = se }) = okToDupSE se -- See (SE1) in Note [StaticEnv]
+contIsDupable (ApplyToVal { sc_dup = dup, sc_arg = arg })
+ = assertPpr (not (okToDup dup && is_cont_ex arg)) (ppr arg) $
+ okToDup dup -- See (AV1,AV2) in Note [The argument of ApplyToVal]
+ where
+ is_cont_ex (ContEx {}) = True
+ is_cont_ex _ = False
contIsDupable (Select { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictBind { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictArg { sc_dup = dup }) = okToDup dup -- ...ditto...
@@ -605,8 +646,8 @@ contArgs env cont
lone (CastIt {}) = False -- stops it being "lone"
lone _ = True
- go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k })
- = go (interestingArg env se arg : args) k
+ go args (ApplyToVal { sc_arg = arg, sc_cont = k })
+ = go (interestingArg env arg : args) k
go args (ApplyToTy { sc_cont = k }) = go args k
go args (CastIt { sc_cont = k }) = go args k
go args k = (False, reverse args, k)
@@ -621,15 +662,13 @@ contOutArgs env cont
go (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
= Type ty : go cont
- go (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = cont })
- = case se of
- Simplified {} -> arg : go cont
- UnSimplified env -> GHC.Core.Subst.substExpr (getFullSubst in_scope env) arg : go cont
- -- Make sure we apply the static environment `sc_env` as a substitution
+ go (ApplyToVal { sc_arg = arg, sc_cont = cont })
+ = simplCloExpr in_scope arg : go cont
+ -- Make sure we apply the static environment of a ContEx as a substitution
-- to get an OutExpr. See (BF1) in Note [tryRules: plan (BEFORE)]
-- in GHC.Core.Opt.Simplify.Iteration
- -- NB: we use substExpr, not substExprSC: we want to get the benefit of
- -- knowing what is evaluated etc, via the in-scope set
+ -- simplCloExpr also wraps the pending cast (if any) around the argument;
+ -- omitting it can make a rule fail to match (#27963)
-- No more arguments
go _ = []
@@ -826,23 +865,86 @@ make use of the strictness info for the function.
* *
********************************************************************* -}
-{- Note [The sc_cast field of ApplyToVal]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [The MOutCoercion field of ContEx]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the `ApplyToVal` case of `pushCast` we want to push an `OutCoercion` into the
-argument. But the argument may or may not have been simplified (see Note [StaticEnv])
-so we definitely can't just wrap the cast around the argument. Instead we store it
-in the `sc_cast` field -- this is the whole reason for the `sc_cast` field.
+argument. But the argument may or may not have been simplified (see Note [The
+argument of ApplyToVal]):
+
+* If it has been simplified, it is (DoneEx arg' _), and we can simply wrap the
+ cast around `arg'`.
+
+* If it has not, it is (ContEx env arg mco), and we definitely can't just wrap
+ the (Out)cast around the InExpr `arg`. Instead we compose it with `mco` --
+ this is the whole reason for the MOutCoercion field of `ContEx`.
+
+All this is done by `mkCloCastMCo`.
We deal with that pending cast mainly in `simplArg`.
But we /also/ sometimes want to substitute that argument for a lambda-binder, in
-`preInlineUnconditionally`. So we also have to put that pending cast into
-`ContEx`; hence the MOutCoercion field of `ContEx`. Then we deal with it
-appropriately when /applying/ the substitution in `simplInId`.
+`preInlineBetaUnconditionally`; and since the substitution maps an Id to a SimplClo,
+the pending cast comes along for free. Then we deal with it appropriately when
+/applying/ the substitution in `simplInId`.
+
+Note [Optimising reflexivity]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+It's important (for compiler performance) to get rid of reflexivity as soon
+as it appears. See #11735, #14737, and #15019.
+
+In particular, we want to behave well on
+
+ * e |> co1 |> co2
+ where the two happen to cancel out entirely. That is quite common;
+ e.g. a newtype wrapping and unwrapping cancel.
+
+
+ * (f |> co) @t1 @t2 ... @tn x1 .. xm
+ Here we will use pushCoTyArg and pushCoValArg successively, which
+ build up SelCo stacks. Silly to do that if co is reflexive.
+
+However, we don't want to call isReflexiveCo too much, because it uses
+type equality which is expensive on big types (#14737 comment:7).
+
+A good compromise (determined experimentally) seems to be to call
+isReflexiveCo
+ * when composing casts, and
+ * at the end
+
+In investigating this I saw missed opportunities for on-the-fly
+coercion shrinkage. See #15090.
+
+Note [Avoid re-simplifying coercions]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+In some benchmarks (with deeply nested cases) we successively push
+casts onto the SimplCont. We don't want to call the coercion optimiser
+on each successive composition -- that's at least quadratic. So:
+
+* The CastIt constructor in SimplCont has a `sc_opt :: Bool` flag to
+ record whether the coercion optimiser has been applied to the coercion.
+
+* In `simplCast`, when we see (Cast e co), we simplify `co` to get
+ an OutCoercion, and built a CastIt with sc_opt=True.
+
+ Actually not quite: if we are simplifying the result of inlining an
+ unfolding (seInlineDepth > 0), then instead of /optimising/ it again,
+ just /substitute/ which is cheaper. See `simplCoercion`.
+
+* In `pushCast` if we combine this new coercion with an existing one,
+ we build a CastIt for (co1 ; co2) with sc_opt=False.
+
+* When unpacking a CastIt, in `rebuild`, we optimise the (presumably
+ composed) coercion if sc_opt=False; this is done by `optOutCoercion`.
+
+* When duplicating a continuation in `mkDupableContWithDmds`, before
+ duplicating a CastIt, optimise the coercion. Otherwise we'll end up
+ optimising it separately in the duplicate copies.
+
+* See also Note [The MOutCoercion field of ContEx]
-}
optOutCoercion :: SimplEnvIS -> OutCoercion -> Bool -> OutCoercion
--- See Note [Avoid re-simplifying coercions] in GHC.Core.Opt.Simplify.Iteration
+-- See Note [Avoid re-simplifying coercions]
optOutCoercion env co already_optimised
| already_optimised = co -- Ditto
| otherwise = optCoercion opts empty_subst co
@@ -862,16 +964,17 @@ pushCastMCo env (MCo co) cont = pushCast env co cont
pushCast :: SimplEnv -> OutCoercion -> SimplCont -> SimplCont
pushCast env co cont
- = go co True cont
+ | isReflCo co = cont -- See Note [Optimising reflexivity]
+ | otherwise = go co True cont
where
-- ToDo: pushCast Refl (ApplylToVal arg1 (ApplyToVal arg2 ...))
-- will do lots of unnecessary work.
go :: OutCoercion -> Bool -> SimplCont -> SimplCont
- go co1 _ (CastIt { sc_co = co2, sc_cont = cont }) -- See Note [Optimising reflexivity] in GHC.Core.Opt.Simplify.Iteration
+ go co1 _ (CastIt { sc_co = co2, sc_cont = cont }) -- See Note [Optimising reflexivity]
= go (mkTransCo co1 co2) False cont
-- False: (mkTransCo co1 co2) is not fully optimised
- -- See Note [Avoid re-simplifying coercions] in GHC.Core.Opt.Simplify.Iteration
+ -- See Note [Avoid re-simplifying coercions]
go co co_is_opt (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail })
| Just (tyL, arg_ty', m_co') <- pushCoTyArg co arg_ty
@@ -886,26 +989,22 @@ pushCast env co cont
-- where co :: (s1->s2) ~ (t1->t2)
-- co1 :: t1 ~ s1
-- co2 :: s2 ~ t2
- go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_env = arg_se
- , sc_cast = arg_mco, sc_cont = tail })
+ go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_cont = tail })
| not co_is_opt
= -- pushCoValArg duplicates the coercion, so optimise first
go (optOutCoercion (zapSubstEnv env) co co_is_opt) True cont
| Just (tyL, m_co1, m_co2) <- pushCoValArg co
= {-#SCC "addCoerce-pushCoValArg" #-}
- -- Dealing with m_co1 is the entire reason for the sc_cast field
- -- of ApplyToVal; see Note [The sc_cast field of ApplyToVal]
- ApplyToVal { sc_arg = arg
- , sc_env = arg_se
- , sc_cast = arg_mco `mkTransMCo` m_co1
- , sc_cont = go_mco m_co2 True tail
- , sc_hole_ty = tyL }
+ -- See Note [The MOutCoercion field of ContEx]
+ cont { sc_arg = mkCloCastMCo arg m_co1
+ , sc_cont = go_mco m_co2 True tail
+ , sc_hole_ty = tyL }
go co co_is_opt cont
| isReflCo co = cont -- Having this at the end makes a huge
-- difference in T12227, for some reason
- -- See Note [Optimising reflexivity] in GHC.Core.Opt.Simplify.Iteration
+ -- See Note [Optimising reflexivity]
| otherwise = CastIt { sc_co = co, sc_opt = co_is_opt, sc_cont = cont }
-- If the first parameter is MRefl, then simplifying revealed a
@@ -914,6 +1013,13 @@ pushCast env co cont
go_mco MRefl _ cont = cont
go_mco (MCo co) opt cont = go co opt cont
+mkCloCastMCo :: SimplClo -> MOutCoercion -> SimplClo
+-- See Note [The MOutCoercion field of ContEx]
+mkCloCastMCo clo MRefl = clo
+mkCloCastMCo (DoneId v) (MCo co) = DoneEx (mkCast (Var v) co) NotJoinPoint
+mkCloCastMCo (DoneEx e _) (MCo co) = DoneEx (mkCast e co) NotJoinPoint
+mkCloCastMCo (ContEx se e mco) (MCo co) = ContEx se e (mco `mkTransMCo` MCo co)
+
{-
************************************************************************
@@ -1227,19 +1333,17 @@ Wrinkles:
-}
-interestingArg :: SimplEnv -> StaticEnv -> CoreExpr -> ArgSummary
+interestingArg :: SimplEnv -> SimplClo -> ArgSummary
-- See Note [Interesting arguments]
-interestingArg env se e
- = case se of
- Simplified {} -> go env 0 e
- UnSimplified static_env -> go (static_env `setInScopeFromE` env) 0 e
+interestingArg env clo
+ = go_clo env 0 clo
where
+ go_clo _ n (DoneId v) = go_var n v
+ go_clo env n (DoneEx e _) = go (zapSubstEnv env) n e
+ go_clo env n (ContEx se e _) = go (se `setInScopeFromE` env) n e
+
-- n is # value args to which the expression is applied
- go env n (Var v)
- = case substId env v of
- DoneId v' -> go_var n v'
- DoneEx e _ -> go (zapSubstEnv env) n e
- ContEx se e _mco -> go (se `setInScopeFromE` env) n e
+ go env n (Var v) = go_clo env n (substId env v)
go _ _ (Lit l)
| isLitRubbish l = NonTrivArg -- See (IA3) in Note [Interesting arguments]
@@ -1738,15 +1842,15 @@ is a term (not a coercion) so we can't necessarily inline the latter in
the former.
-}
-preInlineUnconditionally
+preInlineLetUnconditionally
:: SimplEnv -> TopLevelFlag -> InId
- -> StaticEnv -> CoreExpr -> MOutCoercion -- The argument
+ -> InExpr -> SimplEnv -- These two go together
-> Maybe SimplEnv -- Returned env has extended substitution
-- Precondition: rhs satisfies the let-can-float invariant
-- See Note [Core let-can-float invariant] in GHC.Core
-- Reason: we don't want to inline single uses, or discard dead bindings,
-- for unlifted, side-effect-ful bindings
-preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
+preInlineLetUnconditionally env top_lvl bndr rhs rhs_env
| not pre_inline_unconditionally = Nothing
| not active = Nothing
| isTopLevel top_lvl && isDeadEndId bndr = Nothing -- Note [Top-level bottoming Ids]
@@ -1758,26 +1862,15 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- See Note [Stable unfoldings and preInlineUnconditionally]
| not (isInlinePragma inline_prag)
- , Just inl <- maybeUnfoldingTemplate unf = assertPpr (isReflMCo rhs_mco) (ppr bndr) $
- Just $! (extend_subst_with inl)
+ , Just inl <- maybeUnfoldingTemplate unf = Just $! (extend_subst_with inl)
| otherwise = Nothing
where
unf = idUnfolding bndr
- -- If the rhs is /not/ already simplified, extend the envt with ContEx, which captures
- -- the the lexical environment for us to restore in `simplInId`.
- -- If the rhs /is/ already simplified, then extend the envt with DoneEx;
- -- That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
- -- the RHS.
- -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
- extend_subst_with inl_rhs
- = extendIdSubst env bndr $!
- case rhs_se of
- Simplified _ -> case rhs_mco of
- MRefl -> DoneEx inl_rhs NotJoinPoint -- Common case
- MCo co -> DoneEx (mkCast inl_rhs co) NotJoinPoint
- UnSimplified rhs_env -> ContEx rhs_env inl_rhs rhs_mco
+ -- The rhs is not yet simplified, so extend the envt with ContEx, which
+ -- captures the lexical environment for us to restore in `simplInId`.
+ extend_subst_with inl_rhs = extendIdSubst env bndr $! ContEx rhs_env inl_rhs MRefl
one_occ IAmDead = True -- Happens in ((\x.1) v)
one_occ OneOcc{ occ_n_br = 1
@@ -1793,39 +1886,6 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- See Note [pre/postInlineUnconditionally in gentle mode]
inline_prag = idInlinePragma bndr
--- Be very careful before inlining inside a lambda, because (a) we must not
--- invalidate occurrence information, and (b) we want to avoid pushing a
--- single allocation (here) into multiple allocations (inside lambda).
--- Inlining a *function* with a single *saturated* call would be ok, mind you.
--- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
--- where
--- is_cheap = exprIsCheap rhs
--- ok = is_cheap && int_cxt
-
- -- int_cxt The context isn't totally boring
- -- E.g. let f = \ab.BIG in \y. map f xs
- -- Don't want to substitute for f, because then we allocate
- -- its closure every time the \y is called
- -- But: let f = \ab.BIG in \y. map (f y) xs
- -- Now we do want to substitute for f, even though it's not
- -- saturated, because we're going to allocate a closure for
- -- (f y) every time round the loop anyhow.
-
- -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
- -- so substituting rhs inside a lambda doesn't change the occ info.
- -- Sadly, not quite the same as exprIsHNF.
- canInlineInLam (Lit _) = True
- canInlineInLam (Cast e _) = canInlineInLam e
- canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
- canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
- canInlineInLam (Var v) = case idOccInfo v of
- OneOcc { occ_in_lam = IsInsideLam } -> True
- ManyOccs {} -> True
- _ -> False
- canInlineInLam _ = False
- -- not ticks. Counting ticks cannot be duplicated, and non-counting
- -- ticks around a Lam will disappear anyway.
-
early_phase =
case sePhase env of
SimplPhase p -> p /= FinalPhase
@@ -1856,6 +1916,97 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- (Nor can we check for `exprIsExpandable rhs`, because that needs to look
-- at the non-existent unfolding for the `I# 2#` which is also floated out.)
+preInlineBetaUnconditionally
+ :: SimplEnv -> Levity -> InId
+ -> SimplClo -- The argument
+ -> Maybe SimplEnv -- Returned env has extended substitution
+-- Like preInlineLetUnconditionally, but for a beta-redex (\bndr. body) arg
+-- The argument may or may not be already simplified (DoneEx or ContEx)
+--
+-- The binder is a lambda binder and so lacks most IdInfo;
+-- see Note [Core binder IdInfo invariants]
+--
+-- Compared to preInlineLetUnconditionally we omit some checks:
+-- * The binder is never top-level, so no need for the
+-- Note [Top-level bottoming Ids] check, nor for `early_phase`
+-- * A lambda binder is never a join point, so no need for the
+-- Note [Do not inline exit join points] check
+-- * A lambda binder never has an inline pragma, a stable unfolding, or RULES
+-- (see `lamBndrInfoOK`), so no need to check activation, nor for
+-- Note [Stable unfoldings and preInlineUnconditionally]
+--
+-- And we add one extra one
+-- * Check the let-can-float invariant, and don't inline if not
+
+preInlineBetaUnconditionally env levity bndr arg
+ | assertPpr (lamBndrInfoOK bndr) (ppr bndr) $
+ not pre_inline_unconditionally = Nothing
+ | isCoVar bndr = Nothing -- Note [Do not inline CoVars unconditionally]
+ | not (one_occ (idOccInfo bndr)) = Nothing
+ | needs_case_binding = Nothing -- Enforce the let-can-float invariant
+ | otherwise = Just $! extendIdSubst env bndr arg
+ -- If the arg is not yet simplified, it is a ContEx, which captures the
+ -- lexical environment for us to restore in `simplInId`.
+ -- If the arg is already simplified, then it is a DoneEx;
+ -- That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
+ -- the arg.
+ -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
+ where
+ pre_inline_unconditionally = sePreInline env
+
+ needs_case_binding = needsCaseBindingL levity rhs
+ -- Ok to test an InExpr or OutExpr in needsCaseBindingL because
+ -- exprOkForSpeculation is stable under simplification
+
+ rhs :: CoreExpr -- Can be InExpr or OutExpr, but here it does not matter
+ rhs = case arg of
+ ContEx _ e _ -> e -- InExpr
+ DoneEx e _ -> e -- OutExpr
+ DoneId v -> Var v -- OutExpr
+
+ one_occ IAmDead = True -- Happens in ((\x.1) v)
+ one_occ OneOcc{ occ_n_br = 1
+ , occ_in_lam = NotInsideLam } = True
+ one_occ OneOcc{ occ_n_br = 1
+ , occ_in_lam = IsInsideLam
+ , occ_int_cxt = IsInteresting } = canInlineInLam rhs
+ one_occ _ = False
+
+
+canInlineInLam :: CoreExpr -> Bool
+-- Be very careful before inlining inside a lambda, because (a) we must not
+-- invalidate occurrence information, and (b) we want to avoid pushing a
+-- single allocation (here) into multiple allocations (inside lambda).
+-- Inlining a *function* with a single *saturated* call would be ok, mind you.
+-- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
+-- where
+-- is_cheap = exprIsCheap rhs
+-- ok = is_cheap && int_cxt
+
+ -- int_cxt The context isn't totally boring
+ -- E.g. let f = \ab.BIG in \y. map f xs
+ -- Don't want to substitute for f, because then we allocate
+ -- its closure every time the \y is called
+ -- But: let f = \ab.BIG in \y. map (f y) xs
+ -- Now we do want to substitute for f, even though it's not
+ -- saturated, because we're going to allocate a closure for
+ -- (f y) every time round the loop anyhow.
+
+ -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
+ -- so substituting rhs inside a lambda doesn't change the occ info.
+ -- Sadly, not quite the same as exprIsHNF.
+canInlineInLam (Lit _) = True
+canInlineInLam (Cast e _) = canInlineInLam e
+canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
+canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
+canInlineInLam (Var v) = case idOccInfo v of
+ OneOcc { occ_in_lam = IsInsideLam } -> True
+ ManyOccs {} -> True
+ _ -> False
+canInlineInLam _ = False
+ -- not ticks. Counting ticks cannot be duplicated, and non-counting
+ -- ticks around a Lam will disappear anyway.
+
{-
************************************************************************
* *
=====================================
compiler/GHC/Core/Opt/SpecConstr.hs
=====================================
@@ -2068,7 +2068,12 @@ mkSeqs seqees res_ty rhs =
-- Argument representing strict field and it's worth passing via cbv
| wantCbvForId arg_id
= Case (Var arg_id)
- (localiseId arg_id) -- See (SCF1) in Note [SpecConstr and strict fields]
+ (mkCaseBndrFromLetBndr arg_id)
+ -- mkCaseBndrFromLetBndr: arg_id may have IdInfo (e.g. an unfolding,
+ -- if it is a global) that a case binder must not have;
+ -- see Note [Core binder IdInfo invariants] in GHC.Core
+ -- Note that mkCaseBndrFromLetBndr also does localiseId:
+ -- see (SCF1) in Note [SpecConstr and strict fields]
res_ty
([Alt DEFAULT [] rhs])
=====================================
compiler/GHC/Core/Opt/WorkWrap.hs
=====================================
@@ -598,13 +598,20 @@ tryWW ww_opts is_rec fn_id rhs
= splitFun ww_opts new_fn_id rhs
-- See Note [Thunk splitting]
- | isNonRec is_rec, is_thunk
- = splitThunk ww_opts is_rec new_fn_id rhs
+ | isNonRec is_rec -- See (TS4)
+ , isStrUsedDmd (demandInfo fn_info) -- See (TS4)
+ , is_thunk -- All join points go via splitFun
+ = do { -- Try strictness then CPR; see (TS5)
+ rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM`
+ splitThunkCpr ww_opts new_fn_id rhs `orElseM`
+ return rhs
+ ; return [ (new_fn_id, rhs') ] }
| otherwise
= return [ (new_fn_id, rhs) ]
where
+ is_join = isJoinId fn_id
fn_info = idInfo fn_id
(wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info)
new_fn_id = zap_join_cpr $ zap_usage fn_id
@@ -613,14 +620,13 @@ tryWW ww_opts is_rec fn_id rhs
-- See Note [Zapping DmdEnv after Demand Analyzer] and
-- See Note [Zapping Used Once info in WorkWrap]
- zap_join_cpr id
- | isJoinId id = id `setIdCprSig` topCprSig
- | otherwise = id
+ zap_join_cpr id | is_join = id `setIdCprSig` topCprSig
+ | otherwise = id
-- See Note [Don't w/w join points for CPR]
- is_fun = notNull wrap_dmds || isJoinId fn_id
- is_thunk = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id)
- && not (isUnliftedType (idType fn_id))
+ is_fun = notNull wrap_dmds || is_join
+ is_thunk = not (exprIsHNF rhs)
+ && not (isUnliftedType (idType fn_id))
{-
Note [Zapping DmdEnv after Demand Analyzer]
@@ -806,7 +812,7 @@ splitFun ww_opts fn_id rhs
(wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info)
- cpr_ty = getCprSig (cprSigInfo fn_info)
+ cpr_ty = cprSigType (cprSigInfo fn_info)
-- Arity of the CPR sig should match idArity when it's not a join point.
-- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal
cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info)
@@ -957,114 +963,140 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>]
Note [Thunk splitting]
~~~~~~~~~~~~~~~~~~~~~~
-Suppose x is used strictly; never mind whether it has the CPR
-property. I'll use a '*' to mean "x* is demanded strictly".
-
- let
- x* = x-rhs
+The worker/wrapper split mainly affects let-bound /functions/. But we can also use
+demand and CPR information to improve let-bound /thunks/. Specifically:
+
+* (A) Demand-led thunk splitting:
+ If a thunk is demanded strictly, perhaps nestedly, we can turn it into a
+ case, perhaps nestedly. For example
+ let x :: (Int, Int)
+ {- Dmd = SP(S,L) -}
+ x = rhs
+ in body
+ We would ultimately like to get
+ case rhs of x { (a,b) ->
+ case a of { I# a# ->
+ body
+
+ This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x`
+ and `a` inside `body`.
+
+* (B) CPR-led thunk splitting:
+ If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly
+ at top level, we can again generate a case
+ let x :: (Int, Int)
+ {- Dmd = S, Cpr = (_, I# _) -}
+ x = rhs
+ in body
+ The CPR info says that if `x` is evaluated (which it is), it'll return a pair,
+ whose second component can very cheaply be evaluated to a (I# b#). We would
+ like to end up with
+ case rhs of x { (a,b) ->
+ case b of { I# b# ->
+ body
+ which is good for the same reasons as before. See (TS3) for an example.
+
+Implementation
+~~~~~~~~~~~~~~
+The worker/wrapper pass does not generate these nested case expressions directly.
+Instead it generates a regular let-binding but, since the binder is marked as
+strict, any `case` expressions in the RHS will float out. Specifically:
+
+(TS1) For (A), `splitThunkStr` generates the binding
+ let x* = case rhs of { (a,b) ->
+ case a of { I# a# ->
+ (I# a, b)
+ Now when the Simplifier floats the `case` expressions out, we get
+ case rhs of { (a,b) ->
+ case a of { I# a# ->
+ let x = (I# a, b)
in body
+ which is equivalent to the expression in (A) above.
-splitThunk transforms like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> I# a }
- in body
+ Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function
+ argument w/w splitting function, to do the unpacking. This automatically
+ deals with nested strictness.
-This is a little strange: we are re-using the same `x` in the RHS; and
-the RHS takes `x` apart and reboxes it. But because the outer 'let' is
-strict, and the inner let mentions `x` only once, the simplifier
-transform it to
- case x-rhs of
- I# a -> let x* = I# a
- in body
-
-That is good: in `body` we know the form of `x`, which
- * gives the CPR property, and
- * allows case-of-case to happen on x
-
-Notes
-* I tried transforming like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> x }
- in body
- where I return `x` itself, rather than reboxing it. But this
- turned out to cause some regressions, which I never fully
- investigated.
-
-* Suppose x-rhs is itself a case:
- x-rhs = case e of { T -> I# e1; F -> I# e2 }
- Then we'll get
- join j a = let x* = I# a in body
- in case e of { T -> j e1; F -> j e2 }
- which is good (no boxing). But in the original, unsplit program
- we would transform
- let x* = case e of ... in body
- ==> join j2 x = body
- in case e of { T -> j2 (I# e1); F -> j (I# e2) }
+(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again
+ using `mkWWcpr_one` to do the unpacking.
+
+Wrinkles:
+
+(TS3) Here's an example of (B), thunk-splitting based on CPR information, in action.
+ Suppose we have
+ let x* = case e of { T -> Just e1; F -> Just e2 }
+ in body
+ If the Simplifier floats the `case` out, we get
+ join j2 x = body
+ in case e of { T -> j2 (Just e1); F -> j2 (Just e2) }
which is not good (boxing).
-* In fact, splitThunk uses the function argument w/w splitting
- function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L))
- then the splitting will go deeper too.
+ If we first do the thunk-splitting transformation, we get
+ let x* = case (case e of { T -> Just e1; F -> Just e2 }) of
+ Just a -> Just a
+ in body
+
+ Now when the Simplifier floats we will get:
+ join j a = let x* = Just a in body
+ in case e of { T -> j e1; F -> j e2 }
+ which is much better (no boxing).
+
+(TS4) We only do thunk-splitting for thunks that are:
+ * strictly-demanded
+ * non-recursive
+ For lazy thunks, transforming the RHS into something more complicated is silly.
+ Note top level thunks are always lazy, so the binder will have an External Name.
-* For recursive thunks, the Simplifier is unable to float `x-rhs` out of
+ For recursive thunks, the Simplifier is unable to float `x-rhs` out of
`x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
- back to the original definition, so we just split non-recursive thunks.
+ back to the original definition.
-Note [Thunk splitting for top-level binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Top-level bindings are never strict. Yet they can be absent, as T14270 shows:
-
- module T14270 (mkTrApp) where
- mkTrApp x y
- | Just ... <- ... typeRepKind x ...
- = undefined
- | otherwise
- = undefined
- typeRepKind = Tick scc undefined
-
-(T19180 is a profiling-free test case for this)
-Note that `typeRepKind` is not exported and its only use site in
-`mkTrApp` guards a bottoming expression. Thus, demand analysis
-figures out that `typeRepKind` is absent and splits the thunk to
-
- typeRepKind =
- let typeRepKind = Tick scc undefined in
- let typeRepKind = absentError in
- typeRepKind
-
-But now we have a local binding with an External Name
-(See Note [About the NameSorts]). That will trigger a CoreLint error, which we
-get around by localising the Id for the auxiliary bindings in 'splitThunk'.
+(TS5) Notice that (B) CPR-led thunk splitting can be useful:
+ * when multi-constructor data types are involved, so that the argument-unboxing
+ mechanism (A) is impotent. See the example in (TS3), which uses `Maybe`.
+ * when the binder is only demanded head-strictly, but CPR has nested information.
+
+ So (A) and (B) have complementary benefits. We might do even better by
+ /combining/ (A) and (B), but at the moment we try (A) first, and then try (B)
+ if (A) is impotent. Combining them would be more work.
-}
--- | See Note [Thunk splitting].
---
--- splitThunk converts the *non-recursive* binding
+-- | splitThunkStr converts the *non-recursive* binding
-- x = e
-- into
--- x = let x' = e in
--- case x' of I# y -> let x' = I# y in x'
--- See comments above. Is it not beautifully short?
--- Moreover, it works just as well when there are
--- several binders, and if the binders are lifted
--- E.g. x = e
--- --> x = let x' = e in
--- case x' of (a,b) -> let x' = (a,b) in x'
--- Here, x' is a localised version of x, in case x is a
--- top-level Id with an External Name, because Lint rejects local binders with
--- External Names; see Note [About the NameSorts] in GHC.Types.Name.
---
--- How can we do thunk-splitting on a top-level binder? See
--- Note [Thunk splitting for top-level binders].
-splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)]
-splitThunk ww_opts is_rec x rhs
- = assert (not (isJoinId x)) $
- do { let x' = localiseId x -- See comment above
- ; (useful,_args, wrap_fn, fn_arg)
- <- mkWWstr_one ww_opts x' NotMarkedStrict
- ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ]
- ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive
- return res
- else return [(x, rhs)] }
+-- x = let x = e in
+-- case x of I# y -> I# y
+-- See Note [Thunk splitting].
+splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+splitThunkStr ww_opts x rhs
+ = do { (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts x NotMarkedStrict
+ -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting]
+
+ ; if useful
+ then return (Just (Let (NonRec x rhs) $
+ wrap_fn fn_arg))
+ else return Nothing }
+
+splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+-- See Note [Thunk splitting]
+-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR
+-- property, say Just (Just _), return this new RHS:
+-- let x' = rhs in
+-- case x' of { Just p -> case p of { Just q -> -- Unpacking code
+-- Just (Just q) }} -- Repacking code
+-- Works for multi-constructor data types, where splitThunkStr will fail
+splitThunkCpr ww_opts x rhs
+ = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $ -- It's a thunk
+ do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr
+ -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting]
+ ; if useful
+ then return (Just (Let (NonRec x rhs) $
+ unpacker rebuild_result))
+ else return Nothing }
+
+ where
+ cpr_type :: CprType
+ cpr_type = cprSigType (idCprSig x)
+ cpr :: Cpr
+ cpr = cprTypeCpr cpr_type
+
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser
{-# LANGUAGE ViewPatterns #-}
module GHC.Core.Opt.WorkWrap.Utils
- ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one
+ ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one
, needsVoidWorkerArg
, DataConPatContext(..)
, UnboxingDecision(..), canUnboxArg
@@ -230,8 +230,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
; let (work_args, work_marks) = unzip work_args_str
-- Do CPR w/w. See Note [Always do CPR w/w]
- ; (useful2, wrap_fn_cpr, work_fn_cpr)
- <- mkWWcpr_entry opts res_ty' res_cpr
+ ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr
; let (work_lam_args, work_call_args, work_call_str)
| needsVoidWorkerArg fun_id arg_vars work_args
@@ -985,6 +984,12 @@ mkWWstr opts args str_marks
-- * wrap_arg assumes work_args are in scope, and builds a ConApp that
-- reconstructs the RHS of wrap_var that we pass to the original RHS
-- See Note [Worker/wrapper for Strictness and Absence]
+--
+-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int
+-- = ( True -- useful
+-- , [p,q#], -- work_args
+-- , \e -> case x of (p,q) -> case q of I# q# -> e -- wrap_fn
+-- , (p, I# q) ) -- wrap_arg
mkWWstr_one :: WwOpts
-> Var
-> StrictnessMark
@@ -1041,7 +1046,7 @@ unbox_one_arg opts arg_var
-- Apply str info to new args. Also remove OtherCon unfoldings so they
-- don't end up in lambda binders of the worker.
- -- See Note [Never put `OtherCon` unfoldings on lambda binders]
+ -- See (CBI1) in Note [Core binder IdInfo invariants]
arg_ids' = map zapIdUnfolding $
zipWithEqual setIdDemandInfo arg_ids ds
@@ -1637,7 +1642,9 @@ mk_res_bndr body_ty = do
-- 1. A 'WwUse' capturing whether the split does anything useful.
-- 2. The list of transit variables (see the Note).
-- 3. The result builder expression for the wrapper. The original case binder if not useful.
--- 4. The result unpacking expression for the worker. 'nop_fn' if not useful.
+-- Assumes that the transit vars are in scope
+-- 4. The result unpacking expression for the worker. 'nop_fn' if not useful
+-- Brings the transit vars into scope
type CprWwResultOne = (WwUse, OrdList Var, CoreExpr , CoreExpr -> CoreExpr)
type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr)
@@ -1711,8 +1718,7 @@ unbox_one_result opts res_bndr
move_transit_vars :: [Id] -> (CoreExpr -> CoreExpr -> CoreExpr, CoreExpr)
move_transit_vars vars
| [var] <- vars
- , let var_ty = idType var
- , isUnliftedType var_ty || exprIsHNF (Var var)
+ , varIsHNF var -- NB: True of variables of unlifted type
-- See Note [No unboxed tuple for single, unlifted transit var]
-- * Wrapper: `unbox scrut alt = (case <scrut> of a -> <alt>)`
-- * Worker: `tup = a`
@@ -1769,7 +1775,7 @@ To achieve said transformation, 'mkWWcpr_entry'
what belongs in the case scrutinee of the unpacker through the communicated
Id `r`: The unpacking expression will be free in that variable.
(This is a similar contract as that of 'mkWWstr_one' for strict args.)
- 3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables
+ 3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables
that have to be transferred from the worker to the wrapper, where the
constructed result can be rebuilt, `a` and `b` above. Part (3) is
responsible for tupling them up in the worker and taking the tuple apart
@@ -1816,7 +1822,7 @@ return unboxed instead of in an unboxed singleton tuple:
We want `$wh :: Int# -> [Int]`.
We'd get `$wh :: Int# -> (# [Int] #)`.
-By considering vars as unlifted that satisfy 'exprIsHNF', we catch (3).
+By considering vars as unlifted that satisfy 'varIsHNF', we catch (3).
Why not check for 'exprOkForSpeculation'? Quite perplexingly, evaluated vars
are not ok-for-spec, see Note [exprOkForSpeculation and evaluated variables].
For (1) and (2) we would have to look at the term. WW only looks at the
=====================================
compiler/GHC/Core/Ppr.hs
=====================================
@@ -637,6 +637,7 @@ instance Outputable IdInfo where
[ (has_prag, text "InlPrag=" <> pprInlineDebug prag_info)
, (has_occ, text "Occ=" <> ppr occ_info)
, (has_dmd, text "Dmd=" <> ppr dmd_info)
+ , (has_cpr, text "Cpr=" <> ppr cpr_info)
, (has_lbv , text "OS=" <> ppr lbv_info)
, (has_arity, text "Arity=" <> int arity)
, (has_called_arity, text "CallArity=" <> int called_arity)
@@ -658,6 +659,9 @@ instance Outputable IdInfo where
lbv_info = oneShotInfo info
has_lbv = not (hasNoOneShotInfo lbv_info)
+ cpr_info = cprSigInfo info
+ has_cpr = not $ isTopCprSig cpr_info
+
arity = arityInfo info
has_arity = arity /= 0
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -13,7 +13,7 @@ module GHC.Core.Utils (
mkTick, mkTicks, mkTickNoHNF, tickHNFArgs,
mkTickCpe,
bindNonRec, needsCaseBinding, needsCaseBindingL,
- mkAltExpr, mkDefaultCase, mkSingleAltCase,
+ mkAltExpr, mkDefaultCase, mkSingleAltCase, mkCaseFromLet,
-- * Taking expressions apart
findDefault, addDefault, findAlt, isDefaultAlt,
@@ -29,7 +29,7 @@ module GHC.Core.Utils (
exprIsTrivial, getIdFromTrivialExpr, getIdFromTrivialExpr_maybe,
trivial_expr_fold,
exprIsDupable, exprIsCheap, exprIsExpandable, exprIsCheapX, CheapAppFun,
- exprIsHNF, exprOkForSpeculation, exprOkToDiscard, exprOkForSpecEval,
+ exprIsHNF, varIsHNF, exprOkForSpeculation, exprOkToDiscard, exprOkForSpecEval,
exprIsWorkFree, exprIsConLike,
isCheapApp, isExpandableApp, isSaturatedConApp,
exprIsTickedString, exprIsTickedString_maybe,
@@ -756,8 +756,17 @@ bindNonRec bndr rhs body
| needsCaseBinding (idType bndr) rhs = case_bind
| otherwise = let_bind
where
- case_bind = mkDefaultCase rhs bndr body
let_bind = Let (NonRec bndr rhs) body
+ case_bind = mkCaseFromLet bndr rhs body
+
+mkCaseFromLet :: Id -> CoreExpr -> CoreExpr -> CoreExpr
+-- Given x=rhs in body, return
+-- case rhs of x { DEFAULT -> body }
+mkCaseFromLet bndr rhs body
+ = mkDefaultCase rhs (mkCaseBndrFromLetBndr bndr) body
+ -- mkCaseBndrFromLetBndr: bndr may have IdInfo suitable for a
+ -- let-binder; see Note [Core binder IdInfo invariants]
+ -- in GHC.Core
-- | `needsCaseBinding` tests whether we have to use a @case@ rather than @let@
-- binding for this expression as per the invariants of 'CoreExpr': see
@@ -2630,12 +2639,37 @@ it doesn't have the trickiness of the let-can-float invariant to worry about.
exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
exprIsHNF = exprIsHNFlike isDataConWorkId isEvaldUnfolding True
+-- | @varIsHNF v@ is the same as @exprIsHNF (Var v)@, but avoids building
+-- the @Var@ only to take it apart again
+varIsHNF :: Var -> Bool
+varIsHNF = varIsHNFlike isDataConWorkId isEvaldUnfolding
+
-- | Similar to 'exprIsHNF' but includes CONLIKE functions as well as
-- data constructors. Conlike arguments are considered interesting by the
-- inliner.
exprIsConLike :: CoreExpr -> Bool -- True => lambda, conlike, PAP
exprIsConLike = exprIsHNFlike isConLikeId isConLikeUnfolding False
+varIsHNFlike :: (Var -> Bool) -> (Unfolding -> Bool) -> Var -> Bool
+-- The (Var v) case of exprIsHNFlike
+{-# INLINE varIsHNFlike #-}
+varIsHNFlike is_con is_con_unf v
+ = idArity v > 0 || is_con v
+ -- A PAP is a value, as is a nullary constructor, so that [] and ()
+ -- are values, for example; and (e.g.) primops that don't have unfoldings.
+ -- This is (id_app_is_value v []) in exprIsHNFlike
+
+ || is_con_unf (idUnfolding v)
+ -- Check the thing's unfolding; it might be bound to a value
+ -- or to a guaranteed-evaluated variable (isEvaldUnfolding)
+ -- Contrast with Note [exprOkForSpeculation and evaluated variables]
+ -- We don't look through loop breakers here, which is a bit conservative
+ -- but otherwise I worry that if an Id's unfolding is just itself,
+ -- we could get an infinite loop
+
+ || definitelyUnliftedType (idType v)
+ -- Unlifted binders are always evaluated (#20140)
+
-- | Returns true for values or value-like expressions. These are lambdas,
-- constructors / CONLIKE functions (as determined by the function argument)
-- or PAPs.
@@ -2649,20 +2683,8 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
= -- pprTraceWith "hnf" (\r -> ppr r <+> ppr e) $
is_hnf_like e
where
- is_hnf_like (Var v) -- NB: There are no value args at this point
- = id_app_is_value v [] -- Catches nullary constructors,
- -- so that [] and () are values, for example
- -- and (e.g.) primops that don't have unfoldings
- || is_con_unf (idUnfolding v)
- -- Check the thing's unfolding; it might be bound to a value
- -- or to a guaranteed-evaluated variable (isEvaldUnfolding)
- -- Contrast with Note [exprOkForSpeculation and evaluated variables]
- -- We don't look through loop breakers here, which is a bit conservative
- -- but otherwise I worry that if an Id's unfolding is just itself,
- -- we could get an infinite loop
-
- || definitelyUnliftedType (idType v)
- -- Unlifted binders are always evaluated (#20140)
+ is_hnf_like (Var v) = varIsHNFlike is_con is_con_unf v
+ -- NB: There are no value args at this point
is_hnf_like (Lit lit)
| isLitRubbish lit = rubbish_lit_result
@@ -2697,6 +2719,8 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
app_is_value _ _ = False
id_app_is_value id val_args
+ | null val_args -- We can get here via (f @Int), say
+ = varIsHNFlike is_con is_con_unf id
| Just dc <- isDataConWorkId_maybe id
, isUnaryClassDataCon dc
= all is_hnf_like val_args -- Look through unary class data cons
=====================================
compiler/GHC/CoreToStg/Prep.hs
=====================================
@@ -2366,7 +2366,7 @@ wrapBinds floats body
-- See Note [BindInfo and FloatInfo] on whether we pick Case or Let here
mk_bind f@(Float bind CaseBound _) body
| NonRec bndr rhs <- bind
- = mkDefaultCase rhs bndr body
+ = mkCaseFromLet bndr rhs body
| otherwise
= pprPanic "wrapBinds" (ppr f)
mk_bind (Float bind _ _) body
=====================================
compiler/GHC/HsToCore/Utils.hs
=====================================
@@ -131,19 +131,20 @@ selectMatchVars ps = mapM (uncurry selectMatchVar) ps
selectMatchVar :: Mult -> Pat GhcTc -> DsM Id
-- Postcondition: the returned Id has an Internal Name
-selectMatchVar w (BangPat _ pat) = selectMatchVar w (unLoc pat)
-selectMatchVar w (LazyPat _ pat) = selectMatchVar w (unLoc pat)
-selectMatchVar w (ParPat _ pat) = selectMatchVar w (unLoc pat)
-selectMatchVar _w (VarPat _ var) = return (localiseId (unLoc var))
- -- Note [Localise pattern binders]
- --
- -- Remark: when the pattern is a variable (or
- -- an @-pattern), then w is the same as the
- -- multiplicity stored within the variable
- -- itself. It's easier to pull it from the
- -- variable, so we ignore the multiplicity.
-selectMatchVar _w (AsPat _ var _) = assert (isManyTy _w ) (return (localiseId (unLoc var)))
-selectMatchVar w other_pat = newSysLocalDs (Scaled w (hsPatType other_pat))
+selectMatchVar w (BangPat _ pat) = selectMatchVar w (unLoc pat)
+selectMatchVar w (LazyPat _ pat) = selectMatchVar w (unLoc pat)
+selectMatchVar w (ParPat _ pat) = selectMatchVar w (unLoc pat)
+
+selectMatchVar _w (VarPat _ var) = return (mkLamBndrFromLetBndr (unLoc var))
+selectMatchVar _w (AsPat _ var _) = assert (isManyTy _w ) $
+ return (mkLamBndrFromLetBndr (unLoc var))
+ -- mkLamBndrFromLetBndr: see Note [Localise pattern binders]
+ --
+ -- Remark: when the pattern is a variable (or an @-pattern), then w is
+ -- the same as the multiplicity stored within the variable
+ -- itself. It's easier to pull it from the variable, so we ignore _w here
+
+selectMatchVar w other_pat = newSysLocalDs (Scaled w (hsPatType other_pat))
{- Note [Localise pattern binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -167,9 +168,15 @@ It's quite rare for this to actually *happen* -- the only case I know
of is tc003 compiled with the 'hpc' way -- but that only makes it
all the more annoying.
-To avoid this, we craftily call 'localiseId' in the desugarer, which
-simply turns the External Name for the Id into an Internal one, but
-doesn't change the unique. So the desugarer produces this:
+Very similarly, we might have
+ {-# NOINLINE a #-}
+ [Just a] = e
+and we don't allow a NOINLINE on case-alternative binders.
+
+To avoid these problems, we craftily call `mkLamBndrFromLetBndr` in the
+desugarer, which simply turns the External Name for the Id into an Internal one,
+and expunges bad IdInfo, but doesn't change the unique. So the desugarer produces
+this:
M.a{r8} = case e of (v:_) ->
case v of Just a{r8} -> M.a{r8}
The unique is still 'r8', but the binding site in the pattern
@@ -265,8 +272,14 @@ bindMatchId new mid body
-- Used to force variables when desugaring strict binders. It's crucial that the
-- variable is shadowed by the case binder. See Wrinkle 1 in
-- Note [Desugar Strict binds] in GHC.HsToCore.Binds.
+--
seqVar :: Var -> CoreExpr -> CoreExpr
-seqVar var body = mkDefaultCase (Var var) var body
+seqVar var body = mkCaseFromLet var (Var var) body
+ -- mkCaseFromLet: the case binder has the same Name (and hence Unique), type
+ -- and multiplicity as `var`, but not its IdInfo: `var` may have, say, a
+ -- NOINLINE pragma, but a case binder must not; see Note [Core binder IdInfo
+ -- invariants] in GHC.Core, and #27965. E.g. `res1` in
+ -- GHC.Internal.Control.Monad.ST.Lazy.Imp has a NOINLINE pragma.
mkCoLetMatchResult :: HasDebugCallStack => CoreBind -> MatchResult CoreExpr -> MatchResult CoreExpr
mkCoLetMatchResult bind = fmap (mkCoreLet bind)
@@ -684,7 +697,7 @@ mkSelectorBinds ticks pat ctx val_expr
binders = collectPatBinders CollNoDictBinders pat'
ticks' = ticks ++ repeat []
- local_binders = map localiseId binders -- See Note [Localise pattern binders]
+ local_binders = map mkLamBndrFromLetBndr binders -- See Note [Localise pattern binders]
strip_bangs :: LPat (GhcPass p) -> LPat (GhcPass p)
-- Remove outermost bangs and parens
=====================================
compiler/GHC/Types/Cpr.hs
=====================================
@@ -8,6 +8,7 @@
module GHC.Types.Cpr (
Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr,
CprType (..), topCprType, botCprType, flatConCprType,
+ cprTypeArity, cprTypeCpr,
lubCprType, applyCprTy, abstractCprTy, trimCprTy,
UnpackConFieldsResult (..), unpackConFieldsCpr,
CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig,
@@ -106,6 +107,12 @@ data CprType
-- 'ct_arty' arguments
}
+cprTypeArity :: CprType -> Arity
+cprTypeArity = ct_arty
+
+cprTypeCpr :: CprType -> Cpr
+cprTypeCpr = ct_cpr
+
instance Eq CprType where
a == b = ct_cpr a == ct_cpr b
&& (ct_arty a == ct_arty b || ct_cpr a == topCpr)
@@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr
-- | The arity of the wrapped 'CprType' is the arity at which it is safe
-- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand"
-newtype CprSig = CprSig { getCprSig :: CprType }
+newtype CprSig = CprSig { cprSigType :: CprType }
deriving (Eq, Binary)
-- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig'
=====================================
compiler/GHC/Types/Id.hs
=====================================
@@ -94,6 +94,7 @@ module GHC.Types.Id (
idArity,
idCallArity, idFunRepArity,
idSpecialisation, idCoreRules, idHasRules,
+ lamBndrInfoOK,
idCafInfo, idLFInfo_maybe,
idOneShotInfo,
idOccInfo,
@@ -103,6 +104,7 @@ module GHC.Types.Id (
-- ** Writing 'IdInfo' fields
setIdUnfolding, zapIdUnfolding, setCaseBndrEvald,
+ mkCaseBndrFromLetBndr, mkLamBndrFromLetBndr,
setIdArity,
setIdCallArity,
@@ -881,10 +883,33 @@ setCaseBndrEvald :: StrictnessMark -> Id -> Id
-- itself, and any pattern-bound variables that are argument of a
-- strict constructor. It just marks the variable as already-evaluated,
-- so that (for example) a subsequent 'seq' can be dropped
+-- See Note [Evaluated-ness on case binders] in GHC.Core
setCaseBndrEvald str id
| isMarkedStrict str = id `setIdUnfolding` evaldUnfolding
| otherwise = id
+-- | Just like `mkLamBndrFromLetBndr` but in addition
+-- record that it is evaluated.
+-- See Note [Core binder IdInfo invariants] in GHC.Core
+mkCaseBndrFromLetBndr :: Id -> Id
+mkCaseBndrFromLetBndr id
+ = mkLamBndrFromLetBndr id `setIdUnfolding` evaldUnfolding
+
+-- | Make a lambda binder from a binder that might have been let-bound, e.g.
+-- let x = rhs in body ==> (\x. body) rhs
+-- The let-binder may have IdInfo (an unfolding, an inline pragma, RULES)
+-- that a case binder must not have, so we keep its Name, type, multiplicity
+-- and IdDetails, plus OccInfo and DemandInfo, but reset its other IdInfo.
+-- See Note [Core binder IdInfo invariants] in GHC.Core
+mkLamBndrFromLetBndr :: Id -> Id
+mkLamBndrFromLetBndr id
+ = localiseId id `setIdInfo` zapped_info
+ where
+ info = idInfo id
+ zapped_info = vanillaIdInfo `setOccInfo` occInfo info
+ `setDemandInfo` (demandInfo info)
+
+
-- | Similar to trimUnfolding, but also removes evaldness info.
zapIdUnfolding :: Id -> Id
zapIdUnfolding v
@@ -905,6 +930,32 @@ idCoreRules id = ruleInfoRules (idSpecialisation id)
idHasRules :: Id -> Bool
idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
+-- | True <=> the Id has only the IdInfo permitted on a lambda, case, or
+-- case-alternative binder. See the table in Note [Core binder IdInfo invariants]
+-- in GHC.Core; Core Lint checks this invariant.
+--
+-- We allow occurrence info, demand info, and one-shot info (which the table
+-- permits only on lambda binders, but a case binder may be about to become one).
+-- We also allow an `OtherCon []` unfolding; lambda binders must have no unfolding
+-- at all, but Lint checks that separately.
+lamBndrInfoOK :: Id -> Bool
+lamBndrInfoOK id
+ = isDefaultInlinePragma (inlinePragInfo info)
+ && isNopSig (dmdSigInfo info)
+ && isTopCprSig (cprSigInfo info)
+ && mayHaveCafRefs (cafInfo info)
+ && arityInfo info == unknownArity
+ && callArityInfo info == unknownArity
+ && isEmptyRuleInfo (ruleInfo info)
+ && unf_ok (realUnfoldingInfo info)
+ where
+ info = idInfo id
+
+ -- See Note [Evaluated-ness on case binders] in GHC.Core
+ unf_ok NoUnfolding = True
+ unf_ok (OtherCon []) = True
+ unf_ok _ = False
+
setIdSpecialisation :: Id -> RuleInfo -> Id
setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
=====================================
compiler/GHC/Utils/Monad.hs
=====================================
@@ -16,7 +16,7 @@ module GHC.Utils.Monad
, mapAccumLM
, mapSndM
, concatMapM
- , mapMaybeM
+ , mapMaybeM, orElseM
, anyM, allM, orM
, foldlM, foldlM_, foldrM, foldMapM
, whenM, unlessM
@@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = do { cond <- condM
; unless cond acc }
+-- | Monadic version of @orElse@
+infixr 4 `orElseM`
+orElseM :: Monad m => m (Maybe a) -> m a -> m a
+orElseM ma def = do { mb_r <- ma
+ ; case mb_r of
+ Just x -> return x
+ Nothing -> def }
+
-- | Like 'filterM', only it reverses the sense of the test.
filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterOutM p =
=====================================
testsuite/tests/simplCore/should_compile/T15445.stderr
=====================================
@@ -4,6 +4,7 @@ Rule fired: Int# -> Integer -> Int# (GHC.Internal.Bignum.Integer)
Rule fired: USPEC plusTwoRec @Int (T15445a)
Rule fired: USPEC $fShowList @Int (GHC.Internal.Show)
Rule fired: Class op >> (BUILTIN)
+Rule fired: Class op show (BUILTIN)
Rule fired: USPEC plusTwoRec @Int (T15445a)
Rule fired: Class op enumFromTo (BUILTIN)
Rule fired: eftInt (GHC.Internal.Enum)
@@ -11,7 +12,6 @@ Rule fired: Class op show (BUILTIN)
Rule fired: USPEC plusTwoRec @Int (T15445a)
Rule fired: Class op enumFromTo (BUILTIN)
Rule fired: eftInt (GHC.Internal.Enum)
-Rule fired: Class op show (BUILTIN)
Rule fired: eftIntList (GHC.Internal.Enum)
Rule fired: ># (BUILTIN)
Rule fired: ==# (BUILTIN)
=====================================
testsuite/tests/simplCore/should_compile/T27962.hs
=====================================
@@ -0,0 +1,16 @@
+{-# LANGUAGE MagicHash #-}
+
+module T27962 where
+
+import GHC.Exts
+
+newtype N = MkN Int
+
+-- After inlining myRun, we get (runRW# @LiftedRep @Int |> co) (\_ -> ...)
+-- and the simplifier pushes co into the argument of runRW#.
+-- #27962: the simplifier dropped that cast, yielding ill-typed Core
+myRun :: (State# RealWorld -> N) -> N
+myRun = coerce (runRW# :: (State# RealWorld -> Int) -> Int)
+{-# INLINE myRun #-}
+
+foo x = myRun (\_ -> MkN (x+1))
=====================================
testsuite/tests/simplCore/should_compile/T27963.hs
=====================================
@@ -0,0 +1,23 @@
+{-# OPTIONS_GHC -Wno-inline-rule-shadowing #-}
+
+module T27963 where
+
+-- This test is pretty delicate because it relies on a function
+-- that has BOTH a rule AND an INLINE pragma
+--
+-- See #27963 for some discussion
+--
+-- Still, it should (just) work
+
+import GHC.Exts
+
+newtype N = MkN Int
+
+f x = x
+{-# INLINE f #-}
+{-# RULES "f/42" forall x. f x = 42::Int #-}
+
+-- The rule "f/42" should fire in both h1 and h2
+h1,h2 :: N -> Int
+h1 n = f (coerce n) + 0
+h2 n = (coerce f) n + 0 -- #27963: the rule did not fire here
=====================================
testsuite/tests/simplCore/should_compile/T27963.stderr
=====================================
@@ -0,0 +1,2 @@
+Rule fired: f/42 (T27963)
+Rule fired: f/42 (T27963)
=====================================
testsuite/tests/simplCore/should_compile/T27965.hs
=====================================
@@ -0,0 +1,9 @@
+-- Lint checks that we don't produce a lambda-binder
+-- with a NOINLINE pragma on it (#27965)
+
+module T27965 where
+
+h fm s = let {-# NOINLINE res1 #-}
+ !res1 = fm s
+ !(f, s') = res1
+ in (f+1::Int, s')
=====================================
testsuite/tests/simplCore/should_compile/T27965a.hs
=====================================
@@ -0,0 +1,7 @@
+{-# LANGUAGE MonoLocalBinds #-}
+module M where
+
+f :: (Int, Int) -> Int
+f p = let {-# NOINLINE a #-}
+ (a, b) = p
+ in a + b
=====================================
testsuite/tests/simplCore/should_compile/T28158.hs
=====================================
@@ -0,0 +1,18 @@
+module T28158 where
+
+-- Here we miss CPR on y
+-- It's a bit of an obscure example, but still; see #28158
+f :: a -> a -> a -> [Int] -> [Int]
+f a b c xs = let y = case xs of
+ [0] -> Just a
+ [1] -> Just b
+ _ -> Just c
+ in h y (case y of
+ Just z -> reverse (reverse (reverse (
+ reverse (reverse (reverse (
+ reverse (reverse xs)))))))
+ Nothing -> xs++xs)
+
+h :: Maybe a -> b -> b
+h (Just y) e = h Nothing e
+h Nothing e = e
=====================================
testsuite/tests/simplCore/should_compile/T28158.stderr
=====================================
@@ -0,0 +1,47 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 72, types: 76, coercions: 0, joins: 1/1}
+
+Rec {
+h = \ @a @b ds e ->
+ case ds of {
+ Nothing -> e;
+ Just y -> h Nothing e
+ }
+end Rec }
+
+f = \ @a a1 b c xs ->
+ join {
+ $j ww
+ = h (Just ww)
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1 (reverse1 (reverse1 (reverse xs) []) []) []) [])
+ [])
+ [])
+ []) } in
+ case xs of {
+ [] -> jump $j c;
+ : ds ds1 ->
+ case ds of { I# ds2 ->
+ case ds2 of {
+ __DEFAULT -> jump $j c;
+ 0# ->
+ case ds1 of {
+ [] -> jump $j a1;
+ : ipv ipv1 -> jump $j c
+ };
+ 1# ->
+ case ds1 of {
+ [] -> jump $j b;
+ : ipv ipv1 -> jump $j c
+ }
+ }
+ }
+ }
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,9 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+test('T27962', normal, compile, [''])
+test('T27962a', [extra_files(['T27962.hs'])], multimod_compile, ['T27962', '-v0 -O'])
+test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
+test('T27965', normal, compile, ['-O'])
+test('T27965a', normal, compile, ['-O'])
+test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/58bf666becc1562b9591c0a0fea143ā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/58bf666becc1562b9591c0a0fea143ā¦
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/apk/stricter-sink] 190 commits: Change the C types of hs_{bitrev,bswap}{16,32} to match the Haskell types
by Andreas Klebinger (ļ¼ AndreasK) 20 Nov '26
by Andreas Klebinger (ļ¼ AndreasK) 20 Nov '26
20 Nov '26
Andreas Klebinger pushed to branch wip/apk/stricter-sink at Glasgow Haskell Compiler / GHC
Commits:
545fd4fb by ARATA Mizuki at 2026-09-22T15:03:24-04:00
Change the C types of hs_{bitrev,bswap}{16,32} to match the Haskell types
bitReverse{16,32}# and byteSwap{16,32}# have the type
Word# -> Word#, but their C correspondents took and
returned StgWord{16,32}.
The mismatch on bitReverse16# led to the problem reported
in #27299. Although no similar issue is reported for
bitReverse32# and byteSwap{16,32}#, it seemed wise to
change them proactively.
This commit fixes the mismatch by changing the C type.
Fixes #27299
- - - - -
bf17f289 by fendor at 2026-09-22T15:04:05-04:00
Don't lose instances from shadowed imported modules with the same name
When we look for instances below the current module, we need to check
the unit id as well when we check for whether the module is the current
module, otherwise we ignore modules we import that have the same name as
the import module.
Adds regression test.
- - - - -
53eead15 by Wolfgang Jeltsch at 2026-09-24T20:12:03-04:00
Correct the documentation of `explicitUnits`
Resolves #27787.
- - - - -
35bf6f4b by Simon Jakobi at 2026-09-24T20:12:49-04:00
Remove stale specHeader bullet from Note [Don't make fillers for constraint types]
The Note said that Specialise.specHeader also calls mkAbsentFiller.
abfc224a27c removed that call: the specialiser no longer drops dead
arguments at all, see Note [Do not drop dead args from specialisations]
in GHC.Core.Opt.Specialise.
Assisted-by: Claude Fable 5.1
- - - - -
1abef1ef by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Improve the `mhu-closure` makefile
- - - - -
a79a68ea by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Make `ghci-multi` hide all unneeded packages
- - - - -
d6e72450 by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Improve the definition of the home unit closure property
- - - - -
c9a2766d by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Re-implement the home unit closure check
Compared to the previous implementation, the new one has the following
advantages:
* It is correct.
- It distinguishes between units that have the same unit ID but
different ABI hashes.
- When `-hide-all-packages` is not used, it considers as home unit
dependencies also units that are made implicitly available
because they are in the package database.
* It seems to be faster in usual settings.
- In particular, it does not have a preparation phase in which it
merges the dependency information from all home units, so that
its running time does not grow linearly with the size of the
package database in normal Cabal scenarios.
* It is (hopefully) clearer.
* It is better documented.
- - - - -
fa96acf8 by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Remove erroneous GHC flag in `hadrian-multi`
The flag was `-Werror=-Wno-error=incomplete-record-selectors`. Its
purpose was to permit incomplete record selectors, but because of the
illegal combination of `-Werror=` and `-Wno-error` it was ignored,
without any negative consequences.
- - - - -
9f48a5b9 by Alan Zimmerman at 2026-09-25T17:02:50-04:00
EPA: Add specific layout field to AnnList
Up to now AnnList has effectively served to represent lists of things
having layout, regardless of whether they do or not.
In Haskell, layout is optional in many places, as there is also an
alternative syntax using braces and semi-colons, which is free-form.
This commit introduces AnnListLayout, a data structure capturing this
distinction.
It is deliberately set up similarly to EpLayout, so that these two can
be merged in time.
The transition is done mechanically, where AnnListBraces is not used
yet, the original Nothing case maps to AnnListNoLayout, and the Just
case to AnnListLayout.
Later commits will fine tune these against the actual parser layout.
- - - - -
234bab08 by Vladislav Zavialov at 2026-09-29T17:22:54-04:00
Add regression test for #7803
Commit 2effe18ab5, first shipped with GHC 8.2.1, fixed #7803 "Superclass
methods are left unspecialized".
This change turns the example from the ticket description into a regression
test, checking that foo1 is fully specialised at Double, with no calls to the
overloaded exp5Tail.
Closes #7803
Assisted-by: Claude Opus 5
- - - - -
c406135c by Andreas Klebinger at 2026-10-01T06:57:28-04:00
RTS: Update flag parsing/handling:
Using 0 as argument to any of these flags now resets the flags setting to default:
- ``-n0`` disables nursery chunking.
- ``-K0`` (or a bare ``-K``) removes the stack size limit.
- ``-M0`` removes the heap size limit.
- ``-H0`` resets the suggested heap size, including the nursery scaling set by ``-H``.
- ``-AL0`` makes the large object allocation limit follow ``-A`` again.
GC Generations are now limited to 64.
-n larger than -A now emits a warning and disables chunking.
Fixes #27830 #27829
- - - - -
984ee82b by Andreas Klebinger at 2026-10-01T06:58:10-04:00
Fix MultiLayerModules timeout multiplier.
We accidentally used the compile multiplier for ghci commands which
use the run timeout setting to set the timeout.
Fixes #26263 and #27796.
- - - - -
50a9cf26 by Andreas Klebinger at 2026-10-01T06:58:10-04:00
testsuite: Include runtime in JUnit report.
- - - - -
e358619f by Alan Zimmerman at 2026-10-01T06:59:01-04:00
EPA: Use EpaLocation in EpVirtualBraces
Haddock processing uses EpLayout.EpVirtualBraces to record the current
layout column, for allocating haddock comments correctly.
For exact printing, we need the line as well as the col, so we know
how many lines to skip when the indented code block starts.
This commit updates EpLayout.EpVirtualBraces so that it carries an
EpaLocation instead of just the Int column, to allow it to be used for
both purposes.
It is a simple mechanical change, with no other impact, but it allows
us to use EpLayout instead of AnnListLayout in AnnList, in the next
commit in this series.
- - - - -
1d2a26ee by Andrew Lelechenko at 2026-10-01T20:22:04-04:00
Remove bitSize from MINIMAL pragma of class Bits
Cf. https://github.com/haskell/core-libraries-committee/issues/441
The function is deprecated for 12 years and has a default implementation,
yet it was never removed from the MINIMAL pragma, putting library authors
in a very awkward position. Let's finally remove bitSize from MINIMAL.
- - - - -
3cc21e4c by Hannes Siebenhandl at 2026-10-01T20:22:59-04:00
Add regression test for #27641
- - - - -
c35096f5 by Hannes Siebenhandl at 2026-10-01T20:23:00-04:00
Don't `:add` modules the loader will reject
Only home modules can be actually added to the loader context, thus we
only accept the module if it belongs to a home unit.
- - - - -
a563cb27 by Simon Jakobi at 2026-10-02T17:37:36-04:00
ci: accept modified changelog.d entries in lint-changelog
The changelog guide says to extend an existing entry rather than add a
new one when the feature is already documented. lint_changelog only
counted added files, so such MRs failed before the validator ran.
Fixes #27779.
Assisted-by: Claude Fable 5.1
- - - - -
03082cd4 by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix warning flag name in the semaphore-v2 entry
The entry refers to -Wsemaphore-version-mismatch, which does not exist.
The warning GHC emits when it cannot use a -jsem semaphore, including
on a protocol version mismatch, is -Wsemaphore-open-failure.
Context: !15729, #25087
Assisted-by: Claude Fable 5.1
- - - - -
a93705ee by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix the CLC proposal link in the T27455 entry
The entry used the Sphinx :ref: role with a URL as its target. :ref:
resolves only internal labels, so the generated release notes would
show the proposal name without a link. Use the plain hyperlink form
like the other entries.
Context: !16274, #27455
Assisted-by: Claude Fable 5.1
- - - - -
54381079 by Hannes Siebenhandl at 2026-10-02T17:39:01-04:00
Extend the `TrustOverlay` for wired-in units
The TrustOverlay only contained the `UnitId` of all on-disk units.
However, wired-in units are referred to by their wired-in unit id, which
is not the same as the on-disk unit id.
Thus, trust checks for wired-in units failed because the lookup was
using the wired-in unit, which wasn't present in the `TrustOverlay`.
We fix #27834, by copying the trust info for wired-in unit ids.
- - - - -
f8cfb1a5 by HƩcate Kleidukos at 2026-10-04T19:36:39+02:00
[CLC 341] Strict variants of mutable types
This commit is the implementation of CLC Proposal 341
https://github.com/haskell/core-libraries-committee/issues/341
- - - - -
575c4bc6 by Rodrigo Mesquita at 2026-10-05T12:32:02-04:00
ttg: HsModuleName in the AST, ModuleName in GHC
This commit makes the AST fully independent from GHC by parsing a
"module name" as an `HsModuleName (= HText)` rather than constructing an
`ModuleName (= FastString)` straight away.
In the GHC side, everything remains as a `ModuleName`. We turn AST
`HsModuleName`s into fast strings with the cheap `mkFastStringShortText`
when we process the AST for manipulation within the compiler.
There are no performance regressions introduced by this approach.
This is the final piece of #21592
Alternative plans were discussed in
gitlab.haskell.org/ghc/ghc/-/merge_requests/16546#note_694647,
but the Simon suggested one won in simplicity and performance when
compared against my attempt at implementing my original plan of having
a family `ModuleNameP`.
- - - - -
b3b89d32 by mangoiv at 2026-10-05T22:03:32-04:00
hadrian: Persist the used flavour name in the build root (#20650)
This executes the idea proposed in #20650, teaching Hadrian to persist
the flavour used to build a build root. This both makes use of multiple
build roots more ergonomic (as the user no longer needs to repeat
themselves) and avoids a tiresome foot-gun (forgetting to specify a
flavour, often wholly invalidating a build root).
Closes #20650.
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
- - - - -
f977837b by mangoiv at 2026-10-05T22:04:21-04:00
configure: fix sed script and subst tooldir script
Fixes #27672
Adds sanity checking for SUBST_TOOLDIR
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
f1cb08be by Hannes Siebenhandl at 2026-10-05T22:05:03-04:00
Prepend in-memory unit database for backpack
The packageDbFlags are stored in reverse order. Thus, prepending will
ensure that the in-memory unit database is the last item on the unit
database stack.
Further, the in-memory unit database needs to be able to shadow units
from earlier unit databases in the unit database stack.
Moreover, a `-clear-package-db` would remove the in-memory database if
it weren't the last item on the stack.
Closes #27835
- - - - -
8d49ed42 by Kazu Yamamoto at 2026-10-06T19:37:25-04:00
Do not leave standard file descriptors free at startup (#24450)
A process may be started with stdout closed -- `prog >&-` from a shell does
exactly that. Nothing then reserves descriptor 1, and open(), pipe() and
socket() hand out the lowest free descriptor, so the next descriptor the
runtime creates for itself takes it: the ticker's pipe, or a capability's IO
manager control pipe.
'GHC.Internal.IO.StdHandles.stdout' is a CAF, built the first time the program
writes to stdout, which is long after that has happened. It builds a 'Handle'
over descriptor 1, which now belongs to the runtime, and nothing reports an
error because the descriptor is perfectly good. The program then writes its
output into the runtime's own plumbing.
What that looks like from the outside is a hang. The descriptor the Handle has
taken over is the read end of a pipe, so poll() for POLLOUT on it never says
yes and epoll_ctl() accepts a registration for it; the thread waiting to write
blocks for ever. Closing the Handle at exit closes the runtime's descriptor,
which is worse: the ticker then fails on every tick.
'hs_init_ghc' now opens /dev/null onto whichever of descriptors 0, 1 and 2 are
closed, before the runtime creates any descriptor of its own. Each is opened
for the access that descriptor would normally have, read-only for 0 and
write-only for 1 and 2, so that writing to 'stdin' or reading from 'stdout'
still fails rather than quietly succeeding against /dev/null. See
Note [Standard file descriptors must be open].
Moving only the descriptors the runtime opens would not do: the first file the
program itself opened would land on the free number instead. The fix has to
leave no free number. A program run this way therefore finds stdout connected
to /dev/null rather than failing with EBADF on the first write, which is what
such a program would get from most other language runtimes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
65bcf9e9 by Simon Jakobi at 2026-10-06T19:38:09-04:00
changelog: Repair the sentence describing #27477
The description read "programs using could crash", the object of
"using" having been lost. The synopsis already says which programs are
affected, so drop the dangling word.
Assisted-by: Claude Fable 5.1
- - - - -
15ece296 by mangoiv at 2026-10-08T15:14:56-04:00
ci: move hadrian/ghci into the lint category so it can be picked up by more runners
Fixes #27817
- - - - -
c0823135 by mangoiv at 2026-10-08T15:14:56-04:00
ci: make lint-adjacent jobs into platform independent
- move lint jobs into lint-anyarch tag
- unify lint jobs under the same platform independent container
- - - - -
f76464cf by Zubin Duggal at 2026-10-08T15:15:39-04:00
DmdAnal: Make AbsDmd neutral in maxDmd
fixes #27845
- - - - -
ffa56ae4 by sheaf at 2026-10-09T17:15:59+02:00
Preserve sign of zero when parsing -0.0#
This commit leverages the recently added GHC.Types.Literal.Floating
module in order to preserve the sign of negative zero from
source-written floating-point literals.
Fixes #27545
- - - - -
d538cac9 by Facundo DomĆnguez at 2026-10-09T20:26:38-04:00
Propagate annotations to simple interfaces
This allows annotations to be visible to plugins when run by
haddock. The LiquidHaskell plugin needs the annotations, in particular.
Fixes #26761
- - - - -
32c4f4ab by meooow25 at 2026-10-09T20:27:28-04:00
Bump containers submodule to 0.8.1
And fix affected tests.
* T4086a: containers depends on template-haskell-lift now instead of
template-haskell.
* T22611: Updated to be less dependent on containers internals.
- - - - -
c786065e by sheaf at 2026-10-09T20:28:20-04:00
Use an explicit pattern match in toIfaceIdDetails
The old wildcard pattern let this code bit rot: it did not properly account
for recently added 'IdDetails' such as 'RepPolyId', which resulted in
spurious 'pprTrace' messages that could even pollute HLS sessions.
Fixes #23785
- - - - -
e7cacf59 by sheaf at 2026-10-09T20:29:09-04:00
Take into account ifKind in freeNamesIfDecl
Commit 3c2f4bb4 added the 'ifKind' field to various constructors
of 'IfaceDecl', which preserves the original kind (before type synonym
expansion) for better error messages.
However, that commit forgot to update 'freeNamesIfDecl' correspondingly.
This could result in a "urk! lookup local fingerpring" crash when e.g.
a type's kind uses a type synonym defined later, as we failed to add a
dependency on the type synonym during dependency analysis.
Fixes #27916
- - - - -
41e80f41 by Simon Peyton Jones at 2026-10-11T14:38:51-04:00
Simplify the error-suppression mechanism in GHC.Tc.Errors
In `GHC.Tc.Errors.reportWanteds` we suppress some errors in favour of
others. But the mechanism had grown crufty, and #27331 exposed a bug.
This MR makes it simpler and more uniform, by doing everything via
the `ei_suppress` field of the ErrorItem.
Claude then found another closely-related bug (see the review linked
on !16564). That bug is immortalised in new test T18851d.
I'm still not happy with `ignoreConstraint` but we can worry about
that another day; I have not touched it.
Main changes
* Instead of /predicting/ when an error will be reported, we set
`cec_error_reported` when an error is /actually/ reported. (I renamed
it from `cec_suppress` to reflect this change.)
Now errors are suppressed only when a preceding error has actually been
reported. Simpler and more robust.
See `Note [cec_error_reported: suppressing less-serious errors]`
The big changes are in `reportWanteds` which looks very different.
* New `Note [ei_suppress: suppressing confusing errors]` describes the
(quite separate) `ei_suppress` mechanism for suppressing confusing
errors, mainly arising from non-empty rewriter sets
* In `tryTypeClassDefaulting`, instead of switching off type-class defaulting
if there is an insoluble /anywhere/, we just switch it off locally when
we find an insoluble sub-tree. See Note [When to do type-class defaulting]
and (W5) in Note [ApproximateWC]
* Greatly simplify `insolubleWantedCt`.
* I made type-class-defaulting be a bit more eager, only switched off when
a peer or ancestor (but not child) constraint is insoluble. See
Note [When to do type-class defaulting].
Small refactorings
* Rename `askNoErrs` to `askErrsFound` and flip its polarity
* The code for "check if ei_suppress is true of all items" code is
moved to `mkErrorItems` rather than in the large `reportWanteds`.
* Code for `has_gadt_match` moves to `mkGivenErrorReporter`, rather than
polluting the large `reportWanteds`.
* Many tests with `-fdefer-type-errors` get more warnings, especially
about ambiguous (Num a) constraints. This is by-design: see
Note [Always warn with -fdefer-type-errors]. Previously GHC was not
honouring this Note but now it is, hence the extra errors.
- - - - -
f217fc31 by Cheng Shao at 2026-10-11T14:39:33-04:00
compiler: ensure cross ghc --info output target unit ids
Previously, for cross ghcs, the base/ghc/ghc-internal unit ids in
--info output do not match the target unit ids reported by ghc-pkg,
breaking cross ghc release builds with hash-unit-ids when being used
with cabal 3.18. This patch fixes it by making --info output target
unit ids. Fixes #27919.
Co-authored-by: Codex <codex(a)openai.com>
- - - - -
d07a5176 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Remove the Eq and Ord instances for ForAllTyFlag
In Note [Comparing visibility] in GHC.Core.TyCo.Compare we read that
"we always compare ForAllTyFlags with `eqForAllVis` or `cmpForAllVis`"
But alas there was an Eq and Ord instance for ForAllTyFlag, which made it
impossible to check this claim. So I made these changes:
* Move the definition of ForAllTyFlag and its related functions from
L.H.S.Specificity (where it did not belong, since L.H.S didn't use it)
into GHC.Types.Var.
* Remove the Eq and Ord instances for ForAllTyFlag
* Deal with the fallout, by using `eqForAllVis` or related functions.
* In interface files we use IfaceType as a key for a de-deduplication map
See Note [Deduplication during iface binary serialisation]
in GHC.Iface.Binary. For this we need /exact/ comparison, so we use a
newtype wrapper for IfaceForAllTyFlag, and give use `cmpForAllTyFlagExactly`
to implement its Ord instance. Tiresome but easy.
* Rename `toIfaceForAllBndrs` to `toIfaceForAllTyBndrs`
- - - - -
ea5c054d by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor type and coercion substitution
This MR refactors type and coercion substitution so that they use
TyCoMapper, rather than hand-rolled code. Fundamentally it's a simple
idea, but I had to do quite a bit of refactoring to make it fly.
I got Claude to help me this this refactoring, but I paid careful
attention to every line of code.
Main changes:
* New module GHC.Core.TyCo.Make which defines TyCoMapper, and a bunch of other
simple "smart constructors" for types and coercions. See
GHC.Core.TyCo.Rep Note [The Type-related module hierarchy], esp (TRM1)
* The new TyCoMapper has new fields `tcm_tcapp_ty` and `tcm_tcapp_co` to handle
type-constructor applications. These replace `tcm_tycon`.
* Rewrite GHC.Core.TyCo.Subst to use TyCoMapper
* Rewrite GHC.Core.Type.expandTypeSynonyms to use TyCoMapper.
* Implement `seqType` and `seqCo` with TyCoFolder. To to this I had to add
a `tcf_lit` field to TyCoFolder.
* A new module GHC.Utils.StrictIdentity to define a strict identity monad,
which itself is used for
substTyCoMapper :: TyCoMapper Subst StrictIdentity
* I removed an apparently-unused instance for Binary Levity
Refactoring `seq` functions
* In GHC.Core.Seq, redefine `seqOneShot`, `seqRuleInfo`, and friends to return
`SeqResult`, a new type defined in GHC.Types.Baseic, rather than `()`. We
can define a Monoid instance for `SeqResult` that does the right thing.
* This has knock-on effects across the compiler.
- - - - -
34165e23 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor TyCoMapper to take a single monad; add StrictReaderT
TyCoMapper used to be parameterised over both an environment and a
monad, with fields like
tcm_tyvar :: env -> TyVar -> m Type
Now it is parameterised over just the monad:
tcm_tyvar :: TyVar -> m Type
If the mapping needs an environment, `m` is a reader monad over that
environment. Many uses (e.g. zonkTcTypeMapper, swizzleMapper) need no
environment at all, and used to pass a dummy (). The binder field
becomes
tcm_tycobinder :: forall r. TyCoVar -> ForAllTyFlag
-> (TyCoVar -> m r) -> m r
and runs the continuation in the extended environment. mapTyCoX is gone;
only mapTyCo remains.
To make this efficient, the reader monad must use the one-shot trick and
be strict in the environment. So:
* New module GHC.Utils.Monad.StrictReader defines
newtype StrictReaderT r m a
with hand-written instances. The builder of the pattern synonym
`StrictReaderT` is a smart constructor that adds both `oneShot` and a
bang on the environment, so every StrictReaderT computation is strict
in the environment. See Note [Instances for StrictReaderT].
* ZonkT becomes type ZonkT = StrictReaderT ZonkEnv
ZonkM becomes type ZonkM = StrictReaderT ZonkGblEnv IO
replacing their own hand-written instances.
* Substitution uses
type SubstM = StrictReaderT Subst StrictIdentity
substTyCoMapper :: TyCoMapper SubstM
and similarly expandTypeSynonymMapper.
* zonk_tycomapper :: TyCoMapper (ZonkT TcM) is now much simpler.
* swizzleMapper uses StrictIdentity rather than Identity.
* Module renaming, so that the strict monads are all peers in GHC.Utils.Monad:
GHC.Utils.StrictIdentity ==> GHC.Utils.Monad.StrictIdentity
GHC.Utils.Monad.State.Strict ==> GHC.Utils.Monad.StrictState
alongside the new GHC.Utils.Monad.StrictReader.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
c0299e15 by Simon Jakobi at 2026-10-13T18:11:23-04:00
testsuite: Line-buffer the driver's stdout
Python block-buffers stdout when it is a pipe. This is the case for
example in CI. As a result there is often no indication of progress at
all until the run ends.
To fix this, we configure it explicitly to use line buffering instead.
stderr is reconfigured too, for consistency: Python line-buffers it by
default since 3.9.
The type-ignores are for mypy, which types these handles as TextIO ā an
interface without reconfigure.
Fixes #12934.
Assisted-by: Claude Fable 5
- - - - -
9b5beaa2 by Florian Ragwitz at 2026-10-13T18:12:05-04:00
hpc: Improve coverage semantics for instance methods and instances
Users care about which of their explicitly written methods are or aren't
covered, not whether all of the inherited methods are covered as well. Those
should be covered where they are implemented.
We therefore skip generating top-level boxes for inherited methods which will
appear as uncovered with no clear indication as to why, and no way to fix other
than exercising code the user has not written.
Previously, top-level boxes for those inherited methods would use the instance
head as their source span. Now that those boxes are gone, we can use that
source span for another purpose:
We introduce a new top-level box for each class instance with its instance head
as the source span, and use that to indicate whether or not an instance has
been covered at all.
We do this by making any method of the instance, inherited/generated or
otherwise, tick the box for the instance head. Excluded from this are
methodless classes, which could never be covered using the current mechanism.
This could be improved upon further.
These changes apply to ticking for program coverage only, and don't affect
source notes. Additionally, we update the scope of record selector ticking to
be limited to program coverage as well, as the oversight to also extend it to
source notes has previously caused bugs and because record selector ticking is
coverage-specific.
Fixes #17155, #15932.
- - - - -
836ec50a by Simon Peyton Jones at 2026-10-13T18:12:54-04:00
Refactor fundeps again
This MR fixes #27828; there was a bad scoping error in `trim_qtvs`.
The main changes are
* Refactor `trim_qtvs` completely to eliminate the bug.
* Remove a redundant `apartnessCheck` from `mkTopOpenFamEqFDs`.
* Lots of improvements to the Notes in FunDeps.hs
I also did a couple of pure refactors:
* I realised that we were carefully caching `cab_incomps` in each
`CoAxBranch`, to make it more efficient to reduce a type family application,
but we were not doing the same thing when computing relevance for functional
dependencies; see Note [Relevance] in GHC.Tc.Solver.FunDeps. So I added
`cab_overlaps`, which is now used in `noEarlierMatch`.
* Use a proper data types, `AmIUnifying` and `OuterKindsFlag`, for two
previously-Boolean arguments to `tc_unify_tys`. This is a pure refactor.
- - - - -
889ef371 by Simon Peyton Jones at 2026-10-13T18:13:36-04:00
Refactor and simplify solver's unification code
Ticket #27844 showed that GHC's constraint solver could miss an
occurs check, and thereby build an infinite type.
This patch significantly simplifes the code in
GHC.Tc.Solver.Equality.canEqCanLHSFinish_try_unification
GHC.Tc.Solver.Equality.canEqCanLHSFinish_no_unification
It is now significantly simpler, and requires much less subtle
reasoning to understand.
Main changes
* If `canEqCanLHSFinish_try_unification` fails to unify, it now /always/ calls
`canEqCanLHSFinish_no_unification` rather than trying to finish the job itself.
* `GHC.Tc.Solver.Monad.checkTypeEq` is moved from Monad into Equality, and renamed
to `GHC.Tc.Solver.Equality.checkTypeEqNoUnification`.
* `canEqCanLHSFinish_no_unification` calls `checkTypeEqNoUnification` to test
the invariants for an inert equality. Before this MR there was a special case for
`do_not_prevent_rewriting`, but that has gone; instead it's just a consequence of
the flags passed to `checkTyEqRhs`, documented in the `PuOK` case of
`canEqCanLHSFinish_no_unification`.
* There is only one bit of "swap back" code, in `finish_no_unify` in
`canEqCanLHSFinish_try_unification. Previously this code was duplicated.
* `kickOutAfterFillingCoercionHole` should account for equalities with a
TyFamLHS. See (KOC5) in Note [Kick out after filling a coercion hole]
* No need to gather coercion holes in the `PuOK` case of `canEqCanLHSFinish_no_unification`.
See documentation with that code.
- - - - -
f9193e53 by Simon Peyton Jones at 2026-10-13T18:13:37-04:00
One line fix to fallout from
...#27731, !16564, simplifying Tc.Errors machinery
There was an over-eager assert!
- - - - -
cdd56b7a by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Fix several sphinx errors and warnings from rendering the release notes
The extension references which are removed here are for extension which were
already previously undocumented, so just removing them seems fine for now.
- - - - -
4f00da25 by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Link to QualifiedStrings documentation
- - - - -
97adaf89 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Line up simpleUnifyCheck and check_ty_eq_rhs
Even after #26543 was allegedly fixed, the original repo case in the
Description continued to fail. The reason was that the QuickLook
unifier, `qlUnify`, used `simpleUnifyCheck` for checking unification
invariants; and `simpleUnifyCheck` conservatively rejected any RHS
with a coercion hole in it. The upshot was that QuickLook was not
as clever as it should be, wrongly failing to do an impredicative
instantiation.
Interestingly `check_ty_eq_rhs`, which does the same job during
constraint solving, was more liberal: it just looked at the free vars
of the coercion, and allowed coercion holes.
This MR lines them up, adding some careful notes. See
Note [simpleUnifyCheck]
Note [Occurs check and coercions]
Note [Unification preconditions] esp (COERCIONS)
Things are better than before, but I am still uncomfortable about the
possibilty that a hole might be filled with a coercion that mentions
the LHS type variable; for now I have left this discomfort documented
in Note [Occurs check and coercions].
Main changes
* `qlUnify` now only unifies /instantiation variables/ not regular unification
variables. This makes QuickLook more predictable. See (UQL6) in
Note [QuickLook unification].
* `qlUnify` no longer needs to call `simpleUnifyCheck`, so we can get rid of
`UC_QuickLook` and its code in `simpleUnifyCheck`.
* I found I could get rid of `mkOccFolders` in favour of `anyFreeVarsOfType`.
Hooray.
* Improve documentation of CycleBreakerTv, and rename it to GivenCycleBreakerTv
because they are only uesd for Givens!
* I accepted a 9% worsening in compile time allocation on T5030
because the newly-consistent story triggered #27934.
Other changes
* I refactored `atvFolder` so that it pairs the "interesting-var" function
with the in-scope set, to avoid building a closure with a free variable.
Now we get nice tight loops for `anyFreeVarsOfType` and friends.
See Note [Any-free-var folder].
Metric Increase:
T5030
- - - - -
5f7b3047 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Fix order-dependence in QuickLook
Ticket #27917 pointed out that QuickLook was order-dependent
-- very bad!
The solution is in `qlUnify`: spot when we are unifying a type with a
definite monotype, and then monomorphise any free instantiation
variables of that type.
See (UQL8) and (UQL9) in Note [QuickLook unification].
- - - - -
c391c70c by Simon Peyton Jones at 2026-10-14T00:07:28+01:00
Add some comments about RuntimeUnk
This commit just adds comments explaining why we don't need to worry about
RuntimeUnkTv in the constraint solver.
It also tightens up docmentation of earlier (overlapping) commits in
this MR.
- - - - -
7df3ba2f by Andrea Vezzosi at 2026-10-14T06:15:48-04:00
add runGhcWithSignalHandlers and remove handling from runGhc[T]
it only ever makes sense to call `withSignalHandlers` from `main`, otherwise
signals can be too easily swallowed without notification to the rest of your
process.
This commit takes withSignalHandlers out of `runGhc/runGhcT` and provides
`runGhcWithSignalHandlers` for the old behaviour.
- - - - -
3a72b8a2 by Hannes Siebenhandl at 2026-10-14T13:48:32-04:00
Fix #27836, normalise unit database path in ExternalUnitDatabases
Add a regression test, proofing that all variations:
- local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf/
are parsed only once.
- - - - -
8ddbc6f9 by Florian Ragwitz at 2026-10-14T13:49:28-04:00
Remove obsolete HPC types
Fixes #27946.
- - - - -
f34c79ee by Alan Zimmerman at 2026-10-15T04:54:47-04:00
EPA: Start using vocurly as basis for AnnListLayout
For the existing cases that populate AnnList.
This uses AnnListBraces when braces are explicitly supplied, and
AnnListLayout when vocurly is used
The change also shows up AnnList usages that can never capture layout,
these are cleared up later.
- - - - -
033ba59c by sheaf at 2026-10-15T04:55:44-04:00
Make exprFreeVars deep
exprFreeVars used to be a shallow free-variable finder (it didn't look
into kinds), but most callers wanted it to be deep. In particular,
'exprFreeVars' is often used to seed an 'InScopeSet', and that must
contain the /deep/ free variables.
This commit makes it deep, which allows us to get rid of calls to
'closeOverKinds' or other workarounds for shallowness in:
- 'GHC.Core.Opt.Simplify.Utils.abstractFloats'
- 'GHC.HsToCore.Binds.dsSpec_help'
- 'GHC.Core.Opt.Arity.etaBodyForJoinPoint'
- 'GHC.Core.FVs.freeVars'
- 'GHC.Core.Lint.lintCoreRule'
We also remove 'deepExprsFreeVarsDSet' and 'closeOverKindsDSet'.
Other places needed a little bit more care, in particular to properly
handle coercion variables free in kinds:
- 'GHC.Core.Opt.Specialise.specHeader' quantifies over the binder of
an unspecialised argument directly, instead of computing the free Ids
of the argument.
- 'GHC.HsToCore.dsWarnRuleShadowing' filters out 'CoVar's.
- 'GHC.Core.Opt.SpecConstr.callToPat' had some ad-hoc logic to compute
argument pattern types and a workaround with 'expandTypeSynonyms'.
That logic is removed in favour of a new 'argsToPats' function which
directly computes the argument pattern types by instantiating the
type of the head of the call pattern.
Fixes #27936
- - - - -
f93d523c by Luite Stegeman at 2026-10-15T04:56:34-04:00
testsuite: Use mkWeakMVar in memo001/memo002
mkWeakPtr in the memo001/memo001 tests created weak pointers
with the MVar box as the key, which is fragile in the presence
of optimization. The fix is using mkWeakMVar, keying on the
primitive MVar# instead.
Fixes #27924 and #27396
- - - - -
8c947573 by Simon Peyton Jones at 2026-10-16T13:11:53+01:00
Improve exprOkForSpeculation
Fixes #27910, which exposed an infelicity in exprOkForSpeculation
The new story is carefully described in new Note [exprOkForSpeculation],
esp (a-c) and (EOKS1).
- - - - -
7dedcf13 by Alan Zimmerman at 2026-10-16T19:03:17-04:00
EPA: Add TTG fields to FamilyInfo
This commit is a simple add, with unused extension fields.
It lays the groundwork for using them for exact print annotations
- - - - -
26b9a8a0 by Arkissa at 2026-10-17T16:04:10+00:00
ghci: Prefer exact source spans in :type-at
Prefer expression types for identical source spans.
Fixes #27412.
- - - - -
70dc4e61 by sheaf at 2026-10-18T18:15:15-04:00
Carefully implement coercion zapping
This commit implements coercion zapping in the rewriter, controlled by
the -fzap-coercions flag (on by default). This significantly reduces
the size of coercions produced when rewriting type family applications,
resulting in much faster compilation. See Note [Coercion zapping]
in GHC.Tc.Solver.Rewrite for an explanation and further details.
The rewriter now keeps track of the `CoVar`s and `CoercionHole`s it uses
when rewriting, which allows computing the dependencies of a zapped
coercion without traversing the coercion the rewriter produced, as
explained in Note [Computing coercion dependencies] in GHC.Tc.Solver.Rewrite.
Accompanying changes:
- Rework how dependencies of 'UnivCo's are tracked, purely for
performance reasons.
We now use the 'UnivCoDeps' datatype instead of '[Coercion]', and
we now insist that 'uco_deps' also contains the CoVars that appear
in the LHS and RHS types of the UnivCo (as a caching mechanism).
- Several performance improvements to the rewriter (e.g. increased
strictness).
- Improvements to the family application cache, including:
- Better documentation.
- Only cache a whole chain of reduction steps.
- Don't put coercion holes in the cache, fixing #27518.
- Allow Core Lint to be called from within the typechecker (and from
within the coercion optimiser).
- Move out "annotation linting" from Core Lint into the general Core
pipeline, to avoid the dependency GHC.Core.Coercion.Opt->GHC.Core.Lint
causing a regression in CountDepsParser due to transitive
dependencies of GHC.Core.Opt.Monad and GHC.Unit.Module.ModGuts.
Fixes #8095 #27336 #27518
Summary of performance numbers
Compile-time byte allocated in GHC's testsuite (0 regressions)
CoOpt_Singletons(normal) ghc/alloc 634,040,332 595,448,728 -6.1% GOOD
FamAppCachePerf(normal) ghc/alloc 495,629,812 191,612,920 -61.3% GOOD
LargeRecord(normal) ghc/alloc 1,226,806,434 966,260,976 -21.2% GOOD
SimplCastPerf(normal) ghc/alloc 160,505,678 148,112,688 -7.7% GOOD
T12227(normal) ghc/alloc 244,668,982 233,037,216 -4.8% GOOD
T12545(normal) ghc/alloc 697,804,842 424,705,152 -39.1% GOOD
T13386(normal) ghc/alloc 422,871,076 35,213,656 -91.7% GOOD
T15703(normal) ghc/alloc 288,402,364 273,692,560 -5.1% GOOD
T26426(normal) ghc/alloc 86,002,052 78,152,104 -9.1% GOOD
T27336(normal) ghc/alloc 498,932,268 35,886,016 -92.8% GOOD
T5030(normal) ghc/alloc 117,057,706 88,785,648 -24.2% GOOD
T5321Fun(normal) ghc/alloc 252,552,628 243,820,176 -3.5% GOOD
T8095(normal) ghc/alloc 768,198,564 127,779,520 -83.4% GOOD
T9872a(normal) ghc/alloc 1,655,675,020 1,406,017,008 -15.1% GOOD
T9872b(normal) ghc/alloc 1,864,180,628 1,644,706,696 -11.8% GOOD
T9872b_defer(normal) ghc/alloc 2,834,585,468 1,657,729,760 -41.5% GOOD
T9872c(normal) ghc/alloc 1,572,573,116 1,354,055,424 -13.9% GOOD
T9872d(normal) ghc/alloc 351,516,004 331,071,424 -5.8% GOOD
TcPlugin_RewritePerf(normal) ghc/alloc 2,063,065,680 1,847,464,272 -10.5% GOOD
Chesskell (github.com/Proxymoron461/chesskell/issues)
Typechecking that the first N plies of kholmovVsBronsteinShort
are a valid chess game:
Plies | GHC 9.14 time/alloc | This commit time/alloc |
-----:|---------------------|------------------------|
2 | 41s/20GB | 0.2s/19MB |
4 | 95s/49GB | 0.3s/25MB |
6 | timed out | 0.6s/522MB |
8 | timed out | 7s/673MB |
10 | timed out | timed out |
Compilation of singletons-base: compile time -28%, allocations -25%
-------------------------
Metric Decrease:
CoOpt_Singletons
FamAppCachePerf
LargeRecord
SimplCastPerf
T12227
T12545
T13386
T15703
T24984
T26426
T27336
T5030
T5321Fun
T8095
T9872a
T9872b
T9872b_defer
T9872c
T9872d
TcPlugin_RewritePerf
-------------------------
Co-Authored-By: Sylvain Henry <sylvain(a)haskus.fr>
- - - - -
3d326d7d by Sylvain Henry at 2026-10-18T18:16:09-04:00
JS: fix stack corruption in h$ap_gen_fast's pushAllRegs (#27624)
The loop added in 9e46990976 ("JS: support more than 128 registers
(#26558)") pushed register N to stack[sp - N - 2] while the switch it
falls through into, and every reader of the h$ap_gen frame, uses
stack[sp - (N - 2)]. Registers >= R32 were therefore written 4 slots
too low: the slots the readers consult were left stale and the frame
below was silently corrupted.
Fix the loop to use the same slot formula as the switch, and add a
regression test: an unknown call to a thunk with 35 argument register
slots, which goes through the generic apply.
Co-Authored-By: Claude Fable 5 <noreply(a)anthropic.com>
- - - - -
6bbca569 by Andreas Klebinger at 2026-10-21T10:01:10+00:00
Fix a few tag inference bugs.
* Treat bottoming functions and nullary join points as functions.
* When generating bytecode don't rely on imported tag sigs.
Fixes #27831, #27841 and #27842.
- - - - -
71808e29 by Sylvain Henry at 2026-10-22T04:50:24-04:00
Add GHC.Internal.Unboxed.Do: do-notation for unboxed values (#27944)
QualifiedDo operators can be representation-polymorphic: a do-block is
expanded into ordinary applications before typechecking, and the only
check on a bound variable is the deferred fixed-runtime-rep check. A
representation-polymorphic (>>=) cannot be defined directly, though,
because its body would bind a variable of unknown representation.
The new module provides such operators for State#-passing code as
methods of a class indexed by RuntimeRep, with one instance per
representation. With optimisation the dictionaries disappear and a
block compiles to the usual nested case expressions:
Ubx.do { x <- readWordArray# mba 0# -- x :: Word#
; writeWordArray# mba 1# x -- unit actions are statements
; Ubx.pure x }
Also add users guide documentation and tests.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
33247780 by Sylvain Henry at 2026-10-22T04:50:24-04:00
Bignum: use Ubx.do for State#-passing code (#27944)
Rewrite the State#-passing code of the GHC.Internal.Bignum modules
(Primitives, WordArray, BigNat, Natural, Integer, Backend.Native,
Backend.GMP) with the qualified do-notation of GHC.Internal.Unboxed.Do.
Nested case chains such as
case newWordArray# sz s of { (# s, mwa #) ->
case act mwa s of { s ->
unsafeFreezeByteArray# mwa s }}
become
Ubx.do
mwa <- newWordArray# sz
act mwa
unsafeFreezeByteArray# mwa
The optimised Core is unchanged (compared per top-level binding).
BigNat now enables MonoLocalBinds: local loops written with Ubx.do
must stay monomorphic in the state type, otherwise GHC does not turn
them into join points.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
593f5f5b by Sylvain Henry at 2026-10-22T04:51:16-04:00
JS: remove archive padding after wasm objects (#25665)
On Darwin hosts, emar (llvm-ar) writes archives in the Darwin format when
the first member is not a known object file, which is the case for the
archives of the JS backend. This format pads each member to 8 bytes with
'\n' and includes the padding in the member size. Wasm objects do not
accept trailing bytes: wasm-ld failed with "section too large".
The JS linker now removes this padding when it extracts a wasm object from
an archive. In addition, Hadrian passes --format=gnu to emar for the JS
target. See Note [Wasm objects in Darwin archives].
Also document the format of Cc (wasm) objects in Note [Cc object format].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
13dff5d0 by L0neGamer at 2026-10-22T21:37:31-04:00
add options for resizing bytearrays (#27244)
add five mutable bytearray resizing operations
for various kinds of pinnedness and aligning.
- prefer unpinned when allocating new array (``resizeMutableByteArrayPreferUnpinned#``; the ``resizeMutableByteArray#`` default)
- prefer pinned when allocating new array (``resizeMutableByteArrayPreferPinned#``)
- prefer aligned and pinned when allocating new array (``resizeMutableByteArrayPreferAlignedPinned#``)
- prefer same as input bytearray when allocating new array (``resizeMutableByteArrayKeepPinnedness#``)
- ensure the output array is aligned and pinned after operation (``resizeMutableByteArrayMakeAlignedPinned#``)
- - - - -
0c17201c by Sylvain Henry at 2026-10-22T21:38:23-04:00
JS: implement performMinorGC and performBlockingMajorGC (#28012)
GHC.Internal.System.Mem imports three C entry points: performMajorGC,
performGC (for performMinorGC) and performBlockingMajorGC. The JS RTS
only defined h$performMajorGC, so calling performMinorGC or
performBlockingMajorGC threw "ReferenceError: h$performGC is not
defined" at runtime.
The JS RTS has a single non-generational collector, so both missing
entry points are now aliases of h$performMajorGC.
Add a test that calls every GC entry point of System.Mem.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
7a631ff2 by L0neGamer at 2026-10-23T09:11:39-04:00
Mon(a|oi)d of No (Return|Mappend) progress (!15795)
Make non-canonical definitions of return and mappend
non-suppressible errors, and make canonical definitions
of those methods warnings.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/328
- - - - -
14656fd4 by Simon Jakobi at 2026-10-23T09:12:27-04:00
Cmm: keep the CBE substitution idempotent
When blocks are merged over multiple rounds during common block
elimination, a block that won a merge in an earlier round can still
lose a merge in a later round. The substitution map (Subst) used to
record this as a chain: the earlier loser mapped to a block that was
itself eliminated. In PLT terminology, the substitution became
*non-idempotent*. Applying such a substitution with a single lookup
left edges to unreachable blocks in the Cmm graph, eventually leading
to a setInfoTableStackMap panic (#27368).
With this patch, each round's fresh substitutions are applied to the old
ones as they are added (extendSubst), so every eliminated block maps
directly to its final replacement and the substitution stays idempotent.
Fixes #27368.
Assisted-by: Claude Fable 5.1
- - - - -
92848e61 by Evgeny Malyshev at 2026-10-23T20:26:04-04:00
hadrian: Include transitive dependencies in Haddock builds
Haddock needs indirect dependency interfaces to resolve references to
definitions outside a package's direct dependencies. Expose Cabal's
configured dependency closure through ContextData and use it alongside
the direct list, preserving direct-interface precedence.
Bump Shake's cache version for the serialized oracle change. Add a
Hadrian selftest requiring template-haskell's indirect ghc-prim interface.
Fixes #25850.
Fixes #27786.
Assisted-By: OpenAI Codex
Metric Increase:
haddock.Cabal
- - - - -
5e8ae81b by Zubin Duggal at 2026-10-23T20:26:47-04:00
WinIO: Don't confuse Win32 errors and NTSTATUS codes
WinIO misinterpreted NTSTATUS codes as Win32 errors, and had some ad hoc logic to deal with this.
However, this logic was incomplete and resulted in the mishandling of results of certain I/O operations
(see testcase).
Now the `ErrCode` argument in `CompletionCallback` is always the Win32 error code,
and we convert the NTSTATUS using RtlNtStatusToDosError.
Also when an overlapped/async operation such as ReadFile fails immediately,
with a Win32 error such as ERROR_BROKEN_PIPE, we don't get a further completion
notification, so we never recorded the failure. This worked by coincidence
earlier, because `STATUS_PENDING` happened to have the same numerical code as
`ERROR_NO_MORE_ITEMS`, but it doesn't now that we translate `STATUS_PENDING`
into the correct Win32 error code (`ERROR_IO_PENDING`). Fix this by using
the Win32 error value we obtained when an operation returns `STATUS_PENDING`.
Fixes #27971
- - - - -
c42ed66a by Martijn Bastiaan at 2026-10-24T16:00:42+02:00
Add single-threaded test for #27526 + #27123
Issue #27526 is a duplicate of #27123, which has already been fixed in
HEAD. The proposed patch in the former carries a "nicer" regression test
in that it doesn't rely on multi-threading to trigger.
Closes #27526
- - - - -
7f73f515 by Simon Peyton Jones at 2026-10-24T17:29:19-04:00
Refactor QuickLook a bit
This MR simply refactors QuickLook a bit. In particular, it
simplifies `tcApp`, and moves shared code into `finishApp`.
It also adds `Note [QuickLook: arguments before result]`
responding to #26599.
There should be no user-visible changes, except perhaps in error messages,
which improve marginally.
For some reason T24984 compiles 8% faster. I'll take the win!
Metric Decrease:
T24984
- - - - -
a4a3a964 by Alan Zimmerman at 2026-10-24T17:30:03-04:00
EPA: Use AnnList for XClosedTypeFamily
We now have TTG annotations for FamilyInfo.
Make use of it to store the AnnList annotations for a closed type
family.
- - - - -
953e4c7f by sheaf at 2026-10-26T18:19:10-04:00
Rework LogQueue to be a proper queue
Now 'LogQueue' uses a 'TQueue' with a separate 'TVar' to indicate
whether the log queue is finished logging, instead of the previous weird
data representation using a reverse-order '[Maybe Msg]' with 'Nothing'
denoting the end of the queue.
- - - - -
ec29c5fa by Rodrigo Mesquita at 2026-10-26T18:19:10-04:00
Refactor GHC.Driver.MakeAction
Pull out of 'runParPipelines' the logic for creating a 'MakeEnv' ready
to be used by multiple threads, as that will be useful for downsweep as
well (which doesn't fit the 'runPipelines' flow), rather than being just
for upsweep.
The code is moved and re-structured to match the export list, simplify
the sequentiality checks previously both in 'runPipelines' and
'runAllPipelines', which were weirdly similar and confusing; into the
two part step where we need these checks: (1) to construct the MakeEnv,
(2) to run the MakeActions in parallel. These two steps are separate and
used to be too mixed up.
Some additional little simplifications or clean ups here and there.
- - - - -
3fb22073 by Rodrigo Mesquita at 2026-10-26T18:19:11-04:00
Refactor GHC.Driver.Downsweep in preparation for parallel downsweep
Pure refactor to improve the code to facilitate implementing parallel
downsweep in the next commit.
This commit puts a MakeEnv into the DownsweepEnv, gives the fields
proper names and uses RecordWildcards to simplify, rather than passing
around all diagnostic wrappers, driver-message-things and using 10s of
positional fields.
No behavior changes here!
- - - - -
52f385a7 by sheaf at 2026-10-26T18:19:11-04:00
Driver: enableCodeGenForTH in load', not downsweep
enableCodeGenForTH modifies the module graph for planning, creating
fresh temporary paths. So it should only be run when we are about to
execute a build plan (e.g. in load'), so that consumers that want to
know facts about the module graph don't go looking for files that don't
exist yet (in particular 'haddock --no-compilation').
- - - - -
82402d14 by sheaf at 2026-10-26T18:19:11-04:00
2-phase Cache/Search Finder monad
This commit restructures the finder abstraction by introducing the
'FinderM' monad, which splits module lookup operations into two phases:
- a cache-only phase, performing no filesystem access,
- from the first cache miss onwards, a search action which may access
the filesystem.
This allows consumers to distinguish between quick cached results versus
more expensive filesystem search operations.
- - - - -
5c302b40 by sheaf at 2026-10-26T18:19:11-04:00
Separate Home/External finder caches
The caches for home modules and modules from external units have
different lifetimes, needing to be invalidated at different points.
This commit moves the cache for modules from external units into the
'UnitState' type, which keeps the cache correct whenever package flags
or package databases change (setSessionDynFlags, :set -package ...,
Backpack's addUnit).
This also makes it easier to clear the cache of home modules, as they
are now stored separately (obviating the 'isUnitEnvInstalledModule'
check we used to perform).
- - - - -
605fbb96 by sheaf at 2026-10-26T18:19:11-04:00
Add known home modules to the finder cache
The finder looks in the file system for the on-disk source that
corresponds to a Haskell module name. There are two kinds of modules
where we need to bypass this search:
- a file passed directly in the command line, which may not be in any
search path and whose module name may differ from the file name;
- Backpack signatures and modules, which do not exist as files at all.
This commit handles these two situations by adding an immutable
'KnownHomeModules' in the finder cache, which is always consulted first
before doing any search.
This removes the ad-hoc imperative logic which relied on mutating the
finder cache at careful points.
'setModuleGraph' now also takes the known home modules, so that the
module graph and the known home modules are always set consistently.
See Note [Known home modules] in GHC.Unit.Finder.Types.
- - - - -
82718f44 by sheaf at 2026-10-26T18:19:11-04:00
Make 'UnresolvedImport' into a suitable cache key
The goal of this commit is to make 'UnresolvedImport' suitable for use
as a cache key. Specifically, during downsweep we want to be able to
cache module resolution queries. We want to do this using some kind of
map, e.g. (roughly speaking):
Map UnresolvedImport ResolvedImport
For this to work, 'UnresolvedImport' must contain **precisely** the
input data to each resolution computation. In other words:
1. If something changes that materially affects resolution, it must
be stored in the cache key.
2. If changing some input does not materially affect the outcome,
then it must not be stored in the cache key.
To satisfy (1), we change 'UnitNode' to also keep track of the home
unit in whose unit state the unit's dependencies were looked up.
For (2), 'ImportResolution' now stores a 'ModuleLookupScope' instead of an
'UnresolvedImportOrigin'. Plugin imports are expressed with a new
'LookupPlugin' scope. The source location of an import, which is
immaterial to the resolution, is stored out of band outside
'UnresolvedImport', in 'ModSummary'.
- - - - -
d4635c7c by sheaf at 2026-10-26T18:19:11-04:00
Add GHC.Data.Dependent
This commit adds a minimal implementation of dependent sums
('Some', 'DSum') and dependent maps ('DMap').
The implementation is not entirely performance optimal, as there are a
few extraneous allocations compared to the full-blown implementation in
the 'dependent-map' package. For our use case (caching downsweep
computations), this does not matter much.
See GHC.Data.Dependent.
- - - - -
6759533e by sheaf at 2026-10-26T18:19:11-04:00
Driver: structured concurrent worker abstraction
This commit introduces a structured concurrency framework in the style
of the 'ki' library: a collection of threads within a scope.
We implement two kinds of concurrent workers on top of this framework:
- Independent workers cannot wait for one another at all. The only
scheduling operation is to wait for quiescence.
- Coordinating workers declare an STM readiness condition (waiting on
other workers to complete) which gates their start.
See Note [Deterministic concurrent workers] in GHC.Driver.Concurrency.
This commit ports upsweep to this new framework, with downsweep being
left as subsequent work.
Further changes along the way:
- Refactoring of how concurrency is acquired to avoid the footgun of
trying to use a no-op 'AbstractSem' as a lock in the serial case.
- The "re-run with -j1" logic for semaphore opening errors no longer
triggers on late semaphore failures (part-way through a lengthy
computation).
- Logger threads are properly cleaned up on exception, with each
concurrent worker's log queue and local TmpFs properly bracketed.
- The 'GhcMessage -> AnyGhcDiagnostic' and 'Maybe Messager'
arguments of 'depanalE', 'depanalPartial' and 'downsweep', which
were all dead in practice, have been dropped.
- Concurrent logging has been completely overhauled. Each worker has
its own log queue. Workers whose logs are printed as we go are
spawned in the order in which their logs must be printed, now using
a TQueue instead of the old complicated LogQueueQueue mechanism.
'logThread' is replaced by 'withLogPrinter', which runs the thread
that prints the log queues within a concurrent worker scope.
These changes allow us to fix issues with the exception handling:
we now always flush remaining log queues before exiting (even when
the action throws an exception), and exceptions that arise while
printing are properly rethrown. This fixes #28009.
- - - - -
38a99006 by sheaf at 2026-10-26T18:19:11-04:00
Rule-based deterministic concurrent downsweep
This commit rewrites downsweep as a single query-answering rule
(see 'DownsweepRule') that can be executed by concurrent worker threads.
The design allows every expensive operation (preprocessing files with CPP,
parsing headers, reading interfaces) to be performed concurrently
according to the -j<N>/-jsem flags.
See Note [Rules-based downsweep] in GHC.Driver.Downsweep.
The rules are run by "GHC.Driver.Concurrency.runRules" in a demand-driven
way: each worker can demand other workers to run, but never wait on
another worker. Every piece of work is done at most once.
Fixes #27514
Memory usage can increase due to doing more work concurrently:
-------------------------
Metric Increase:
MultiComponentModulesRecomp
MultiComponentModulesRecomp100
mhu-perf
-------------------------
- - - - -
9fa7b7be by sheaf at 2026-10-26T18:19:11-04:00
Acquire/release semaphore tokens more readily
This commit reworks GHC.Driver.MakeSem to use the scoped worker
abstraction of GHC.Utils.Concurrent.Scope. This allows us to get rid of
a lot of the tricky logic in GHC.Driver.MakeSem involving manual
exception handling, thread spawning and lifetime management, etc.
The main user-visible change is that token acquisition is no longer
rate limited (due to a bug, there previously was a 1s rate limit on
acquisition of semaphore tokens), with the release debounce period
shortened from 1s to 10ms.
Other changes:
- With -jsem, the number of capabilities is now capped at the number
of processors, bringing it in line with the -jN behaviour.
- Pending jobs whose wait for a token is interrupted by an exception
are now withdrawn from the jobserver, instead of acquiring a token
that it hung onto without doing useful work.
Fixes #27763
- - - - -
c83c6733 by Alan Zimmerman at 2026-10-26T18:19:55-04:00
EPA: Update AnnClsInstDecl to contain AnnList
It was already separately tracking the '{', '}' and leading ';' values.
This aligns it with layout-introducing parser productions ('vocurly'),
so the layout processing can be handled uniformly
- - - - -
ac870ad5 by Simon Jakobi at 2026-10-28T04:40:42-04:00
X86 NCG: use 32-bit POPCNT for sub-word popcounts
A 32-bit write zero-extends the result to the full register, so we
don't need to emit additional code for this.
We also skip emitting zero-extension instructions for the argument
when it is already visibly zero-extended.
For the byte-wise popcount loop from #24813, this shrinks the popcount
sequence from 5 instructions to 3.
Assisted-by: Claude Fable 5.1
- - - - -
53087373 by Facundo DomĆnguez at 2026-10-28T04:41:32-04:00
Use a ShortByteString in Serialized instead of [Word8]
This makes the in-memory representation 40x more compact for all values
stored in annotations.
A test is added to measure the representation size of annotations
specified in the compiler input.
The GHC API is modified. All functions that previously handled annotations
in [Word8] form now use ShortByteString. The following definitions have
modified types:
* GHC.findGlobalAnns
* GHC.Tc.Gen.Splice.getAnnotationsByTypeRep
* GHC.Core.Opt.Monad.getAnnotations
* GHC.Core.Opt.Monad.getFirstAnnotations
* GHC.Types.Annotations.deserializeAnns
* GHC.Types.Annotations.findAnns
* GHC.Types.Annotations.findAnnsByTypeRep
* GHC.Serialized.Serialized
* GHC.Serialized.toSerialized
* GHC.Serialized.fromSerialized
* GHC.Serialized.serializeWithData
* GHC.Serialized.deserializeWithData
* GHCi.Message.ReifyAnnotations
Fixes #28002.
- - - - -
cc533b66 by Sasha Bogicevic at 2026-10-31T09:18:15-04:00
Don't report -XStrict-generated bangs under -Wredundant-bang-patterns
The -XStrict flag causes the desugarer to insert bang patterns.
These are not user-written, so -Wredundant-bang-patterns must not
report them.
To achieve this, the desugarer now tracks whether it is desugaring
compiler-generated code (similar to the typechecker's 'tcl_in_gen_code').
Bangs inserted by -XStrict are given generated spans, which suppresses
the "redundant bang" warnings without otherwise affecting pattern-match
warnings.
Fixes #27323
- - - - -
13d38047 by Luite Stegeman at 2026-10-31T09:19:11-04:00
rts: tombstone Weak# copies that lose an evacuation race (#23160)
Mark the losing copy of a Weak# during an evacuation race in parallel
GC with stg_DEAD_WEAK_info. This ensures that the nonmoving GC
doesn't follow dangling pointers, leading to crashes.
Fixes #23160
- - - - -
63347328 by Zubin Duggal at 2026-10-31T09:19:52-04:00
ghci: Drop GHCi's exception context when rethrowing in ghc -e
Fixes #27847.
- - - - -
a85fef3f by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context in modifyIOError
Fixes #27851.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/446
- - - - -
1d60b591 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context in mapException
Fixes #27851.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/446
- - - - -
3c029a1b by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in Handle reads
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
ab2b317a by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in hClose
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
f5abf277 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in Windows openFile
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
d842c672 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in executablePath
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
c5a8bb9f by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Simplify a tc-trace which could crash the compiler
The trace formatted an error message, which prematurely
read the ExpType in a FunResCtxt.
Solution: don't put call the error message formatting
when tc-tracing.
- - - - -
ab49b1d2 by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Tiny comment change to uniqAway
- - - - -
6efe4ba3 by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Make niFixSubst idempotent
I discovered (when fixing #27994) that `niFixSubst` didn't actually
generate an idempotent subsitution despite its claims. It could
return a substitution that mentions domain variables on in its range,
when those variables are hidden inside the kind of a type variable
occurrence. As a result it can generate ill-kinded types. Boo!
The fix is simple, and uses deep substitution.
See Note [Finding the substitution fixpoint]
I don't think it actually /caused/ any bugs, so there is no
regression test.
- - - - -
3b60ae7e by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Fix a nasty bug in fundeps
This MR fixes #27994, which turned out to be very tricky.
See Note [Exploiting closed type famililes], especially (CF7). I was
ending up with TyVars (not TcTyVars) in the solver, because the
substitution computed in `getRelevantBranches` mixed the two.
The code was just too clever. I ended up simplifying it quite a bit.
For /closed/ families we no longer call `trimQtvs` (was `trim_qtvs`).
Open families still do use `trimQtvs`. See Note [trimQTvs]
This patch also fixes one other buglet in the same code.
* Over-saturated type families were being mis-handled.
See the new use of `saturatedFamApp_maybe`.
- - - - -
e4610f2d by Facundo DomĆnguez at 2026-10-31T09:21:24-04:00
Have haddock --incremental look for the module in -this-unit-id
- - - - -
bc6c0db6 by sheaf at 2026-10-31T09:22:20-04:00
mightBeFunTy: hotfix for #27979
ce01ccb6 refactored 'GHC.Types.RepType.mightBeFunTy' to look through
unary classes. That change introduced the helper function 'unwrap_type'
which was supposed to always return an unwrapped type, but its fallback
equation mistakenly returned the original type. This caused the
subsequent 'tyConAppTyCon_maybe' to fail in cases where it should
succeed (e.g. looking through foralls).
In this commit, we move all the unary class unwrapping logic into
'unwrapType' where it belonged from the start, and update the
documentation of 'unwrapType' to better explain what it should be used
for (#26695).
Fixes #27979 #26695
-------------------------
Metric Increase:
T5642
-------------------------
- - - - -
233cce46 by Alan Zimmerman at 2026-10-31T09:23:01-04:00
EPA: Tidy up ExactPrint.markAnnListA'
It takes an action which can modify the AnnList, but this
is never used. So remove it.
- - - - -
3594a908 by Sylvain Henry at 2026-10-31T09:23:51-04:00
gitmodules: ignore dirty libffi-clib submodule (#26785)
`./boot` runs autoreconf in libraries/libffi-clib, which leaves
`configure~` behind and rewrites the tracked `aclocal.m4` whenever the
local automake version differs from the one that generated it. Every
checkout then looks dirty. Ignore working-tree changes in the submodule
(`ignore = dirty`); a changed submodule commit is still reported.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
341223c0 by Rodrigo Mesquita at 2026-10-31T09:24:33-04:00
refactor: Keep the interactive Ids directly rather than Name
Removes things like
names <- map idName ids
map (\i -> let id = find (\x -> i==idName x) names) idso
and is more straightforward because there's less state going around (no
more updating HscEnv as an output)
It also kills `printTypeOfNames` completely, since now we just have the
Ids. No longer `lookupName` names to get back the ids...
```
printTypeOfName :: GHC.GhcMonad m => Name -> m ()
printTypeOfName n
= do maybe_tything <- GHC.lookupName n
case maybe_tything of
Nothing -> return ()
Just thing -> printTyThing thing
```
now is just `printTyThing . AnId`
Also:
```diff
- tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
- docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
+ docs <- mapM pprTypeAndContents idsSorted
```
(and yes, in ExecBreaks there are only Ids, no TyThings, bc they are
only constructed by the interpreter execution which can only bind ids.
for TyThings use runDecls which doesn't return execBreaks.)
There's some care to be had to make sure we use the "most refined" Ids,
whereas when using `Name`s we'd always fetch the most refined Id from
scratch.
Fixes #28052
- - - - -
54cf3c1e by sheaf at 2026-11-03T07:00:23-05:00
Consolidate all CPU feature handling
This commit introduces GHC.Platform.CpuFeatures which consolidates all
of the logic for implications between CPU feature flags (mainly X86):
- DynFlags now only records the set of -m<feature> flags that were
passed, as an EnumSet CpuFeature. That keeps it a simple record of
the flags the user passed, with no post-processing.
- GHC.Platform.CpuFeatures.initCpuFeatures turns this set into a
CpuFeatures value, applying all implications and the per-architecture
baseline. This is the single home for all of the feature implication
logic.
Some datatypes were reworked to better reflect the implication
structure in the types, e.g. SseAvxVersion has a strategically
placed 'FMA' boolean.
- The NCG, LLVM backend, StgToCmm, CPP defines and LLVM -mattr
flags all consult CpuFeatures, via targetCpuFeatures.
See Note [CPU features], which replaces
Note [Implications between X86 CPU feature flags].
Behaviour changes:
- x86 feature flags (-msse3, -mavx, -mavx512*, -mgfni, ...) passed
when targeting a non-x86 architecture no longer cause x86 CPP
macros (__SSE3__, __AVX512BW__, __GFNI__, ...) to be defined, nor
x86 attributes to be passed to LLVM.
- Error messages reported when required CPU features are not enabled
now print out the minimal set of flags required
(e.g. "-mavx512vl" rather than "-mavx512f -mavx512vl").
- - - - -
9af64305 by Luite Stegeman at 2026-11-03T07:01:23-05:00
rts: move stack check to the start of the stg_unpack_cstring thunks
fixes a deadlock
see #27272
- - - - -
a2208b21 by Simon Jakobi at 2026-11-03T07:02:05-05:00
Cmm: exclude the entry block from common block elimination
a1d8139054c had fixed #27722 only partially, because it didn't prevent
elimination of the entry block in later rounds, where the entry block is
no longer guaranteed to come first.
To close this loophole, we exclude the entry block from the CBE merge
logic. See Note [Retain entry block during common block elimination] for
details.
This also deletes a misleading comment regarding unreachable blocks: the
control-flow optimiser doesn't actually guarantee that no unreachable
blocks reach CBE.
Fixes #27722.
Assisted-by: Claude Fable 5.1
- - - - -
37ad4710 by Alan Zimmerman at 2026-11-03T07:02:46-05:00
EPA: Use AnnList for GADT declarations
Continuing the process of using AnnList to capture parser layout
- - - - -
56757900 by Sebastian Graf at 2026-11-04T20:36:47+01:00
Documentation for the Core data constructors
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
9f57c265 by Sylvain Henry at 2026-11-06T06:46:15-05:00
ghc-internal: avoid unnecessary allocations in bignum division (#27231)
Avoid unnecessary allocations in bignum division in the Haskell (native)
backend. The long-division loop used to allocate a fresh BigNat for the
partial product on every iteration, plus one more per quotient-digit
correction; it now subtracts the partial product in place and
materializes nothing.
The quotient-digit estimate is also refined against the second-highest
divisor word, so the add-back correction runs at most once per
iteration.
bignat_quotrem_normalized now requires a divisor of at least 2 words, so
bignat_quotrem dispatches 1-word divisors to bignat_quotrem_word.
See Note [Knuth division loop] and Note [Fused multiply-subtract for
long division] in GHC.Internal.Bignum.Backend.Native.
Measured on the new T27231 perf test (10000 native-backend 8192/2048-bit
Integer quotRem calls): bytes allocated drops from 305 MB to 52 MB (-83%).
Improvement on CI (x86-64-linux-deb13-int_native):
space_leak_001(normal) run/alloc 12,492,185,536 9,073,055,928 -27.4% GOOD
Metric Decrease:
space_leak_001
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
c5b80f4e by mangoiv at 2026-11-06T06:46:57-05:00
ci: build and test stage
Split up CI in a build and test stage:
1. in the build stage, just produce a bindist as well as running the
stage1 tests
2. in the test stage, install the bindist, then run the testsuite with
out of tree args
- - - - -
e4b1c892 by mangoiv at 2026-11-06T06:46:57-05:00
ci: reorder packaging and testing stages
- - - - -
19901b41 by mangoiv at 2026-11-06T06:46:57-05:00
ci: out of tree compiler does not imply no hadrian being available
- - - - -
83a860a7 by mangoiv at 2026-11-06T06:46:57-05:00
ci: don't do msys deps check on stage1 compiler
- - - - -
abf5b3af by mangoiv at 2026-11-06T06:46:57-05:00
testsuite: allow metric decreases on windows
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13253-spj
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
9185f1ab by mangoiv at 2026-11-06T06:46:57-05:00
ci: stop using ellipses in testsuite output and output env before invoking hadrian
- - - - -
bf9ece2b by Simon Jakobi at 2026-11-06T06:47:42-05:00
testsuite: Skip the changelog-d test in CI
Full-build validate jobs run the whole testsuite and thus repeated the
changelog validation that the dedicated lint-changelog job had already
reported in the early tool-lint stage.
Skip the test when GITLAB_CI is set, making lint-changelog the only CI
check of changelog.d while keeping the test available in local
testsuite runs.
Fixes #27325.
Assisted-by: Claude Fable 5
- - - - -
ef6adb30 by ARATA Mizuki at 2026-11-06T06:48:31-05:00
testsuite: Mark T367_letnoescape fragile for the optllvm way
It was marked broken, but it is now unexpectedly passing on aarch64-linux-deb13-validate+llvm.
Marking it fragile for now.
See #7292
- - - - -
1db5f9d7 by Rodrigo Mesquita at 2026-11-06T06:49:13-05:00
interp: Make resumeExec and ExecBreak use `Resume` directly
Previously, `Resume` contexts were just put directly in the global
interactive environment state, so they were only accessible through it.
However, in the context of multi-threaded debugging, in that many
threads may hit breakpoints, it no longer suffices to have a global
linear list of breakpoints hit. We need a per-breakpoint Resume context
and need to be able to wield it directly rather than going through a
global context.
The driving changes of this commit are:
- Put the Resume data in ExecBreak
- Make resumeExec receive a Resume as an argument
This also simplifies the interpreter in that we no longer necessarily
rely on the global interactive state to resume a thread. We can do it
directly from the ExecBreak.
The interactive context still maintains a stack of resumes, but
`resumeExec` can no longer pop the resume it resumes off of the
breakpoints stack, since it is no longer guaranteed to be resuming the
first in that list. Hence, callers of `resumeExec` must update ic_resume
on their own.
Fixes #28058
- - - - -
fd00a88c by Rodrigo Mesquita at 2026-11-06T06:49:54-05:00
Per-thread break-on exception (TSO_STOP_ON_EXCEPTION)
The `-fbreak-on-exception` flag allows the interactive interpreter to stop
when a synchronous exception is raised.
However, this is a global toggle backed by a global variable in the RTS
(rts_stop_on_exception) which is not compatible with a multi-threaded
debugger where we may want to stop if some threads raise a synchronous
exception but not other.
This commit makes -break-on-exception similar to step-next and step-out
where there is a per-thread toggle on each TSO (TSO_STOP_ON_EXCEPTION),
and that break-on-exception set in EvalOpts when resuming a statement
only affect the thread being resumed.
Fixes #28068
- - - - -
d735b507 by Andrea Vezzosi at 2026-11-06T06:50:35-05:00
driver: Don't let -dynamic unset -fsplit-sections
`addWay' WayDyn` used to unset Opt_SplitSections, so -fsplit-sections was
ignored if it came before -dynamic, but worked if it came after.
The -fsplit-sections -dynamic combination has legitimate uses, e.g. an
executable can be linked dynamically against libraries and still have dead code
from its own sources to eliminate. Or the same objects could be used for both
static archives and shared objects.
The removal of Opt_SplitSections was also motivated by problems on Darwin.
It is now done in `makeDynFlagsConsistent` instead, see Note [Split sections are not
supported on Mach-O].
For consistency, we also keep Opt_SplitSections when `dynamicNow` is activated.
There is a cost of larger .dyn_o (but not .so) files and slower link times (esp.
with ld.bfd), but does not seem significant enough to warrant special casing.
Fixes #28061
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
10e36bd2 by Alan Zimmerman at 2026-11-06T06:51:18-05:00
EPA: Use AnnList in AnnClassDecl
Capture parser layout
- - - - -
20334e1d by sheaf at 2026-11-06T06:52:06-05:00
Avoid panic in 'solveImplicationsUsingUnsatGiven'
Commit 52a4d1da refactored this code to use 'setWantedDict' which panics
for equality constraints. This commit fixes that by explicitly handling
HoleDest.
Fixes #28081
- - - - -
0423f413 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: add tests for the IO manager lock-up of #21969
T21969a 'closeFdWith' takes every 'EventManager''s 'callbackTableVar'
inside 'uninterruptibleMask_' and only puts them back on the paths
that do not throw, so a throw from 'closeFd_' leaves those MVars
empty for good. Afterwards every 'threadWaitRead' and
'closeFdWith' on an fd in the same bucket blocks forever.
T21969b 'closeFdWith' runs the fd's callbacks while asynchronous exceptions
are uninterruptibly masked, so a callback that blocks makes the
thread calling it permanently unkillable.
T21969c 'closeFd_' drops the registrations before telling the backend to
forget the fd, so when the backend throws the fd is never closed
and the threads waiting on it are never woken.
T21969d the cleanup handler of 'threadWait' calls 'unregisterFd_', which
throws on backend errors. It runs inside the handler for the
asynchronous exception being delivered, so its exception replaces
that one: 'killThread' returns but 'ThreadKilled' never arrives.
T21969e an exception from re-arming an fd escapes the poll loop, and 'loop'
turns it into 'cleanup mgr': the 'EventManager' of that capability
is shut down and every thread using it is left blocked. This is
the lock-up of #21969 itself.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5c197e2e by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Make the IO manager cope with errors from the polling backend (#21969)
Three changes in 'GHC.Internal.Event.Thread': 'closeFdWith' puts every
'callbackTableVar' back on the paths that throw too and no longer skips the
callbacks when 'close' fails, those callbacks now run under the 'mask_' of
'close_loop' rather than uninterruptibly masked, and the cleanup of
'threadWait' ignores a failure from 'unregisterFd_'.
This fixes T21969a, T21969b and T21969d, and clears their expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cb765ded by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let backend errors abandon the close of a file descriptor (#21969)
'closeFd_' and 'closeFd' now ignore errors from telling the backend to forget
the fd: the registration is being torn down and the error says it is already
gone. 'registerFd_' still reports them (!10643), where the caller has to
learn that the registration did not happen. Both also test
'I.elEvent oldEls /= mempty' rather than 'oldEls /= mempty'.
This fixes T21969c, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
9073bc43 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let a backend error take down a capability's IO manager (#21969)
A failure to re-arm an fd in 'selectCallbacks' is now handled the way
'registerFd_' handles one (!10643): the registrations are taken back out of
the callback table and returned, so their callbacks run and the waiting
threads find out for themselves instead of hanging. Checked on aarch64 Linux
(epoll) and aarch64 macOS (kqueue), 10 runs each way.
This fixes T21969e, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cdff4e76 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let the deregistration of threadWaitSTM throw either (#21969)
'threadWaitReadSTM' and 'threadWaitWriteSTM' return the action that gives up
interest in the fd as the second component of their pair, and it was
return (waitAction, unregisterFd_ mgr reg >> return ())
'unregisterFd_' talks to the polling backend, which throws on errors such as
ENOENT and EBADF -- which is how a backend reports an fd it no longer knows,
once that fd has been closed without going through 'closeFdWith'.
That is the same shape as the cleanup of 'threadWait', which the rest of this
series made quiet, and it is the same on both counts. There is nothing to
decide: the registration is being abandoned, and "the backend does not know
this fd" is the state the action is trying to reach. And it does harm: the
action is what a caller uses from the cleanup of a 'bracket', where an
exception out of it replaces whatever was being propagated.
It now goes through 'quietUnregisterFd', as the cleanup of 'threadWait' does,
and that function's comment covers both callers.
T21969f covers it, and is deterministic on both backends: dropping the only
registration changes the event set, so 'unregisterFd_' always reaches the
backend.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
a7ed305b by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: let T21969 run on FreeBSD, and unmark it (#21969, #25512)
T21969 now carries the descriptor from 'createPipe' instead of recovering it
with 'handleToFd', which rejects the 'DuplexHandle' that FreeBSD's
bidirectional pipes become and killed the test in setup there (#25512). The
expect_broken goes with it: with the descriptor problem out of the way the
test times out on master, so it can only be unmarked on top of this series.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
3074ae61 by Sylvain Henry at 2026-11-08T10:21:50-05:00
rts: heap census counts every small pinned object
Blocks of small pinned objects carry BF_LARGE as well as BF_PINNED but
hold many objects. heapCensusChain treated every BF_LARGE block whose
first object is an ARR_WORDS as holding that single object, a workaround
for the slop left by shrinkMutableByteArray# (#11627). So every heap
profile mode under-reported pinned byte arrays, i.e. ByteString payloads.
Shrinking now writes a slop marker that skipSlop understands (#19048,
#27585), so the block walk is safe for large and pinned blocks alike.
The block that a capability fills with small pinned objects stays
attached to the capability until it is full (see allocatePinned), so it
is on no generation list and the census never saw its objects. heapCensus
now walks cap->pinned_object_block too.
A pinned block is kept or freed as a whole (#28005), so dead pinned
objects are counted until their block is freed. T7275 gains one sample in
which its dead small arrays still show. The user guide and changelog
document this.
T7257 retains most of its pinned blocks and takes a census at every GC
(+RTS -i0 -hT), so walking every pinned object made it 7x slower and it
hit the CI timeout. It now runs 1000000 iterations instead of 5000000.
Metric Decrease:
T7257
Fixes #28000
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
16fd075a by Sylvain Henry at 2026-11-08T10:22:39-05:00
rts: fix GC CPU time accounting with idle GC threads (#26169)
stat_endGC summed gc_end_cpu - gc_start_cpu over every GC thread, but
only the threads that take part in a collection set these fields, and
new_gc_thread did not initialise them. With -qn below the capability
count, the first collection after setNumCapabilities added garbage to
the GC CPU time.
Let each participating thread add its own CPU time to an accumulator
in stat_endGCWorker, and let stat_endGC take the total. This removes
the loop over gc_threads, the reset from #21082 and the gc_end_cpu
field. Also drop the unused gc_end_elapsed field.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
0ef732e2 by Sylvain Henry at 2026-11-08T10:23:30-05:00
Serialized: encode numbers with LEB128
serializeWithData used the Binary instances of Data.Binary for the
numbers in a ConstrRep. They have a fixed width: 8 bytes for the
constructor index (an Int) and 5 bytes for a small Integer. Each
element of a [Int] cost 15 bytes.
Now the constructor representation is one unsigned LEB128 number that
also contains the index of an algebraic constructor, and the payloads
(Integer, Rational, Char) are LEB128 encoded. Most constructors take
one byte, and small numbers two. See Note [Serialized encoding].
Sizes measured by the T16841 test:
[1..100] :: [Int] 1509 -> 338 bytes
"helloworld" 119 -> 31 bytes
2^100 :: Integer 24 -> 16 bytes
Just True 18 -> 2 bytes
3.25 :: Double 11 -> 3 bytes
42 :: Int 6 -> 2 bytes
A new test, SerializedRoundTrip, round-trips values at the boundaries
of the encoding (negative numbers, big Integers, Rationals, Chars).
Follow-up to !16841 (#28002).
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
22344fbc by Sylvain Henry at 2026-11-08T10:24:21-05:00
docs: fix duplicate label in qualified_strings.rst
The file started with the label "multiline-strings", copied from
multiline_strings.rst. Sphinx warned about the duplicate label on every
build. Use the label "qualified-strings" instead.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
b7022624 by Alan Zimmerman at 2026-11-08T10:25:02-05:00
EPA: Use LHsLocalBinds instead of HsLocalBinds
This reverses an earlier change, and brings processing of local binds
into alignement with the exact printing principle that the LocatedA
contents provide the location and extent of the enclosed item,
together with any comments or context-specific trailing items like
commas or semi colons.
The internal TTG extension points only carry exact print annotations
related to printing the item within its bounds.
This change brings back the problem of EmptyLocalBinds, which by
definition cannot have a location. These get a noSrcSpan location,
which is ignored in the exact printing process.
- - - - -
bc2fae45 by Rodrigo Mesquita at 2026-11-08T18:37:40-05:00
Build EvalOpts once per exec rather than per breakpoint stop
We were unnecessarily constructing `eval_opts` in `handleRunStatus`
(which is run many times in a loop until we hit a breakpoint we care
about, e.g. when :steplocal), despite the `eval_opts` being constant
across all these runs.
So, construct `eval_opts` outside `handleRunStatus` and share the value
in all loop calls. The loop always uses the same eval_opts, so no point
in constructing them inside `handleRunStatus` from scratch every time.
I found out about the significance of this re-construction of `EvalOpts`
when I added a record update of `eval_opts` *after* the construction
from scratch inside `handleRunStatus` that regressed allocations
significantly.
This improves the performance of `interpreter_steplocal` on my machine:
Baseline
Test Metric value New value Change
-------------------------------------------------------------------------
interpreter_steplocal(ghci) ghc/alloc 459,845,696 449,843,480 -2.2%
Fixes #28068
- - - - -
ba579288 by Rodrigo Mesquita at 2026-11-08T18:38:21-05:00
refactor: move and order helper functions in GHCi.Run
A small refactor to the order of top-level functions in GHCi.Run
- - - - -
24927752 by Luite Stegeman at 2026-11-09T09:21:24-05:00
rts: add missing nonmoving write barrier in out-of-line array copies
The out-of-line entries stg_copyArrayzh/stg_copyMutableArrayzh (taken
whenever the element count of copyArray#/copyMutableArray# is not a
compile-time constant) didn't push the overwritten elements to the
nonmoving collector's remembered set.
Fixes #27376
- - - - -
6dbcca65 by Rodrigo Mesquita at 2026-11-09T09:22:06-05:00
interp: Set per-thread break flags consistently on eval/resume
Currently, the per-thread flags are:
- Single-step: Stop at the immediate next breakpoint in this thread
- Step-out: Stop at the next continuation with a breakpoint this thread
returns to.
- Break-on-exception: Stop the next time a synchronous exception is
raised in this thread.
Originally, these flags were all set globally across all threads. More
recently, these flags are set per-thread when `resume`ing that thread,
but globally when starting the evaluation of a new expression
(`evalStmt`).
With this commit, we now use per-TSO flags in both scenarios evaluating
expressions in the interpreter (`evalStmt` and `resumeStmt`).
- In `resumeStmt` we set the `EvalOpts` specifically in the `ThreadId`
being resumed.
- In `evalStmt`, we set the `EvalOpts` exclusively on the sandbox thread
we fork to evaluate the given expression
- When not using the sandbox thread (i.e. -fno-ghci-sandbox), we
don't support the debugger anyway, so the break flags are
irrelevant.
We do this by consistently calling `setBreakFlags` when starting,
resuming, or killing the evaluation.
See Note [Always setBreakFlags on running thread].
This slightly changes the behavior of evaluating a new expression in
the debugger (resuming a thread behaves the same as before). Namely,
`:step <expr>`, where <expr> forks a thread, will stop at the immediate
next breakpoint in the <expr> main thread, not on a breakpoint of any
forked thread.
NB: the forked thread may still stop at breakpoint, if it is enabled by
index specifically, and then :step-ing from that thread's breakpoint
will toggle per-thread stepping for that forked thread.
We will want to control stepping in "all threads, regardless of whether
we control them or if they were spawned by the debuggee" separately from
the commands which trigger evaluation of just an expression. Namely,
we'll likely want a "break at the next immediate breakpoint hit on ANY
thread" command that the user can execute before launching a debuggee
which is multi-threaded. This may even be the default for GHCi.
Towards #26064
Fixes #28080
- - - - -
19ff36f2 by Simon Jakobi at 2026-11-09T09:22:47-05:00
testsuite: Mark T8209 fragile for the ghci ways on FreeBSD and darwin
A shutdown race in the I/O manager intermittently fails T8209(ghci) on
x86_64-freebsd14-validate and aarch64-darwin-validate, recently killing
several Marge batches. Mark it fragile there until the race is fixed.
See #27948.
Assisted-by: Claude Opus 5.5
- - - - -
212c292f by Rajkumar Natarajan at 2026-11-11T13:54:08-05:00
document what ->>> stands for in heap profile
updates the profiling section of the user's guide to explain how types
are approximated when using -hy. Also adds haddocks to getTyDescription
with the same information.
Fixes #26754
- - - - -
c64fc319 by Jonathan at 2026-11-11T13:54:55-05:00
Fix AArch64 veneer target for relocations with an addend
Fixes #27807
The RTS linker would construct invalid relocation veneers on AArch64 if
the addend was non-zero, which typically caused SIGILL crashes. This
could be triggered by evaluating Template Haskell in a package with a
large number of dependencies using a static build of GHC.
- - - - -
cd4dce19 by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
testsuite: add a test for registerFd_ trusting the callback table (#27821)
registerFd001 shows a 'threadWaitRead' that never finishes after an fd is
closed with 'closeFd' rather than 'closeFdWith'. Darwin is the only platform
this reaches -- one-shot registrations are implemented but not used there
(#7651) -- so the test is expect_broken on Darwin only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5ab442ee by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
registerFd_: always tell the polling backend (#27821)
Where the backend has no one-shot registrations, 'registerFd_' now tells it
about every registration, rather than only when the events differ from the
ones the callback table records: the table alone cannot say whether the
backend still knows the fd. The 'modify' it returns is unchanged. See Note
[Do not trust the callback table].
This fixes registerFd001 and clears its expect_broken.
Changelog wording from Duncan Coutts in review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
ab8b5b06 by Vladislav Zavialov at 2026-11-11T13:56:27-05:00
Curried contexts in prefix GADT constructors (#27424)
Prefix GADT constructor declarations now accept multiple consecutive
contexts, equivalent to a single conjoined context:
data G a where
MkCurried :: C a => (D a, E a) => G a
MkConjoined :: (C a, D a, E a) => G a
This is a step towards GHC Proposal #402 "Stable GADT constructor syntax".
To represent multiple contexts, the `con_mb_cxt` field of `ConDeclGADT` has
been replaced by `con_cxts`, which stores a list instead of a Maybe:
- con_mb_cxt :: Maybe (LHsContext pass)
+ con_cxts :: [LHsContext pass]
The rest of this patch follows from this change.
Note that in ConDeclH98, the optional context is still stored as a Maybe.
To accommodate this difference, a few helper functions were generalised over
a Foldable container `t`:
hsConDeclTheta :: Foldable t => t (LHsContext ...) -> [LHsType ...]
pprLHsContext :: (Foldable t, ...) => t (LHsContext ...) -> SDoc
repContexts :: Foldable t => t (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))
tcHsContext :: Foldable t => t (LHsContext GhcRn) -> TcM [PredType]
In practice, the instantiations of `t` are either `Maybe` or `[]`.
Record-style GADT constructors continue to accept at most one context.
`splitLHsGadtTy` accounts for this by splitting off only the first context
if it detects record syntax, leaving the offending part of the type in the
body for the renamer to reject later on.
Test cases: T12087a T27424a T27424b T27424c T27424d GadtConSigs_th_dump1
- - - - -
d2f135ff by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: cache register usage in liveness annotations
regUsageOfInstr allocates fresh register lists on every call, and on the
linear allocator path it was called three times per instruction: in the
backward liveness pass, in the forward liveness pass and in the allocator
itself. Store the usage computed by the backward pass in the Liveness
annotation and reuse it in the other passes (and in the graph allocator's
spill passes). patchRegsLiveInstr recomputes it for the patched
instruction.
See Note [Cached register usage in liveness annotations].
Part of #28008.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
ff0a5d32 by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: describe register usage with a small DSL
This new register usage DSL (see Note [Register usage DSL] in
GHC.CmmToAsm.RegUsage) reduces allocation compared to the previous
list-based approach.
Fixes #28008.
Metric Decrease:
ManyAlternatives
T12707
T13035
T13379
T13960
T18698b
T19695
T21839c
T3064
T3294
T4801
T5321FD
T5321Fun
T783
T9198
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
51f38f3a by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock-library: fix the build of the spec and fixtures test suites
The documentation pipeline moved from String to Text (commit 202ed264141)
but the two test suites of haddock-library were left behind and no
longer compiled. They are not run by GHC's CI (see #16206), so this went
unnoticed.
The fixtures suite still has four pre-existing failures (list-blocks1,
table1, table4, table5) that are not addressed here.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
394d9d6d by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: parse backtick spans as monospaced text
A backtick span whose content is not a valid Haskell identifier, such as
`foo bar`, was rendered as plain text with literal backticks. It is now
parsed as monospaced text, like @foo bar@. A closed backtick span whose
whole content is one identifier keeps its meaning as a hyperlinked
identifier. A span such as `foldl' f z xs` is code: it is no longer read
as the identifier foldl between a backtick and a single quote. The
TeX-style form `foo' stays an identifier when no backtick closes the
span on the same line.
Code spans follow the CommonMark rules: a span opened by a run of N
backticks ends at the next run of exactly N backticks on the same line,
so ``x `plus` y`` is code "x `plus` y". One space is removed at each end
when both are present, and an unclosed opening run is plain text. The
content is literal: no markup is parsed and backslashes are kept, so
`\x -> x` renders as written.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Fixes #28090
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7ae41c37 by Sylvain Henry at 2026-11-11T13:58:14-05:00
Use 'T' instead of `T' in Haddock comments next to backtick spans
With backtick code spans, a TeX-style quote `T' followed by a backtick on
the same line opens a code span up to that backtick. Use the 'T' form in
the Haddock comments where this happens.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
ce96f0b6 by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: do not parse backtick spans inside @...@
Text between @...@ is already code, so backtick code spans are no longer
parsed there. Thus in
@x <- f -- of type `M Bool`@
the backticks stay as text. Inline markup inside @...@, such as /.../,
passes this context down.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
744b3036 by Sylvain Henry at 2026-11-11T13:58:15-05:00
haddock: keep the backticks of infix identifiers inside @...@
A backticked identifier inside @...@ was always rendered without its
backticks, so @f `elem` xs@ rendered as "f elem xs". Now an identifier
in an infix application or an operator section, such as @f `elem` xs@
or @(`elem` xs)@, is parsed in infix form, as if written ``elem``, and
renders with its backticks and with elem linked. Elsewhere, as in
@`foldlM` :: ...@, the backticks still only mark the link.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
0d8e1f8d by Sylvain Henry at 2026-11-11T13:59:05-05:00
PPC NCG: print non-standard NaN literals in target byte order
The PowerPC NCG printed a non-standard NaN literal byte by byte with
floatToBytes/doubleToBytes, which use the byte order of the host. This
is wrong when the host and the target have a different endianness (e.g.
from x86_64 to big-endian PowerPC). Print the bits with `.long`/`.quad`
instead, so that the assembler uses the target byte order.
Also make `ppr_item` print its argument: some clauses printed the
literal of `pprDataItem` instead.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
5a9db1ed by Sylvain Henry at 2026-11-11T13:59:05-05:00
Print all NaN literals as integer bits (#28101)
The x86 and PowerPC NCGs printed the quiet NaNs 0x7fc00000 and
0x7ff8000000000000 as `.float NaN`/`.double NaN`. GNU as and clang
encode these with all mantissa bits set, so constant-folded bit casts
of these values gave 0x7fffffff/0x7fffffffffffffff. The C backend
printed every NaN as `NAN`, losing its sign and payload.
Now the NCGs print all NaNs with `.long`/`.quad` and the C backend with
hs_bitcastword2float/hs_bitcastword642double.
See Note [Printing NaN literals].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b4ceb6a9 by mangoiv at 2026-11-11T13:59:47-05:00
ci: fix ghcup nightly script misbehaviour
- download all jobs instead of just the first 100
- stop using a canary job to detect whether it's a nightly or release
pipeline
- - - - -
aefa0c1b by Alan Zimmerman at 2026-11-11T14:00:28-05:00
EPA: Use AnnList in HsMultiIf
It introduces layout, capture it
- - - - -
d72505e4 by Simon Jakobi at 2026-11-12T15:26:14-05:00
testsuite: Fix T17088 flakiness and restore bug coverage
T17088 reads and prints a byte from an uninitialized array. Debug RTS
ways fill allocated memory with 0xaa, so the test can fail due to an
output mismatch unrelated to the pointer-tagging bug it covers.
Initialize the byte to zero to make the output deterministic.
The original bug requires the compacting collector and particular
compiler and RTS settings. Run the test only in the compacting_gc way
with -O1 and -A128k. Also disable STG lambda lifting because it removes
the closure shape needed to reproduce the pointer-tagging failure.
This makes the test reliable while ensuring it remains an effective
reproducer for #17088.
Closes #27534.
Assisted-by: gpt-5.6-sol via Codex CLI
- - - - -
5a7591b3 by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: Fix python type errors
These errors appear when using the VSCode python extension which uses
Pylance under the hood.
- - - - -
52f129f8 by David Eichmann at 2026-11-12T15:26:56-05:00
Add test modifier to test over all IO Managers
- - - - -
22e8b92a by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: include custom IO Manager in test name
- - - - -
82c34ccd by Simon Jakobi at 2026-11-12T15:27:40-05:00
Make T2464 actually test #ifdef'd pragmas
The test guarded a LANGUAGE EmptyDataDecls pragma behind #if, but
EmptyDataDecls is on by default since Haskell2010, so the module
compiled even when the guarded pragma was ignored. Guard MagicHash
instead, which is unlikely to be included in a future default language.
The test also checks that warnings from file-header pragmas are emitted
only once, even though the pragmas are parsed both before and after
CPP, using the -fffi deprecation warning as the canary. Use an
unrecognised warning flag instead, so the test no longer depends on a
deprecated flag that is about to be removed.
Context: #27939
Assisted-by: Claude Fable 5.1
- - - - -
419f2a12 by Simon Jakobi at 2026-11-12T15:27:40-05:00
Remove command-line flags deprecated in GHC 8.2 or earlier
Also remove the INCLUDE file-header pragma, which only expanded to
the now-removed -#include.
Closes #27939.
Assisted-by: Claude Fable 5.1
- - - - -
adc294d0 by Erik de Castro Lopo at 2026-11-12T15:28:21-05:00
TimerManager: publish only evaluated timeout queues (#9809)
The issue in #9809 was triggered by many threads registering timeouts
at the same time and those timeouts being stored as unevaluated thunks
in the shared list. When say 100,000 timeouts are registered at the
same time, the program can be slowed down considerably and the memory
usage grow unacceptably large.
The commit that caused the problem was 2d5eccdf1c, a 2013 change that
fixed #7653.
The fix is to add a modifyTimeouts function which applies an edit to a
copy of the list and fully evaluates the result before replacing the
shared list with a CAS operation.
Performance has improved for the threaded case and not regressed for
the single thread case:
Forked registrations of 100k timeouts (median of 5 runs):
-N4: 0.577 s, 428 MB -> 0.078 s, 39 MB
-N12: 1.227 s, 479 MB -> 0.127 s, 80 MB
Forked registrations of 1M timeouts on -N1 (median of 3 and 10 runs):
5.21 s (range 0.67-9.47 s), 1613 MB -> 0.67 s, 250 MB
Single-thread registrations are unchanged or slightly faster, and timer
latency during registration storms improves (p99 lateness of a 1 ms
threadDelay during 100k forked registrations on -N4: 302-394 ms ->
3.5-4.1 ms).
The registration code still runs in constant stack, so #7653 stays fixed;
T7653 and the concurrent, base and ghc-internal testsuites pass.
modifyTimeouts is OPAQUE so that the optimiser cannot expose the edit
function's inspection of the old queue next to the compare-and-swap and
replace the expected pointer with the evaluated queue, which would make the
compare-and-swap keep failing when the MutVar# holds a thunk or indirection.
Regression test T9809.hs included.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b294b82f by Moritz Angermann at 2026-11-12T15:28:21-05:00
testsuite: give pause_resume_via_safe_ffi_concurrent 60s on Darwin CI
The 10s System.Timeout watchdog was a false deadlock: five serialized
1s pauses plus rts_pause waiting on threadDelay/timer-manager traffic
overruns that budget on loaded Mac runners. Keep a watchdog so a real
hang still fails.
- - - - -
1543f834 by Simon Jakobi at 2026-11-12T15:29:03-05:00
testsuite/README: Don't append new tests at the end of all.T
Patches that each add a test at the end of the same all.T conflict
with each other. Tests added elsewhere in the file usually merge cleanly.
Context: #26285
Assisted-by: Claude Opus 5.5
- - - - -
9ad25cb2 by Sven Tennie at 2026-11-14T06:20:13-05:00
hadrian: Add Stage3 cross-compiled target bindist (#26924)
Add a `binary-dist-stage3` Hadrian target that packages target
executables (produced by the stage2 compiler) into a separate
'_build/bindist-stage3/' folder, distinct from the stage2 regular or
cross-compiler bindist in '_build/bindist/'.
This allows a single CI pipeline job to produce both a cross-compiler
bindist (e.g. x86_64 -> RISC-V) and a target-architecture bindist (e.g.
RISC-V -> RISC-V) that can be installed and run natively on the target.
To avoid issues with stale files or race-conditions on them, generate
the `configure` script per stage in `_build/<stage>/distrib`
directories.
- - - - -
ca91017d by Sven Tennie at 2026-11-14T06:20:13-05:00
ci: Build Stage3 and Stage2 bindists for cross targets in one job (#26924)
Building the stage3 target bindist already produces most of the stage2
cross-compiler bindist as a byproduct, so building them in separate jobs
duplicates the build efforts for no benefit. Instead of a separate
CROSS_STAGE=3 job, the stage3 job now also builds and publishes the
stage2 bindist.
The stage3 tarball is named and versioned as if it were built natively
on the target (target triple prefix, non-cross opsys), so its artifact
name stays what downstream consumers already expect and no changes are
needed on their side.
For now, this is only enabled for the RISC-V job. Others can easily
follow.
- - - - -
71b41e09 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: model cross targets as structured TargetPlatform triples (#26924)
Storing the cross target as a raw triple forced ad-hoc parsing at every
use, and broke the single responsibility rule. Modelling it as a
structured `TargetPlatform`` instead, avoids parsing and provides a
clear separation of concerns.
- - - - -
8067c2f9 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: extract the cross smoke tests into a separate smoke_test command (#26924)
This reduces if-nesting and complexity of the main `test_hadrian`
command. The decision how to test is now made by the caller. This is a
fair choice, because most test cases can run under emulation - they are
just very slow then.
The Stage3 smoke test also checks that the target compiler does not report
itself as cross-compiling and, when supported, runs a small GHCi expression.
- - - - -
7ece99a7 by fendor at 2026-11-14T06:20:57-05:00
Add `-dep-json` flag to `ghc -M`
Add an optional flag to `ghc -M` that allows to write the dependency
information in JSON Lines format.
The JSON Lines format enables us to stream the output of the dependency
generation to a consumer.
The output of `-dep-json` is streamed to a temporary file and then
copied to the final destination to avoid partial writes.
Each line contains one of two possible json objects:
1. A Home Unit Dependency
* Contains the name of the home module, its unit, where it is
located, whether a preprocessor is used, and all of its imports.
Importantly, the imports include `-XExplicitLevelImports`
information.
* If requested via `-include-pkg-deps`, includes imports of external
units, e.g. modules from `base`.
* If requested via `-include-cpp-deps`, files included via CPP.
2. External Unit Dependency
* Only if `-include-pkg-deps` is given
* Contains unit-id, its package name and package id.
---
This PR refactors the Makefile generation to use phases appropriately.
We introduce an intermediate data structure that is generated based on
the module graph nodes, and only then generate the Makefile rules.
This allows the dep-json and dep-makefile generation to use the same
dependency processing.
- - - - -
0f6e0146 by fendor at 2026-11-14T06:20:57-05:00
Add multiple home unit support to `ghc -M`
Allows to process the module graph of multiple home units at once using
the same syntax as `--make` and `--interactive`:
ghc -M -unit @unitA -unit @unitB
The semantics are identical to `--make` and `--interactive`.
Each home unit can declare individually to use `-include-cpp-deps` and
`-include-pkg-deps`.
However, there can only be one output file, and `-dep-json` and
`-dep-makefile` can only be provided at the top of the cli invocation.
We introduce a new GHC API `doMkDepend` that allows to use multiple home
units conveniently.
The output of `-dep-json` and `-dep-makefile` does not change, since we
were careful to choose a format that supports multiple home units from
the start.
Single home units are still accepted like before with no changes.
- - - - -
5598e6a0 by fendor at 2026-11-14T06:20:57-05:00
Deprecate `doMkDependHS` in favour of `doMkDepend`
- - - - -
39f2943e by David Eichmann at 2026-11-14T06:21:41-05:00
rts: Expose getRtsSymbols() and store redirect labels and external symbols tag
- - - - -
aa159605 by David Eichmann at 2026-11-14T06:21:41-05:00
hadrian: when running tests, properly set have_gdb and have_readelf
- - - - -
ff826da4 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: add have_ldd() test modifier
- - - - -
b9f0b7e2 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite driver: on windows, ensure PATH correctly contains mingw and ghc-pkg libraries
- - - - -
543c108e by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: driver now sets WAY_FLAGS variable for makefile tests
- - - - -
13408a2b by David Eichmann at 2026-11-14T06:21:41-05:00
Add golden test for rts/RtsSymbols.c
This test compares declared symbols against symbols observed
in the rts DSO (.so file).
- - - - -
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
cbe0a6bf by fendor at 2026-11-17T09:25:55-05:00
Add support for streaming `ghc -M` to stdout
Adds the flags `-dep-json-stdout` and `-dep-makefile-stdout` which
streams dependency information line-by-line to stdout.
Each dependency generation can be redirected to separate outputs.
Providing any extra `-dep-{json,makefile}[-stdout]` disables the default
generation of the `Makefile` file.
Allows consumers to start processing the dependency information as it
comes in and not waiting for the dependency generation to finish.
`DepStream` abstracts over the possible output handles, which is either
a file or the stdout handle.
Writing to a file requires temporary file paths, thus `DepStream` must
provide a way to perform clean up when dependency processing finished or
when an error is thrown for any reason.
We further decouple the rendering and writing of the result from the
dependency generation, localising side effects and making the code
slightly more readable.
The testsuite now also handles `ghc -M` writing to stdout.
We add a test for each combination of writing to stdout and file,
except for writing both makefile and json.
While it probably works, is really undefined behaviour.
Closes #27937
- - - - -
fbd49db2 by Sylvain Henry at 2026-11-17T09:27:09-05:00
Link the on-demand iserv without --gc-sections
GHC links an iserv program each time a session needs the external
interpreter. The link is static, against the ghci library and the boot
libraries. Like all executable links, it passed -Wl,--gc-sections to a
GNU linker. On libraries built with -split-sections (the release
bindists), the section garbage collection of ld.bfd is the largest part
of that link: with binutils 2.45, the link takes 3 times longer with
--gc-sections than without. The program is temporary and its size is
not important. Thus the iserv link does not use --gc-sections. Other
executable links do not change.
In CI, each ext-interp or ghci-ext test takes 12 to 18 times longer in
the x86_64-linux-fedora43-release test job (split sections) than in the
x86_64-linux-deb13-validate test job (no split sections) on the same
runner, while a normal-way test takes the same time in both. This link
is most of that difference.
See Note [No --gc-sections for the on-demand iserv] in
GHC.Runtime.Interpreter.C.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
09c965e2 by mangoiv at 2026-11-17T09:27:51-05:00
ci: make tests-primops run on marge CI
test primops dispatch was disabled on the *full-ci
group label to avoid dispatching for some of its configs
but wasn't reenabled for marge ci runs which it ought to
run
Fixes #27765
- - - - -
83038fbe by David Eichmann at 2026-11-17T09:28:32-05:00
test driver refactor: replace `.format(**locals())` with f-string
- - - - -
dda36ee2 by Andreas Klebinger at 2026-11-20T17:12:07+01:00
CmmSink: Avoid a pointless thunk.
It's always used so this reduces allocs by ~1%.
- - - - -
1099 changed files:
- .gitignore
- .gitlab-ci.yml
- .gitlab/ci.sh
- .gitlab/common.sh
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/hello.hs
- .gitlab/jobs.yaml
- .gitlab/rel_eng/mk-ghcup-metadata/mk_ghcup_metadata.py
- .gitmodules
- + changelog.d/21969
- + changelog.d/24450
- + changelog.d/25665
- + changelog.d/25850
- + changelog.d/26169.md
- + changelog.d/26610
- changelog.d/26616
- + changelog.d/26761
- + changelog.d/27368
- + changelog.d/27624
- + changelog.d/27641
- + changelog.d/27821
- + changelog.d/27845
- + changelog.d/27892
- + changelog.d/27936
- + changelog.d/27971
- + changelog.d/28002-leb128
- + changelog.d/28012
- + changelog.d/28080
- + changelog.d/28081
- + changelog.d/28101
- + changelog.d/T23785
- + changelog.d/T26543
- + changelog.d/T26754
- + changelog.d/T27323
- changelog.d/T27329
- + changelog.d/T27412
- changelog.d/T27455
- + changelog.d/T27545
- changelog.d/T27722-cbe-entry-block.md
- + changelog.d/T27731
- + changelog.d/T27763
- + changelog.d/T27828
- + changelog.d/T27830-rts-flag-bounds
- + changelog.d/T27831-bottoming-strict-field
- + changelog.d/T27842-bytecode-imported-tags
- + changelog.d/T27844
- + changelog.d/T27847
- + changelog.d/T27916
- + changelog.d/T27979
- + changelog.d/T27994
- + changelog.d/T28002
- + changelog.d/T28002-api
- + changelog.d/T28123
- + changelog.d/T4162
- + changelog.d/T9809-timer-manager-contention
- changelog.d/allow-gadt-prefix-con-parens
- + changelog.d/bignum-quotrem-no-alloc
- changelog.d/boxing-family
- + changelog.d/caf-deadlock-27272
- + changelog.d/clc-341-strict-mutable-data-types
- + changelog.d/clc-446
- + changelog.d/clc-447
- + changelog.d/fix-aarch64-veneer-target-16686
- + changelog.d/fix-copyarray-nonmoving-barrier-27376
- + changelog.d/fix-cross-ghc-info-unit-id
- + changelog.d/fix-heap-census-pinned-blocks.md
- + changelog.d/fix-nonmoving-weak-evacuation-race-23160
- changelog.d/fix-parallel-gc-selector-race-27477
- + changelog.d/gadt-curried-contexts-27424
- + changelog.d/ghc-api-exec-break-resume
- + changelog.d/ghc-api-interactive-ids
- + changelog.d/hadrian-persist-flavour
- + changelog.d/hpc-classinsts
- + changelog.d/hpc-cleanup
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-deprecate-doMkDependHS
- + changelog.d/make-depends-json
- + changelog.d/make-depends-multiple-home-units
- + changelog.d/make-depends-streaming-output
- + changelog.d/monad-of-no-return-canonical
- + changelog.d/ncg-reg-usage.md
- + changelog.d/ncg-x86-subword-popcnt
- + changelog.d/parallel-downsweep
- + changelog.d/remove-long-deprecated-flags.md
- + changelog.d/resizeMutableByteArray-pinnedness
- changelog.d/semaphore-v2
- + changelog.d/split-sections-dynamic
- + changelog.d/stage3-cross-bindists
- changelog.d/tcplugin_init.md
- + changelog.d/unboxed-do
- changelog.d/unit-index
- + changelog.d/zap-coercions
- compiler/GHC.hs
- compiler/GHC/Builtin.hs
- compiler/GHC/Builtin/Modules.hs
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/Builtin/WiredIn/Prim.hs
- compiler/GHC/Builtin/WiredIn/Types/Box.hs
- compiler/GHC/Builtin/primops.txt.pp
- compiler/GHC/ByteCode/Asm.hs
- compiler/GHC/ByteCode/Show.hs
- compiler/GHC/Cmm/CallConv.hs
- compiler/GHC/Cmm/CommonBlockElim.hs
- compiler/GHC/Cmm/GenericOpt.hs
- compiler/GHC/Cmm/Sink.hs
- compiler/GHC/Cmm/UniqueRenamer.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/CFG/Dominators.hs
- compiler/GHC/CmmToAsm/Config.hs
- compiler/GHC/CmmToAsm/Dwarf/Types.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Ppr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- + compiler/GHC/CmmToAsm/RegUsage.hs
- compiler/GHC/CmmToAsm/Wasm/Asm.hs
- compiler/GHC/CmmToAsm/Wasm/Types.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/CmmToLlvm/CodeGen.hs
- compiler/GHC/CmmToLlvm/Config.hs
- compiler/GHC/Core.hs
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Coercion.hs-boot
- compiler/GHC/Core/Coercion/Axiom.hs
- compiler/GHC/Core/Coercion/Opt.hs
- compiler/GHC/Core/DataCon.hs
- compiler/GHC/Core/FVs.hs
- compiler/GHC/Core/FamInstEnv.hs
- compiler/GHC/Core/Lint.hs
- + compiler/GHC/Core/Lint.hs-boot
- compiler/GHC/Core/Make.hs
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/CallerCC.hs
- compiler/GHC/Core/Opt/CallerCC/Types.hs
- compiler/GHC/Core/Opt/Exitify.hs
- compiler/GHC/Core/Opt/Monad.hs
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Core/Predicate.hs
- compiler/GHC/Core/Reduction.hs
- compiler/GHC/Core/Seq.hs
- compiler/GHC/Core/SimpleOpt.hs
- compiler/GHC/Core/Subst.hs
- compiler/GHC/Core/TyCo/Compare.hs
- compiler/GHC/Core/TyCo/FVs.hs
- compiler/GHC/Core/TyCo/FVs.hs-boot
- + compiler/GHC/Core/TyCo/Make.hs
- + compiler/GHC/Core/TyCo/Make.hs-boot
- compiler/GHC/Core/TyCo/Ppr.hs
- compiler/GHC/Core/TyCo/Rep.hs
- compiler/GHC/Core/TyCo/Rep.hs-boot
- compiler/GHC/Core/TyCo/Subst.hs
- compiler/GHC/Core/TyCo/Tidy.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Type.hs-boot
- compiler/GHC/Core/Unify.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToIface.hs-boot
- compiler/GHC/CoreToStg.hs
- + compiler/GHC/Data/Dependent.hs
- compiler/GHC/Data/FastString.hs
- compiler/GHC/Data/OrdList.hs
- compiler/GHC/Data/OsPath.hs
- compiler/GHC/Data/Pair.hs
- compiler/GHC/Data/Word64Map/Internal.hs
- compiler/GHC/Data/Word64Set/Internal.hs
- compiler/GHC/Driver/Backpack.hs
- compiler/GHC/Driver/CmdLine.hs
- + compiler/GHC/Driver/Concurrency.hs
- compiler/GHC/Driver/Config.hs
- compiler/GHC/Driver/Config/CmmToAsm.hs
- compiler/GHC/Driver/Config/CmmToLlvm.hs
- + compiler/GHC/Driver/Config/Concurrency.hs
- compiler/GHC/Driver/Config/Core/Lint.hs
- compiler/GHC/Driver/Config/StgToCmm.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Errors/Ppr.hs
- compiler/GHC/Driver/Errors/Types.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeAction.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/MakeSem.hs
- compiler/GHC/Driver/Pipeline.hs-boot
- compiler/GHC/Driver/Pipeline/Execute.hs
- compiler/GHC/Driver/Pipeline/LogQueue.hs
- compiler/GHC/Driver/Pipeline/Phases.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Driver/Session/Units.hs
- compiler/GHC/Hs/Binds.hs
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/Doc.hs
- compiler/GHC/Hs/Dump.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/ImpExp.hs
- compiler/GHC/Hs/Lit.hs
- compiler/GHC/Hs/Type.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Arrows.hs
- compiler/GHC/HsToCore/Binds.hs
- compiler/GHC/HsToCore/Docs.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Expr.hs-boot
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- compiler/GHC/HsToCore/Pmc/Desugar.hs
- compiler/GHC/HsToCore/Pmc/Types.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/HsToCore/Types.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Iface/Decl.hs
- compiler/GHC/Iface/Errors/Types.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Iface/Ext/Debug.hs
- compiler/GHC/Iface/Ext/Types.hs
- compiler/GHC/Iface/Ext/Utils.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Iface/Rename.hs
- compiler/GHC/Iface/Syntax.hs
- compiler/GHC/Iface/Tidy.hs
- compiler/GHC/Iface/Type.hs
- compiler/GHC/Iface/Type.hs-boot
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/JS/Opt/Simple.hs
- compiler/GHC/Linker/Deps.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/Errors/Ppr.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Parser/String.hs
- compiler/GHC/Platform.hs
- + compiler/GHC/Platform/CpuFeatures.hs
- compiler/GHC/Platform/Ways.hs
- compiler/GHC/Rename/Bind.hs
- compiler/GHC/Rename/Env.hs
- compiler/GHC/Rename/Expr.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Names.hs
- compiler/GHC/Rename/Unbound.hs
- compiler/GHC/Rename/Utils.hs
- compiler/GHC/Runtime/Context.hs
- compiler/GHC/Runtime/Debugger.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Heap/Inspect.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- compiler/GHC/Runtime/Interpreter/JS.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Settings.hs
- compiler/GHC/Settings/IO.hs
- compiler/GHC/Stg/BcPrep.hs
- compiler/GHC/Stg/Debug.hs
- compiler/GHC/Stg/EnforceEpt.hs
- compiler/GHC/Stg/EnforceEpt/Rewrite.hs
- compiler/GHC/Stg/EnforceEpt/TagSig.hs
- compiler/GHC/Stg/EnforceEpt/Types.hs
- compiler/GHC/Stg/Make.hs
- compiler/GHC/Stg/Subst.hs
- compiler/GHC/StgToCmm/Closure.hs
- compiler/GHC/StgToCmm/Config.hs
- compiler/GHC/StgToCmm/Prim.hs
- compiler/GHC/StgToJS/Apply.hs
- compiler/GHC/StgToJS/ExprCtx.hs
- compiler/GHC/StgToJS/Linker/Linker.hs
- compiler/GHC/StgToJS/Object.hs
- compiler/GHC/StgToJS/Prim.hs
- compiler/GHC/SysTools/Cpp.hs
- compiler/GHC/Tc/Deriv/Functor.hs
- compiler/GHC/Tc/Deriv/Generate.hs
- compiler/GHC/Tc/Deriv/Generics.hs
- compiler/GHC/Tc/Errors.hs
- compiler/GHC/Tc/Errors/Ppr.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/App.hs
- compiler/GHC/Tc/Gen/Arrow.hs
- compiler/GHC/Tc/Gen/Export.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Match.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Instance/FunDeps.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Plugin.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/Equality.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Tc/Solver/InertSet.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/Solver/Rewrite.hs
- compiler/GHC/Tc/Solver/Solve.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/TyCl/PatSyn.hs
- compiler/GHC/Tc/Types.hs
- compiler/GHC/Tc/Types/Constraint.hs
- compiler/GHC/Tc/Types/ErrCtxt.hs
- compiler/GHC/Tc/Utils/Backpack.hs
- compiler/GHC/Tc/Utils/Monad.hs
- compiler/GHC/Tc/Utils/TcMType.hs
- compiler/GHC/Tc/Utils/TcType.hs
- compiler/GHC/Tc/Utils/Unify.hs
- compiler/GHC/Tc/Zonk/Env.hs
- compiler/GHC/Tc/Zonk/Monad.hs
- compiler/GHC/Tc/Zonk/TcType.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Annotations.hs
- compiler/GHC/Types/Arity.hs
- compiler/GHC/Types/Basic.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Demand.hs
- compiler/GHC/Types/Error/Codes.hs
- compiler/GHC/Types/Hint.hs
- compiler/GHC/Types/Hint/Ppr.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Types/Literal/Floating.hs
- compiler/GHC/Types/Name/Env.hs
- compiler/GHC/Types/Name/Occurrence.hs
- compiler/GHC/Types/RepType.hs
- compiler/GHC/Types/Tickish.hs
- compiler/GHC/Types/Unique.hs
- compiler/GHC/Types/Unique/DSM.hs
- compiler/GHC/Types/Unique/DSet.hs
- compiler/GHC/Types/Unique/FM.hs
- compiler/GHC/Types/Unique/Map.hs
- compiler/GHC/Types/Unique/Set.hs
- compiler/GHC/Types/Unique/Supply.hs
- compiler/GHC/Types/UnresolvedImport.hs
- compiler/GHC/Types/Var.hs
- compiler/GHC/Types/Var.hs-boot
- compiler/GHC/Types/Var/Env.hs
- compiler/GHC/Types/Var/FV.hs
- compiler/GHC/Types/Var/Set.hs
- compiler/GHC/Unit/Env.hs
- compiler/GHC/Unit/External/Database.hs
- compiler/GHC/Unit/External/ModuleOrigin.hs
- compiler/GHC/Unit/External/Visibility.hs
- compiler/GHC/Unit/External/Wired.hs
- compiler/GHC/Unit/Finder.hs
- + compiler/GHC/Unit/Finder/Cache.hs
- compiler/GHC/Unit/Finder/Types.hs
- compiler/GHC/Unit/Home.hs
- compiler/GHC/Unit/Module.hs
- compiler/GHC/Unit/Module/Env.hs
- compiler/GHC/Unit/Module/Graph.hs
- compiler/GHC/Unit/Module/ModSummary.hs
- + compiler/GHC/Unit/Module/Name.hs
- compiler/GHC/Unit/Module/WholeCoreBindings.hs
- compiler/GHC/Unit/Parser.hs
- compiler/GHC/Unit/State.hs
- compiler/GHC/Unit/Types.hs
- compiler/GHC/Unit/Types.hs-boot
- compiler/GHC/Utils/Binary.hs
- + compiler/GHC/Utils/Concurrent/Scope.hs
- compiler/GHC/Utils/Json.hs
- compiler/GHC/Utils/Monad/Codensity.hs
- + compiler/GHC/Utils/Monad/StrictIdentity.hs
- + compiler/GHC/Utils/Monad/StrictReader.hs
- compiler/GHC/Utils/Monad/State/Strict.hs ā compiler/GHC/Utils/Monad/StrictState.hs
- compiler/GHC/Utils/Outputable.hs
- compiler/GHC/Utils/Panic.hs
- compiler/GHC/Utils/Ppr/Colour.hs
- compiler/GHC/Utils/TmpFs.hs
- compiler/Language/Haskell/Syntax.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Decls/Foreign.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/Extension.hs
- compiler/Language/Haskell/Syntax/ImpExp.hs
- compiler/Language/Haskell/Syntax/Lit.hs
- compiler/Language/Haskell/Syntax/Module/Name.hs
- compiler/Language/Haskell/Syntax/Specificity.hs
- compiler/Language/Haskell/Syntax/Text.hs
- compiler/Language/Haskell/Syntax/Type.hs
- compiler/ghc.cabal.in
- distrib/configure.ac.in
- docs/users_guide/codegens.rst
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/extending_ghc.rst
- docs/users_guide/exts/control.rst
- docs/users_guide/exts/ffi.rst
- docs/users_guide/exts/gadt_syntax.rst
- docs/users_guide/exts/literals.rst
- docs/users_guide/exts/pragmas.rst
- docs/users_guide/exts/qualified_do.rst
- docs/users_guide/exts/qualified_strings.rst
- docs/users_guide/exts/type_families.rst
- docs/users_guide/ghc.rst
- + docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/phases.rst
- docs/users_guide/profiling.rst
- docs/users_guide/runtime_control.rst
- docs/users_guide/separate_compilation.rst
- docs/users_guide/using-warnings.rst
- ā docs/users_guide/what_glasgow_exts_does.rst
- ghc/GHCi/UI.hs
- ghc/GHCi/UI/Info.hs
- ghc/GHCi/UI/Monad.hs
- ghc/Main.hs
- ghc/ghc-bin.cabal.in
- hadrian/bindist/Makefile
- hadrian/bindist/config.mk.in
- hadrian/doc/cross-compile.md
- hadrian/doc/flavours.md
- hadrian/ghci-multi-cabal.in
- hadrian/src/Base.hs
- hadrian/src/BindistConfig.hs
- hadrian/src/Builder.hs
- hadrian/src/Context.hs
- hadrian/src/Flavour.hs
- hadrian/src/Hadrian/Haskell/Cabal/Parse.hs
- hadrian/src/Hadrian/Haskell/Cabal/Type.hs
- hadrian/src/Hadrian/Haskell/Hash.hs
- hadrian/src/Hadrian/Package.hs
- hadrian/src/Main.hs
- hadrian/src/Oracles/Flag.hs
- hadrian/src/Oracles/Setting.hs
- hadrian/src/Oracles/TestSettings.hs
- hadrian/src/Packages.hs
- hadrian/src/Rules.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Documentation.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Rules/Program.hs
- hadrian/src/Rules/Selftest.hs
- hadrian/src/Rules/Test.hs
- hadrian/src/Settings.hs
- hadrian/src/Settings/Builders/Ar.hs
- hadrian/src/Settings/Builders/DeriveConstants.hs
- hadrian/src/Settings/Builders/RunTest.hs
- hadrian/src/Settings/Packages.hs
- hadrian/src/Settings/Warnings.hs
- libraries/base/base.cabal.in
- libraries/base/changelog.md
- libraries/base/src/Control/Concurrent/Chan.hs
- + libraries/base/src/Control/Concurrent/Chan/Strict.hs
- libraries/base/src/Control/Concurrent/MVar.hs
- + libraries/base/src/Control/Concurrent/MVar/Strict.hs
- libraries/base/src/Data/Foldable.hs
- libraries/base/src/Data/IORef.hs
- + libraries/base/src/Data/IORef/Strict.hs
- libraries/base/src/GHC/Base.hs
- libraries/base/src/GHC/Exts.hs
- libraries/base/tests/.gitignore
- + libraries/base/tests/IO/T27971.hs
- + libraries/base/tests/IO/T27971.stdout
- libraries/base/tests/IO/all.T
- libraries/base/tests/Memo1.lhs
- libraries/base/tests/Memo2.lhs
- + libraries/base/tests/T9809.hs
- libraries/base/tests/all.T
- libraries/containers
- libraries/ghc-boot/GHC/Serialized.hs
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingDisabled.hsc
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingEnabled.hsc
- libraries/ghc-heap/tests/parse_tso_flags.hs
- libraries/ghc-internal/CHANGELOG.md
- libraries/ghc-internal/ghc-internal.cabal.in
- libraries/ghc-internal/src/GHC/Internal/Base.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Backend/GMP.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Backend/Native.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/BigNat.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Integer.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Natural.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Primitives.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/WordArray.hs
- libraries/ghc-internal/src/GHC/Internal/Bits.hs
- libraries/ghc-internal/src/GHC/Internal/Conc/IO.hs
- libraries/ghc-internal/src/GHC/Internal/Control/Exception/Base.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Manager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Thread.hs
- libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Windows.hsc
- libraries/ghc-internal/src/GHC/Internal/Event/Windows/FFI.hsc
- libraries/ghc-internal/src/GHC/Internal/Heap/Closures.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Text.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Windows.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Windows/Handle.hsc
- libraries/ghc-internal/src/GHC/Internal/System/Environment/ExecutablePath.hsc
- libraries/ghc-internal/src/GHC/Internal/System/IO/Error.hs
- + libraries/ghc-internal/src/GHC/Internal/Unboxed/Do.hs
- libraries/ghci/GHCi/Debugger.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Run.hs
- libraries/ghci/GHCi/TH.hs
- libraries/ghci/GHCi/TH/Binary.hs
- linters/lint-codes/LintCodes/Static.hs
- m4/subst_tooldir.m4
- rts/Exception.cmm
- rts/Interpreter.c
- rts/Interpreter.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/PrimOps.cmm
- rts/ProfHeap.c
- rts/RtsFlags.c
- rts/RtsStartup.c
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.c
- rts/Stats.c
- rts/Stats.h
- rts/StgStdThunks.cmm
- rts/include/Cmm.h
- rts/include/Rts.h
- rts/include/rts/Constants.h
- rts/include/rts/Flags.h
- + rts/include/rts/RtsSymbols.h
- rts/include/rts/storage/GC.h
- rts/include/stg/MiscClosures.h
- rts/include/stg/Prim.h
- rts/js/environment.js
- rts/linker/PEi386.c
- rts/linker/elf_reloc_aarch64.c
- rts/prim/bitrev.c
- rts/prim/bswap.c
- rts/rts.cabal
- rts/sm/Evac.c
- rts/sm/GC.c
- rts/sm/GCThread.h
- rts/sm/NonMovingMark.c
- rts/sm/Storage.c
- testsuite/README.md
- testsuite/config/ghc
- testsuite/driver/junit.py
- testsuite/driver/my_typing.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/driver/testutil.py
- testsuite/mk/test.mk
- testsuite/tests/ado/ado-optimal.hs
- testsuite/tests/ado/ado001.hs
- testsuite/tests/annotations/should_run/Makefile
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.hs
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout-ws-32
- + testsuite/tests/annotations/should_run/T16841.hs
- + testsuite/tests/annotations/should_run/T16841.stdout
- testsuite/tests/annotations/should_run/all.T
- + testsuite/tests/backpack/should_compile/T27835.bkp
- + testsuite/tests/backpack/should_compile/T27835.stderr
- testsuite/tests/backpack/should_compile/all.T
- + testsuite/tests/bytecode/T27842.hs
- + testsuite/tests/bytecode/T27842.stdout
- + testsuite/tests/bytecode/T27842A.hs
- + testsuite/tests/bytecode/T27842N.hs
- testsuite/tests/bytecode/all.T
- + testsuite/tests/cmm/should_run/T27722.hs
- + testsuite/tests/cmm/should_run/T27722_cmm.cmm
- + testsuite/tests/cmm/should_run/T28101.hs
- + testsuite/tests/cmm/should_run/T28101.stdout
- + testsuite/tests/cmm/should_run/T28101_cmm.cmm
- testsuite/tests/cmm/should_run/all.T
- + testsuite/tests/codeGen/should_compile/T27368.hs
- + testsuite/tests/codeGen/should_compile/T27979.hs
- + testsuite/tests/codeGen/should_compile/T27979.stderr
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_gen_asm/T24813.asm
- + testsuite/tests/codeGen/should_gen_asm/T24813.cmm
- testsuite/tests/codeGen/should_gen_asm/all.T
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.hs
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.hs
- + testsuite/tests/codeGen/should_run/T27624.hs
- + testsuite/tests/codeGen/should_run/T27624.stdout
- testsuite/tests/codeGen/should_run/all.T
- testsuite/tests/concurrent/T13615/Parallel.hs
- testsuite/tests/concurrent/should_run/T21651.hs
- testsuite/tests/concurrent/should_run/T21969.hs
- + testsuite/tests/concurrent/should_run/T21969a.hs
- + testsuite/tests/concurrent/should_run/T21969a.stdout
- + testsuite/tests/concurrent/should_run/T21969b.hs
- + testsuite/tests/concurrent/should_run/T21969b.stdout
- + testsuite/tests/concurrent/should_run/T21969c.hs
- + testsuite/tests/concurrent/should_run/T21969c.stdout
- + testsuite/tests/concurrent/should_run/T21969d.hs
- + testsuite/tests/concurrent/should_run/T21969d.stdout
- + testsuite/tests/concurrent/should_run/T21969e.hs
- + testsuite/tests/concurrent/should_run/T21969e.stdout
- + testsuite/tests/concurrent/should_run/T21969f.hs
- + testsuite/tests/concurrent/should_run/T21969f.stdout
- testsuite/tests/concurrent/should_run/all.T
- + testsuite/tests/concurrent/should_run/registerFd001.hs
- + testsuite/tests/concurrent/should_run/registerFd001.stdout
- testsuite/tests/concurrent/should_run/setnumcapabilities001.hs
- testsuite/tests/corelint/T27374.hs
- testsuite/tests/count-deps/CountDepsAst.stdout
- testsuite/tests/count-deps/CountDepsParser.stdout
- testsuite/tests/cpranal/should_run/T20598a.hs
- testsuite/tests/default/default-fail05.stderr
- testsuite/tests/dependent/should_compile/T14729.stderr
- testsuite/tests/deriving/should_compile/T13758.hs
- testsuite/tests/deriving/should_run/all.T
- + testsuite/tests/deriving/should_run/drvrun-canonical-methods.hs
- + testsuite/tests/deriving/should_run/drvrun-canonical-methods.stderr
- + testsuite/tests/deriving/should_run/drvrun-canonical-methods.stdout
- testsuite/tests/determinism/determ017/A.hs
- testsuite/tests/diagnostic-codes/codes.stdout
- testsuite/tests/dmdanal/should_compile/T9208.hs
- + testsuite/tests/dmdanal/should_run/T27845.hs
- + testsuite/tests/dmdanal/should_run/T27845.stdout
- + testsuite/tests/dmdanal/should_run/T27845_Lib.hs
- + testsuite/tests/dmdanal/should_run/T27845b.hs
- + testsuite/tests/dmdanal/should_run/T27845b.stdout
- + testsuite/tests/dmdanal/should_run/T27845b_Lib.hs
- testsuite/tests/dmdanal/should_run/all.T
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/T2464.hs
- testsuite/tests/driver/T2464.stderr
- testsuite/tests/driver/T27461/Makefile
- + testsuite/tests/driver/T27461/T27461c.stderr
- testsuite/tests/driver/T27461/all.T
- + testsuite/tests/driver/T27461/src/Wrong.hs
- + testsuite/tests/driver/T27836/A.hs
- + testsuite/tests/driver/T27836/B.hs
- + testsuite/tests/driver/T27836/C.hs
- + testsuite/tests/driver/T27836/Makefile
- + testsuite/tests/driver/T27836/T27836.stdout
- + testsuite/tests/driver/T27836/all.T
- + testsuite/tests/driver/T27836/unitA
- + testsuite/tests/driver/T27836/unitB
- + testsuite/tests/driver/T27836/unitC
- + testsuite/tests/driver/T28009.hs
- testsuite/tests/driver/all.T
- + testsuite/tests/driver/mkdepend/Makefile
- + testsuite/tests/driver/mkdepend/README.md
- + testsuite/tests/driver/mkdepend/T24384/A.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/D.hs
- + testsuite/tests/driver/mkdepend/T24384/E.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/DepInternal.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/dep-internal.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep-public/DepPublic.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-public/dep-public.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep/Dep.hs
- + testsuite/tests/driver/mkdepend/T24384/dep/dep.pkg
- + testsuite/tests/driver/mkdepend/T24384/foo.h
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/preproc.sh
- + testsuite/tests/driver/mkdepend/T24384a.stdout
- + testsuite/tests/driver/mkdepend/T24384b.stdout
- + testsuite/tests/driver/mkdepend/T24384c.stdout
- + testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/format_json.sh
- + testsuite/tests/driver/mkdepend/format_makefile.sh
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs-boot
- + testsuite/tests/driver/mkdepend/mhu01/a/A/TH.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Normal.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Splice.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/c/C.hs
- + testsuite/tests/driver/mkdepend/mhu01/unitA
- + testsuite/tests/driver/mkdepend/mhu01/unitB
- + testsuite/tests/driver/mkdepend/mhu01/unitC
- + testsuite/tests/driver/mkdepend/mhu02/A.hs
- + testsuite/tests/driver/mkdepend/mhu02/B.hs
- + testsuite/tests/driver/mkdepend/mhu02/pp.sh
- + testsuite/tests/driver/mkdepend/mhu02/unitA
- + testsuite/tests/driver/mkdepend/mhu02/unitB
- + testsuite/tests/driver/mkdepend/mhu03/pkg/A.hs
- + testsuite/tests/driver/mkdepend/mhu03/pkg/pp.sh
- + testsuite/tests/driver/mkdepend/mhu03/unitA
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend01/A.hs
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu03.dep-json
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/Makefile
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/mhu-closure.stderr
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/mhu-closure.stdout
- + testsuite/tests/exceptions/T27851.hs
- + testsuite/tests/exceptions/T27851.stderr
- + testsuite/tests/exceptions/T27851b.hs
- + testsuite/tests/exceptions/T27851b.stderr
- + testsuite/tests/exceptions/T27851c.hs
- + testsuite/tests/exceptions/T27851c.stdout
- + testsuite/tests/exceptions/T27851d.hs
- + testsuite/tests/exceptions/T27851d.stdout
- + testsuite/tests/exceptions/T27851d.stdout-javascript-unknown-ghcjs
- testsuite/tests/exceptions/all.T
- testsuite/tests/ffi/should_run/T2594.hs
- testsuite/tests/ffi/should_run/ffi015.hs
- testsuite/tests/ffi/should_run/fptr01.hs
- testsuite/tests/ffi/should_run/fptrfail01.hs
- ā testsuite/tests/gadt/T12087.stderr
- + testsuite/tests/gadt/T12087a.hs
- testsuite/tests/gadt/T12087.hs ā testsuite/tests/gadt/T12087b.hs
- + testsuite/tests/gadt/T12087b.stderr
- + testsuite/tests/gadt/T27424a.hs
- + testsuite/tests/gadt/T27424b.hs
- + testsuite/tests/gadt/T27424b.stderr
- testsuite/tests/gadt/all.T
- testsuite/tests/generics/T27245.hs
- testsuite/tests/generics/T27245.stdout
- + testsuite/tests/ghc-api/T4162.hs
- + testsuite/tests/ghc-api/T4162.stdout
- testsuite/tests/ghc-api/all.T
- testsuite/tests/ghc-api/downsweep/IncrementalDownsweep.hs
- testsuite/tests/ghc-api/downsweep/OldModLocation.hs
- testsuite/tests/ghc-api/downsweep/PartialDownsweep.hs
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghc-api/fixed-nodes/FixedNodes.hs
- testsuite/tests/ghc-api/fixed-nodes/InterfaceModuleGraph.hs
- testsuite/tests/ghc-api/fixed-nodes/ModuleGraphInvariants.hs
- testsuite/tests/ghc-e/should_fail/T18441fail7.stderr
- testsuite/tests/ghc-e/should_run/ghc-e005.stderr
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.hs
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.script
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.stdout
- testsuite/tests/ghci.debugger/scripts/T14628.stderr
- testsuite/tests/ghci.debugger/scripts/all.T
- + testsuite/tests/ghci.debugger/scripts/break037.hs
- + testsuite/tests/ghci.debugger/scripts/break037.script
- + testsuite/tests/ghci.debugger/scripts/break037.stdout
- testsuite/tests/ghci/linking/T25155_iserv_main.c
- testsuite/tests/ghci/prog-mhu001/prog-mhu001c.stdout
- testsuite/tests/ghci/prog-mhu002/prog-mhu002d.stdout
- + testsuite/tests/ghci/prog-mhu008/Makefile
- + testsuite/tests/ghci/prog-mhu008/a/M.hs
- + testsuite/tests/ghci/prog-mhu008/all.T
- + testsuite/tests/ghci/prog-mhu008/b/M.hs
- + testsuite/tests/ghci/prog-mhu008/prog-mhu008.script
- + testsuite/tests/ghci/prog-mhu008/prog-mhu008.stdout
- + testsuite/tests/ghci/prog-mhu008/unitA
- + testsuite/tests/ghci/prog-mhu008/unitB
- testsuite/tests/ghci/prog020/ghci.prog020a.stderr
- testsuite/tests/ghci/prog020/ghci.prog020b.stderr
- testsuite/tests/ghci/prog021/prog021a.stderr
- testsuite/tests/ghci/prog021/prog021b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022a.stderr
- testsuite/tests/ghci/prog022/ghci.prog022b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022c.stderr
- testsuite/tests/ghci/prog022/ghci.prog022d.stderr
- testsuite/tests/ghci/prog022/ghci.prog022e.stderr
- testsuite/tests/ghci/prog022/ghci.prog022f.stderr
- testsuite/tests/ghci/scripts/Defer02.stderr
- testsuite/tests/ghci/scripts/T16575.script
- testsuite/tests/ghci/scripts/T16575.stdout
- testsuite/tests/ghci/scripts/T16804.stdout
- testsuite/tests/ghci/scripts/T20150.stdout
- + testsuite/tests/ghci/scripts/T27412.hs
- + testsuite/tests/ghci/scripts/T27412.script
- + testsuite/tests/ghci/scripts/T27412.stdout
- + testsuite/tests/ghci/scripts/T27641.script
- + testsuite/tests/ghci/scripts/T27641.stderr
- + testsuite/tests/ghci/scripts/T27641.stdout
- + testsuite/tests/ghci/scripts/T27834.hs
- + testsuite/tests/ghci/scripts/T27834.script
- + testsuite/tests/ghci/scripts/T27834.stdout
- testsuite/tests/ghci/scripts/all.T
- + testsuite/tests/haddock/haddock_testsuite/IncrementalUnitId.hs
- testsuite/tests/haddock/haddock_testsuite/Makefile
- testsuite/tests/haddock/haddock_testsuite/all.T
- + testsuite/tests/haddock/haddock_testsuite/haddockIncrementalUnitId.stdout
- testsuite/tests/haddock/perf/Fold.hs
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T24221.stderr
- testsuite/tests/hiefile/should_compile/hie002.hs
- testsuite/tests/hiefile/should_run/T24544.hs
- + testsuite/tests/hpc/instmeths/instmeths.hs
- + testsuite/tests/hpc/instmeths/instmeths.stdout
- + testsuite/tests/hpc/instmeths/test.T
- testsuite/tests/hpc/raytrace/Eval.hs
- + testsuite/tests/impredicative/T27917.hs
- testsuite/tests/impredicative/all.T
- + testsuite/tests/indexed-types/should_compile/T27828.hs
- + testsuite/tests/indexed-types/should_compile/T27828a.hs
- + testsuite/tests/indexed-types/should_compile/T27828b.hs
- testsuite/tests/indexed-types/should_compile/T3787.hs
- + testsuite/tests/indexed-types/should_compile/ZapDeps.hs
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/SkolemOccursLoop.hs
- testsuite/tests/indexed-types/should_fail/T1897b.stderr
- testsuite/tests/indexed-types/should_fail/T7729.hs
- testsuite/tests/indexed-types/should_fail/T7729a.hs
- testsuite/tests/indexed-types/should_fail/T9662.stderr
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-prim-exports.stdout
- testsuite/tests/interface-stability/ghc-prim-exports.stdout-mingw32
- testsuite/tests/javascript/Makefile
- + testsuite/tests/javascript/T25665.hs
- + testsuite/tests/javascript/T25665.pkg
- + testsuite/tests/javascript/T25665.stdout
- + testsuite/tests/javascript/T25665Lib.hs
- + testsuite/tests/javascript/T25665_c.c
- + testsuite/tests/javascript/T25665_js.js
- testsuite/tests/javascript/all.T
- testsuite/tests/linters/all.T
- testsuite/tests/llvm/should_compile/all.T
- + testsuite/tests/llvm/should_compile/split-sections-darwin.hs
- testsuite/tests/module/mod130.stderr
- testsuite/tests/module/mod133.hs
- testsuite/tests/module/mod185.stderr
- + testsuite/tests/numeric/should_run/T27545.hs
- + testsuite/tests/numeric/should_run/T27545.stdout
- testsuite/tests/numeric/should_run/all.T
- testsuite/tests/overloadedstrings/should_fail/T25926.stderr
- testsuite/tests/overloadedstrings/should_fail/T27124.stderr
- testsuite/tests/package/T4806a.stderr
- testsuite/tests/package/all.T
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/DumpTypecheckedAst.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T14189.stderr
- testsuite/tests/parser/should_compile/T15279.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20718b.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/parser/should_compile/T23315/T23315.stderr
- testsuite/tests/patsyn/should_fail/records-nofieldselectors.stderr
- testsuite/tests/perf/compiler/T13253.hs
- testsuite/tests/perf/compiler/T14683.hs
- testsuite/tests/perf/compiler/T16473.hs
- testsuite/tests/perf/compiler/T18730_A.hs
- testsuite/tests/perf/compiler/T25723.hs
- testsuite/tests/perf/compiler/all.T
- testsuite/tests/perf/compiler/hard_hole_fits.stderr
- testsuite/tests/perf/compiler/large-project/all.T
- + testsuite/tests/perf/compiler/large-project/large-project-mhu.sh
- + testsuite/tests/perf/should_run/T27231.hs
- + testsuite/tests/perf/should_run/T27231.stdout
- testsuite/tests/perf/should_run/T7257.hs
- testsuite/tests/perf/should_run/T7257.stdout
- testsuite/tests/perf/should_run/all.T
- + testsuite/tests/plugins/T26761.hs
- + testsuite/tests/plugins/T26761.stderr
- + testsuite/tests/plugins/T26761Plugin.hs
- + testsuite/tests/plugins/T26761a.hs
- testsuite/tests/plugins/all.T
- testsuite/tests/plugins/defaulting-plugin/DefaultLifted.hs
- testsuite/tests/pmcheck/should_compile/T11276.hs
- + testsuite/tests/pmcheck/should_compile/T27323.hs
- + testsuite/tests/pmcheck/should_compile/T27323b.hs
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- + testsuite/tests/primops/should_run/ResizeByteArrayPinnedness.hs
- + testsuite/tests/primops/should_run/ResizeByteArrayPinnedness.stdout
- + testsuite/tests/primops/should_run/T27299.hs
- + testsuite/tests/primops/should_run/T27299.stdout
- testsuite/tests/primops/should_run/all.T
- testsuite/tests/printer/AnnotationNoListTuplePuns.stdout
- testsuite/tests/printer/Makefile
- testsuite/tests/printer/T17697.stderr
- testsuite/tests/printer/T18791.stderr
- + testsuite/tests/printer/T27424c.hs
- testsuite/tests/printer/Test20297.hs
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/printer/all.T
- testsuite/tests/profiling/should_compile/T19894/StreamK.hs
- testsuite/tests/profiling/should_run/T3001-2.hs
- testsuite/tests/profiling/should_run/T7275.stdout
- testsuite/tests/profiling/should_run/caller-cc/CallerCcParser.hs
- testsuite/tests/programs/galois_raytrace/Eval.hs
- testsuite/tests/qualifieddo/should_compile/all.T
- + testsuite/tests/qualifieddo/should_compile/qdocompile003.hs
- + testsuite/tests/qualifieddo/should_compile/qdocompile003.stderr
- testsuite/tests/qualifieddo/should_fail/all.T
- + testsuite/tests/qualifieddo/should_fail/qdofail006.hs
- + testsuite/tests/qualifieddo/should_fail/qdofail006.stderr
- testsuite/tests/qualifieddo/should_run/all.T
- + testsuite/tests/qualifieddo/should_run/qdorun008.hs
- + testsuite/tests/qualifieddo/should_run/qdorun008.stdout
- testsuite/tests/rebindable/rebindable2.hs
- + testsuite/tests/rename/should_fail/Noncanonical.hs
- + testsuite/tests/rename/should_fail/Noncanonical.stderr
- testsuite/tests/rename/should_fail/T15607.stderr
- testsuite/tests/rename/should_fail/T19843b.stderr
- testsuite/tests/rename/should_fail/all.T
- testsuite/tests/rename/should_fail/rnfail026.hs
- testsuite/tests/rep-poly/RepPolyRule3.stderr
- testsuite/tests/rts/Makefile
- testsuite/tests/rts/T17088.hs
- + testsuite/tests/rts/T23160.hs
- + testsuite/tests/rts/T23160.stdout
- + testsuite/tests/rts/T24450.hs
- + testsuite/tests/rts/T24450.stderr
- + testsuite/tests/rts/T26169.hs
- + testsuite/tests/rts/T27272.hs
- + testsuite/tests/rts/T27272_gen.py
- + testsuite/tests/rts/T27376.hs
- + testsuite/tests/rts/T27376.stdout
- + testsuite/tests/rts/T27526.hs
- + testsuite/tests/rts/T27526.stdout
- + testsuite/tests/rts/T28012.hs
- + testsuite/tests/rts/T28012.stdout
- testsuite/tests/rts/all.T
- + testsuite/tests/rts/census_pinned.hs
- + testsuite/tests/rts/census_pinned.stdout-ws-32
- + testsuite/tests/rts/census_pinned.stdout-ws-64
- + testsuite/tests/rts/census_pinned.stdout-ws-64-mingw32
- testsuite/tests/rts/ipe/IpeStats/Fold.hs
- testsuite/tests/rts/linker/Makefile
- + testsuite/tests/rts/linker/T27807.s
- + testsuite/tests/rts/linker/T27807.stdout
- testsuite/tests/rts/linker/all.T
- testsuite/tests/rts/pause-resume/all.T
- testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs
- testsuite/tests/rts/rtsflags001.stderr-ws-32
- testsuite/tests/rts/rtsflags001.stderr-ws-64
- + testsuite/tests/rts/symbols/Main.hs
- + testsuite/tests/rts/symbols/Makefile
- + testsuite/tests/rts/symbols/all.T
- + testsuite/tests/rts/symbols/dumpDeclaredSymbols.c
- + testsuite/tests/rts/symbols/rts-check-symbols.sh
- + testsuite/tests/rts/symbols/rts-check-symbols.stdout
- testsuite/tests/safeHaskell/ghci/p4.stderr
- testsuite/tests/safeHaskell/ghci/p6.stderr
- testsuite/tests/simplCore/should_compile/T14908_Deps.hs
- testsuite/tests/simplCore/should_compile/T22375.stderr
- testsuite/tests/simplCore/should_compile/T22375DataFamily.stderr
- testsuite/tests/simplCore/should_compile/T22611.hs
- testsuite/tests/simplCore/should_compile/T22611.stderr
- + testsuite/tests/simplCore/should_compile/T22611a.hs
- testsuite/tests/simplCore/should_compile/T26051.stderr
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T27910.hs
- + testsuite/tests/simplCore/should_compile/T27910.stderr
- + testsuite/tests/simplCore/should_compile/T27936.hs
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- + testsuite/tests/simplCore/should_compile/T7803.hs
- + testsuite/tests/simplCore/should_compile/T7803.stderr
- + testsuite/tests/simplCore/should_compile/T7803a.hs
- testsuite/tests/simplCore/should_compile/all.T
- testsuite/tests/simplCore/should_compile/simpl017.hs
- testsuite/tests/simplStg/should_compile/all.T
- + testsuite/tests/simplStg/should_compile/inferTags005.hs
- + testsuite/tests/simplStg/should_compile/inferTags005.stderr
- + testsuite/tests/simplStg/should_compile/inferTags006.hs
- + testsuite/tests/simplStg/should_compile/inferTags006.stderr
- + testsuite/tests/simplStg/should_run/InferTags007_A.hs
- + testsuite/tests/simplStg/should_run/T27831.hs
- + testsuite/tests/simplStg/should_run/T27831.stdout
- + testsuite/tests/simplStg/should_run/T27857.hs
- + testsuite/tests/simplStg/should_run/T27857.stdout
- testsuite/tests/simplStg/should_run/all.T
- + testsuite/tests/simplStg/should_run/inferTags007.hs
- + testsuite/tests/simplStg/should_run/inferTags007.stdout
- testsuite/tests/splice-imports/SI35.hs
- testsuite/tests/th/GadtConSigs_th_dump1.hs
- testsuite/tests/th/GadtConSigs_th_dump1.stderr
- + testsuite/tests/th/T27424d.hs
- + testsuite/tests/th/T27424d.stderr
- testsuite/tests/th/all.T
- testsuite/tests/typecheck/should_compile/DeepSubsumption02.hs
- testsuite/tests/typecheck/should_compile/LocalGivenEqs.hs
- testsuite/tests/typecheck/should_compile/T11254.stderr
- testsuite/tests/typecheck/should_compile/T15370.stderr
- + testsuite/tests/typecheck/should_compile/T26543_orig.hs
- + testsuite/tests/typecheck/should_compile/T27916.hs
- + testsuite/tests/typecheck/should_compile/T27994.hs
- + testsuite/tests/typecheck/should_compile/T27994a.hs
- + testsuite/tests/typecheck/should_compile/T27994b.hs
- testsuite/tests/typecheck/should_compile/T4524.hs
- testsuite/tests/typecheck/should_compile/T4969.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_compile/valid_hole_fits.stderr
- testsuite/tests/typecheck/should_fail/ClassOperator.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion2.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion3.stderr
- testsuite/tests/typecheck/should_fail/FunDepOrigin1b.hs
- testsuite/tests/typecheck/should_fail/T12785b.stderr
- testsuite/tests/typecheck/should_fail/T18851.stderr
- + testsuite/tests/typecheck/should_fail/T18851e.hs
- + testsuite/tests/typecheck/should_fail/T18851e.stderr
- + testsuite/tests/typecheck/should_fail/T18851f.hs
- + testsuite/tests/typecheck/should_fail/T18851f.stderr
- testsuite/tests/typecheck/should_fail/T22707.hs
- testsuite/tests/typecheck/should_fail/T22940.stderr
- testsuite/tests/typecheck/should_fail/T25950.stderr
- + testsuite/tests/typecheck/should_fail/T26543a.hs
- + testsuite/tests/typecheck/should_fail/T26543a.stderr
- testsuite/tests/typecheck/should_fail/T26823.stderr
- + testsuite/tests/typecheck/should_fail/T27731.hs
- + testsuite/tests/typecheck/should_fail/T27731.stderr
- + testsuite/tests/typecheck/should_fail/T27844.hs
- + testsuite/tests/typecheck/should_fail/T27844.stderr
- testsuite/tests/typecheck/should_fail/T5691.stderr
- testsuite/tests/typecheck/should_fail/T7019.hs
- testsuite/tests/typecheck/should_fail/T7437.stderr
- testsuite/tests/typecheck/should_fail/T8450.stderr
- testsuite/tests/typecheck/should_fail/T8603.hs
- testsuite/tests/typecheck/should_fail/all.T
- testsuite/tests/typecheck/should_fail/mc24.stderr
- testsuite/tests/typecheck/should_fail/tcfail019.stderr
- testsuite/tests/typecheck/should_fail/tcfail189.stderr
- + testsuite/tests/unsatisfiable/T28081.hs
- testsuite/tests/unsatisfiable/all.T
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
- testsuite/tests/warnings/should_compile/Overflow.stderr-ws-32
- testsuite/tests/warnings/should_compile/Overflow.stderr-ws-64
- + testsuite/tests/warnings/should_compile/RedundantCanonicalMethods.hs
- + testsuite/tests/warnings/should_compile/RedundantCanonicalMethods.stderr
- testsuite/tests/warnings/should_compile/T13256.stderr-ws-32
- testsuite/tests/warnings/should_compile/T13256.stderr-ws-64
- testsuite/tests/warnings/should_compile/WarnNoncanonical.hs
- testsuite/tests/warnings/should_compile/WarnNoncanonical.stderr
- testsuite/tests/warnings/should_compile/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Parsers.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
- utils/check-ppr/Main.hs
- utils/count-deps/Main.hs
- utils/dump-decls/Main.hs
- utils/haddock/CHANGES.md
- utils/haddock/doc/markup.rst
- utils/haddock/haddock-api/haddock-api.cabal
- utils/haddock/haddock-api/src/Haddock.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Parser.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Renderer.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Utils.hs
- utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/GhcUtils.hs
- utils/haddock/haddock-api/src/Haddock/Interface.hs
- utils/haddock/haddock-api/src/Haddock/Interface/ParseModuleHeader.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-api/src/Haddock/Types.hs
- utils/haddock/haddock-api/src/Haddock/Utils/Json.hs
- utils/haddock/haddock-api/test/Haddock/Backends/Hyperlinker/ParserSpec.hs
- utils/haddock/haddock-library/CHANGES.md
- utils/haddock/haddock-library/fixtures/Fixtures.hs
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.parsed
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.parsed
- utils/haddock/haddock-library/haddock-library.cabal
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser.hs
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser/Identifier.hs
- utils/haddock/haddock-library/test/Documentation/Haddock/ParserSpec.hs
- utils/haddock/haddock.cabal
- utils/runghc/Main.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/27dccdec23ee9b646270fb5ade5b70ā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/27dccdec23ee9b646270fb5ade5b70ā¦
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/io-manager-deadlock-detection] 22 commits: FIXUP review finding f1
by Duncan Coutts (ļ¼ dcoutts) 20 Nov '26
by Duncan Coutts (ļ¼ dcoutts) 20 Nov '26
20 Nov '26
Duncan Coutts pushed to branch wip/io-manager-deadlock-detection at Glasgow Haskell Compiler / GHC
Commits:
46bda42a by Duncan Coutts at 2026-11-20T15:58:19+00:00
FIXUP review finding f1
- - - - -
9741554a by Duncan Coutts at 2026-11-20T15:58:19+00:00
In the scheduler, move I/O blocking after deadlock detection
To make deadlock detection effective in the non-threaded RTS when there
are deadlocked threads and other unrelated threads waiting on I/O, we
need to arrange to do deadlock detection before we block in scheduler
to wait on I/O.
The solution is to:
1. adjust scheduleFindWork, which runs before deadlock detection, to
only poll for I/O and not block; and
2. add a step after deadlock detection to wait on I/O if there are
still no threads to run (and there's any I/O or timeouts outstanding)
The scheduleCheckBlockedThreads is now so simple that it made more sense
to inline it into scheduleFindWork.
- - - - -
5e296da3 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Remove bogus anyPendingTimeoutsOrIO guard from scheduleDetectDeadlock
The deadlock detection was only invoked if both of these conditions
hold:
1. the run queue is empty
2. there is no pending I/O or timeouts
The second condition is unnecessary. The deadlock detection mechanism
can find deadlocks even if there are other threads waiting on I/O or
timers. Having this extra condition means that we fail to detect
blocked threads if there are any threads waiting on I/O or timers.
Part of fixing issue #26408
- - - - -
09b3a791 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Don't consider pending I/O for early context switch optimisation
Context switches are normally initiated by the timer signal. If however
the user specifies "context switch as often as possible", with +RTS -C0
then the scheduler arranges for an early context switch (when it's just
about to run a Haskell thread).
Context switching very often is expensive, so as an optimisation there
cases where we do not arrange an early context switch:
1. if there's no other threads to run
2. if there is no pending I/O or timers
This patch eliminates case 2, leaving only case 1.
The rationale is as follows. The use of this was inconsistent across
platforms and threaded/non-threaded RTS ways. It only worked on the
non-threaded RTS and on Windows only worked for the win32-legacy I/O
manager. On all other combinations anyPendingTimeoutsOrIO would always
return false. The fact that nobody noticed and complained about this
inconsistency suggests that the feature is not relied upon.
If however it turns out that applications do rely on this, then the
proper thing to do is not to restore this check, but to add a new I/O
manager hint function that returns if there is any pending events that
are likely to happen *soon*: for example timeouts expiring within one
timeslice, or I/O waits on things likely to complete soon like disk I/O,
but not for example socket/pipe I/O.
The motivation to avoid this use of anyPendingTimeoutsOrIO is to
allow us to eliminate anyPendingTimeoutsOrIO entirely. All other uses
of this are just guards on {await,poll}CompletedTimeoutsOrIO and
the guards can safely be folded into those functions. This will better
cope with some I/O managers having no proper implementation of
anyPendingTimeoutsOrIO.
Ultimately this will let us simplify the scheduler which currently has
to have special #ifdef mingw32_HOST_OS cases to cope with the lack of a
working anyPendingTimeoutsOrIO for some Windows I/O managers
- - - - -
acc1666c by Duncan Coutts at 2026-11-20T15:58:19+00:00
Remove anyPendingTimeoutsOrIO guarding {poll,await}CompletedTimeoutsOrIO
Previously the API of the I/O manager used a two step process: check
anyPendingTimeoutsOrIO and then call {poll,await}CompletedTimeoutsOrIO.
This was primarily there as a performance thing, to cheaply check if we
need to do anything.
And then because anyPendingTimeoutsOrIO existed, it was used for other
things too. We have now eliminated the other uses, and are just left
with the performance pattern.
But this was problematic because not all I/O managers correctly
implement anyPendingTimeoutsOrIO (specifically the win32 ones), and now
that we also make I/O managers responsible for signals then we need to
poll/await even if there is no pending I/O or timeouts. If there is no
pending I/O or timeouts then await needs to degenerate to just waiting
forever for any signals.
- - - - -
8db4c177 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Remove anyPendingTimeoutsOrIO, it is no longer used
And this avoids the problems arising from the win32 I/O managers having
had a bogus implementation.
- - - - -
c49d4b08 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Remove second scheduler call to awaitCompletedTimeoutsOrIO
Previously awaitCompletedTimeoutsOrIO was called both before and after
deadlock detection in the scheduler. The reason for that was that the
win32 I/O managers had a bogus implementation of anyPendingTimeoutsOrIO
and this was used to guard the call of awaitCompletedTimeoutsOrIO prior
to deadlock detection. This meant the first call site was never actually
called when using the win32 I/O managers. This was the reason for the
second call: the first one was never used. What a mess.
So now we have a simple design in the scheduler:
1. poll for completed I/O, timers or signals
2. if no runnable threads: do deadlock detection
3. if still no runnable threads: block waiting for I/O, timers or
signals.
- - - - -
fde9fdaf by Duncan Coutts at 2026-11-20T15:58:19+00:00
Lift emptyRunQueue guard out of scheduleDetectDeadlock
this improved the clarity of the logic when reading the scheduler code.
And improve the comment about scheduleDoGC that was rather unclear.
- - - - -
c8738f2f by Duncan Coutts at 2026-11-20T15:58:19+00:00
Make interruptIOManager work for WinIO (non-threaded)
Fixes #27403
The idle GC scheme now fundamentally relies on interruptIOManager
working, so it's no longer acceptable for it to be missing for WinIO.
Not having it would cause lock ups.
- - - - -
20284dfd by Duncan Coutts at 2026-11-20T15:58:19+00:00
Make non-threaded deadlock detection also rely on idle GC
Only do deadlock detection GC when idle GC kicks in. This also relies on
using wakeUpRts, so now do this unconditionally. Previously wakeUpRts
was for the threaded rts only.
- - - - -
111daf0f by Duncan Coutts at 2026-11-20T15:58:19+00:00
Enable idle GC by default on non-threaded RTS
The behaviour is now uniform between the threaded and non-threaded RTS
ways. The deadlock detection now relies on idle GC for both threaded
and non-threaded ways. Previously deadlock detection did not rely on
idle GC for the non-threaded way.
Also tweak test T7275 to account for idle GC. This test's output is
sensitive to the number of major GCs run. Since this commit enables idle
GC for the non-threaded RTS, for this test that increases the number of
major GCs, since the test program is frequently idle for more than 300ms.
- - - - -
8be819a5 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Fix state of idle GC control vars with +RTS -V0
Currently when the user uses +RTS -I0, then doIdleGC is set to false.
But if the master tick interval -V is set to 0 then the idleGCDelayTime
was being set to 0 but doIdleGC was not being set to false, which is
inconsistent, and almost certainly buggy.
- - - - -
e1ce75c0 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Add a long Note [Deadlock detection]
It describes the historical and modern designs and their trade-offs.
The point is we've now unified the code for deadlock detection between
the threaded and non-threaded ways, by changing the non-threaded to
follow the same design as the threaded.
- - - - -
72e9e31d by Duncan Coutts at 2026-11-20T15:58:19+00:00
Refactor the utils providing the I/O timeout for different system APIs
We have to provide a timeout in three different time formats (int
milliseconds, struct timeval *, and struct timespec *). These are for
platform APIs including poll, select, ppoll, pselect, epoll_wait,
epoll_wait2 and in future kevent and io_uring.
Previously we had one util for each format that both worked out what
the timeout should be and converted it into the particular format. This
duplicates some logic and it also makes it awkward to modify the timeout
value (since there's no common format).
Modifying the timeout value is exactly what we want to do, in a
subsequent commit, where we want to adjust the timeout to take account
of idle GC.
- - - - -
c1e15034 by Duncan Coutts at 2026-11-20T15:58:19+00:00
Update the old select I/O manager to use the new timeout utils
This will make it much easier to adjust the timeout to take account of
idle GC.
- - - - -
c40976b9 by Duncan Coutts at 2026-11-20T15:59:13+00:00
Add opportunistic deadlock detection without idle GC
Our general design is now that comprehensive deadlock detection relies
on idle GC. This allows us to detect partial deadlocks that are not
system deadlocks. But it's not prompt.
It's a nice to have feature to be able to promptly detect the cases that
are system deadlocks. There's no hope to do this in the threaded RTS
with -N > 1, but it can be done for the non-threaded RTS and _could_ be
done for the threaded RTS with -N1.
We can integrate this feature into the general design without too many
contortions. We just need the I/O managers to check before sleeping if
they would be about to sleep indefinately with no I/O and no registered
signal handlers. If so, they can notify the idle GC that we're
deadlocked and we schedule and idle GC.
- - - - -
958a84d9 by Duncan Coutts at 2026-11-20T16:00:07+00:00
Add idle GC mode for !HAVE_PREEMPTION
We have to do idle GC (and thus deadlock detection) differently when we
do not have the ticker and the ability to interrupt the I/O manager
when it's blocking.
- - - - -
7a19f71e by Duncan Coutts at 2026-11-20T16:00:09+00:00
Add and use USED_IF_PREEMPTION to avoid warnings
- - - - -
7e568e31 by Duncan Coutts at 2026-11-20T16:00:09+00:00
Add performDeadlockDetection and export via ghc-experimental
When documenting the idle GC and deadlock detection behaviour in the
user guide, it becomes obiovus that in some cases one would want manual
control over deadlock detection.
In particular, for applications that disable idle GC, for debugging or
robustness, they may want to invoke deadlock detecting GC manually.
Bind it in ghc-internal GHC.Internal.System.Mem and re-export via
ghc-experimental in System.Mem.Experimental. It is clearly
implementation specific behaviour, especially since in GHC the deadlock
detection is tied to doing a major GC.
- - - - -
e6aa9cb3 by Duncan Coutts at 2026-11-20T16:00:09+00:00
Add tests for deadlock detection, issue #26408
We have three tests:
T26408a: make sure that we can detect a /partial deadlock/ that is not
also a /system deadlock/
T26408b: make sure that we can detect a /system deadlock/ promptly
without relying on idle GC
T26408c: make sure that we do not falsely detect a deadlock when there is
nothing to do except wait on signals
T26408d: make sure that we can detect a system deadlock with idle GC
disabled, after the idle GC timeout has elapsed.
- - - - -
fffe0932 by Duncan Coutts at 2026-11-20T16:00:09+00:00
Update the user guide with the revised idle GC behaviour
It's now not just for the threaded RTS, but general.
Add a new section in the RTS chapter: Idle GC and deadlock detection.
Provide general documentation on both topics. In particular, document
the behaviour of deadlock detection and how it depends on idle GC.
Move the existing entries for -I and -Iw to this section.
Add a changelog entry.
- - - - -
99f865ba by Duncan Coutts at 2026-11-20T16:00:09+00:00
Remove variable n_haskell_handlers which has become write-only
- - - - -
42 changed files:
- + changelog.d/idle-gc-and-deadlock-detection
- docs/users_guide/profiling.rst
- docs/users_guide/runtime_control.rst
- libraries/ghc-experimental/src/System/Mem/Experimental.hs
- libraries/ghc-internal/src/GHC/Internal/System/Mem.hs
- rts/IOManager.c
- rts/IOManager.h
- rts/IdleGC.c
- rts/IdleGC.h
- rts/RtsFlags.c
- rts/RtsSymbols.c
- rts/Schedule.c
- rts/Schedule.h
- rts/Timer.c
- rts/include/rts/OSThreads.h
- rts/include/rts/storage/GC.h
- rts/posix/Poll.c
- rts/posix/Poll.h
- rts/posix/Select.c
- rts/posix/SelectBis.c
- rts/posix/SelectBis.h
- rts/posix/Signals.c
- rts/posix/Timeout.c
- rts/posix/Timeout.h
- rts/win32/AsyncMIO.c
- rts/win32/AsyncMIO.h
- rts/win32/AsyncWinIO.c
- rts/win32/AsyncWinIO.h
- rts/win32/AwaitEvent.c
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout-mingw32
- testsuite/tests/profiling/should_run/Makefile
- testsuite/tests/rts/Makefile
- + testsuite/tests/rts/T26408a.hs
- + testsuite/tests/rts/T26408a.stderr
- + testsuite/tests/rts/T26408b.hs
- + testsuite/tests/rts/T26408b.stderr
- + testsuite/tests/rts/T26408c.hs
- + testsuite/tests/rts/T26408c.stdout
- + testsuite/tests/rts/T26408d.hs
- + testsuite/tests/rts/T26408d.stderr
- testsuite/tests/rts/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3a2e7e819f8053f3928d0cc1de0421ā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3a2e7e819f8053f3928d0cc1de0421ā¦
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc] Pushed new branch wip/dcoutts/scheduler-clarity
by Duncan Coutts (ļ¼ dcoutts) 20 Nov '26
by Duncan Coutts (ļ¼ dcoutts) 20 Nov '26
20 Nov '26
Duncan Coutts pushed new branch wip/dcoutts/scheduler-clarity at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/dcoutts/scheduler-clarity
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/marge_bot_batch_merge_job] 12 commits: NCG: List each destination of a jump table once
by Marge Bot (ļ¼ marge-bot) 20 Nov '26
by Marge Bot (ļ¼ marge-bot) 20 Nov '26
20 Nov '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
483477c7 by Sylvain Henry at 2026-11-20T10:33:16-05:00
NCG: List each destination of a jump table once
jumpDestsOfInstr listed a block once per jump table entry that named
it. The linear register allocator makes a fixup block per listed
destination, so such a block got several fixup blocks. The patch of
the jump sends every entry to the first one. The other fixup blocks
were dead code, and the CFG had an edge to each of them.
jumpDestsOfInstr now lists each destination once, in every backend.
joinToTargets asserts it in debug builds.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
15aba315 by Andreas Klebinger at 2026-11-20T10:33:16-05:00
x86 ncg: Track the current block in NatM to keep the CFG in sync
The x86 NCG uses a CFG for code layout. When instruction selection
makes new blocks (word2Float#, cmpxchg loops, 64-bit shifts on i386),
it must add them to the CFG. Some sites did not. The CFG went out of
sync, the layout was bad, and the register allocator panicked when it
added fixup blocks (#27694, #27915).
NatM now keeps the current block in its state. Combinators update the
CFG and the current block together. See Note [Updating the CFG during
CodeGen] in GHC.CmmToAsm.Monad.
Other changes:
* -dasm-lint checks that the jumps in the code and the edges in the
CFG agree in both directions. This found a second desync: the CFG
did not follow the jumps that allocMoreStack retargets. The new
addPreentryBlock fixes it.
* The code must be emitted in generation order, because the CFG
records new blocks in that order. A store now generates the code of
its value before the code of its address, in the order it emits
them. Atomic operations take their address from the new
getNonClobberedAmode, so the code of their other operands cannot
clobber it.
Fixes #27694, #27915
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
c27f4850 by Sylvain Henry at 2026-11-20T10:33:16-05:00
x86 ncg: Maintain the CFG on i386
The i386 NCG now keeps its CFG in sync with the code (see the previous
commit), so backendMaintainsCfg is now True for i386. i386 gets the
CFG based code layout, dead code elimination and the -dasm-lint check,
like x86-64.
The compiler allocates more on i386: the CFG now goes through the
register allocator, branch shortcutting and optimizeCFG, which i386
skipped before. x86-64 already does this work.
Metric Increase:
CoOpt_Read
ManyAlternatives
T10421
T12425
T12707
T13056
T13253
T13253-spj
T13960
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T19695
T20049
T21839c
T24471
T26425
T26989
T5642
T6048
T783
T9233
T9630
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
9424f981 by Simon Peyton Jones at 2026-11-20T10:33:18-05:00
Redesign the noinline magic
The principal goal of this MR is to avoid `noinline` getting in the way
of strictness analysis and specialisation. It involves a bit of redesign.
Main idea:
* When simplifying `noinline (f e1 e2)`, switch off inlining when
simplifying `f`, but not when simplifying `e1` and `e2`.
* Mechanism: see `simplOutId`, the `noinlineIdKey` case
* If: we see `noinline (f e1) e2`, the simplifier moves the `e2` inside;
see the `splitContArgs` call. This is important so you can write
`noinline f e1 e2` and have it mean the same as `noinline (f e1 e2)`.
* Now `f` sees all its arguments, hence:
* Fixes #27724 (noinline inhibits specialisation)
* Fixes #23911 (noinline worsens demand signatures)
* Also fixes #27803 where we were not respecting `noinline` if the RHS
was trivial
See Note [noinlineId magic] for lots of specifics. It's surprisingly tricky!
For some reason a couple of perf tests allocate 1.2% less at compile time,n
namely T29872 and T8095. Geom mean decease of 0.1%
Metric Decrease:
T9872d
- - - - -
eac98b68 by fendor at 2026-11-20T10:33:19-05:00
`ghc -M`: Add support for link nodes to json output
`LinkNode`s are part of the module graph and indicate that a certain
linking artefact is to be produced from other module graph nodes.
We expose `LinkNode`s in the output of `ghc -M -dep-json`, allowing
consumers to see when a linking artefact is to be produced.
Only the JSON output format of `ghc -M` supports `LinkNode` as it is
unclear how the Makefile output should be retrofitted to express the
dependencies, and whether it would require a feature guard.
Closes #28007
- - - - -
5983563d by Ryan Scott at 2026-11-20T10:33:21-05:00
GHC.HsToCore.Quote: Quote \cases with the correct type
Previously, `\cases` expressions inside of Template Haskell quotes would
incorrectly use the `Match` type instead of `Clause` for the element type. We
now use `nonEmptyCoreList` when quoting `\cases`, which infers the correct type
automatically. This works because `\cases` has an invariant that the list of
clauses is always non-empty.
Fixes #27826.
- - - - -
e7e758dc by Simon Peyton Jones at 2026-11-20T10:33:23-05:00
Better desugaring for bang patterns
Ticket #27862 showed that we were desugaring bang patterns in a
silly way, which led to bad code. This small fix makes it much
better.
I ended up refactoring `decomposeFirstPat` to be of type
(LPat -> LPat) instead of (Pat -> Pat)
which made it much easier to keep the locations correct.
On the way I also fixed #28137, a missing warning.
See Note [Tidying patterns] which has new (TP1) and (TP2)
and Note [Grouping equations] especially (GE1)
- - - - -
6b8de959 by Hannes Siebenhandl at 2026-11-20T10:33:24-05:00
Use Set operations over Foldable operations
Use `O(log n)` operations over `O(n)` for all call-sites of `hsc_all_home_unit_ids`.
- - - - -
1d3c61e8 by Alan Zimmerman at 2026-11-20T10:33:26-05:00
EPA: Use AnnList in DecBrl
Via updating the TTG extension point payload
- - - - -
833950e1 by David Eichmann at 2026-11-20T10:33:27-05:00
Fix race condition in IOManager test
- - - - -
495d5193 by Simon Peyton Jones at 2026-11-20T10:33:29-05:00
Fix a zonking bug
As #28135 showed, we were failing to zonk some type-variable
binders before doing scoped-sort dependency analysis, resulting
in chaos.
The fix is easy.
- - - - -
dc81dc01 by mangoiv at 2026-11-20T10:33:31-05:00
ci: nightly push can run on any arch
- - - - -
131 changed files:
- .gitlab-ci.yml
- + changelog.d/27694
- + changelog.d/T27137
- + changelog.d/T27724
- + changelog.d/T27862
- + changelog.d/T28135
- + changelog.d/make-depends-link-nodes
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/Builtin/WiredIn/Prim.hs
- compiler/GHC/Builtin/WiredIn/Types/Box.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/Core/Opt/SetLevels.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Core/TyCo/Rep.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToStg/Prep.hs
- compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- compiler/GHC/HsToCore/Pmc/Solver/Types.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Parser.y
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Instance/Class.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/Types/Origin.hs
- + distrib/configure.ac
- docs/users_guide/make-depends-json-schema-1_0.json
- libraries/ghc-internal/src/GHC/Internal/Exts.hs
- libraries/ghc-internal/src/GHC/Internal/Magic.hs
- testsuite/tests/ado/T22483.stderr
- + testsuite/tests/codeGen/should_compile/T27694.hs
- + testsuite/tests/codeGen/should_compile/T27694c.hs
- + testsuite/tests/codeGen/should_compile/T27694d.hs
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_run/T27694b.hs
- + testsuite/tests/codeGen/should_run/T27694b.stdout
- + testsuite/tests/codeGen/should_run/T27915.hs
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-32
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-64
- testsuite/tests/codeGen/should_run/all.T
- testsuite/tests/corelint/LintEtaExpand.hs
- + testsuite/tests/deSugar/should_compile/T27862.hs
- + testsuite/tests/deSugar/should_compile/T27862.stderr
- + testsuite/tests/deSugar/should_compile/T27862a.hs
- + testsuite/tests/deSugar/should_compile/T27862a.stderr
- + testsuite/tests/deSugar/should_compile/T27862b.hs
- + testsuite/tests/deSugar/should_compile/T27862b.stderr
- + testsuite/tests/deSugar/should_compile/T27862c.hs
- + testsuite/tests/deSugar/should_compile/T27862c.stderr
- + testsuite/tests/deSugar/should_compile/T27862d.hs
- + testsuite/tests/deSugar/should_compile/T27862d.stderr
- + testsuite/tests/deSugar/should_compile/T28137.hs
- + testsuite/tests/deSugar/should_compile/T28137.stderr
- testsuite/tests/deSugar/should_compile/all.T
- testsuite/tests/deSugar/should_run/dsrun008.stderr
- + testsuite/tests/dmdanal/should_compile/T23911.hs
- + testsuite/tests/dmdanal/should_compile/T23911.stderr
- testsuite/tests/dmdanal/should_compile/all.T
- testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/mhu04/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu04/app/Utils.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu04/unitApp
- + testsuite/tests/driver/mkdepend/mhu04/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu05/test/Spec.hs
- + testsuite/tests/driver/mkdepend/mhu05/unitApp
- + testsuite/tests/driver/mkdepend/mhu05/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/unitTest
- + testsuite/tests/driver/mkdepend/mkdepend02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend02/Main.hs
- + testsuite/tests/driver/mkdepend/mkdepend_bkp_01/bkp01.bkp
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-makefile
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-prim-exports.stdout
- testsuite/tests/interface-stability/ghc-prim-exports.stdout-mingw32
- testsuite/tests/pmcheck/should_compile/T24234.stderr
- testsuite/tests/rts/IOManager.hsc
- testsuite/tests/rts/all.T
- testsuite/tests/simplCore/should_compile/T18995.stderr
- + testsuite/tests/simplCore/should_compile/T27724a.hs
- + testsuite/tests/simplCore/should_compile/T27724a.stderr
- + testsuite/tests/simplCore/should_compile/T27803.hs
- + testsuite/tests/simplCore/should_compile/T27803.stderr
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/th/T27826.hs
- testsuite/tests/th/all.T
- + testsuite/tests/typecheck/should_compile/T28135.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_fail/T17940.stderr
- testsuite/tests/typecheck/should_fail/tcfail203a.stderr
- utils/check-exact/ExactPrint.hs
- utils/genprimopcode/Main.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c1c8e3886df4e0df2655dc29b7e9f0ā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c1c8e3886df4e0df2655dc29b7e9f0ā¦
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/has-field-hie] 221 commits: ci: Actually pass --ignore-perf-failures to the testsuite driver
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
20 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/has-field-hie at Glasgow Haskell Compiler / GHC
Commits:
4e9297ea by Simon Jakobi at 2026-09-11T08:32:45-04:00
ci: Actually pass --ignore-perf-failures to the testsuite driver
684c0018d9 changed the IGNORE_PERF_FAILURES handling to append to
RUNTEST_ARGS with bash array syntax, but the three use sites still
expand RUNTEST_ARGS as a scalar, which yields only the first array
element. The appended flag was therefore dropped in every job, so
perf improvements kept failing Marge Bot batches and master pipelines,
contrary to #19562.
Append as a string instead, matching the existing --force-colors
append in test_hadrian.
Fixes #27563.
Assisted-by: Claude Fable 5.1
- - - - -
4f78dfdf by Simon Jakobi at 2026-09-11T08:33:24-04:00
testsuite: Give T26537 a 1.5x compile timeout
Its -fregs-graph compile step tends to time out in unoptimized builds
(#27188, #27776).
Assisted-by: Claude Fable 5.1
- - - - -
130286e3 by Alan Zimmerman at 2026-09-11T08:34:08-04:00
EPA: Remove ListBanana / ListParens from AnnListBrackets
This is a step towards making AnnList only represent
lists of items which can have either braces or layout.
- - - - -
a9827d13 by Simon Jakobi at 2026-09-11T18:53:32-04:00
Reject ~, UNPACK and multiplicity annotations on type data fields
Only `!` was rejected so far. `~`, UNPACK and multiplicity annotations
were silently accepted. None of them make sense at the type level, so
restriction (R3) of Note [Type data declarations] now covers all of
them.
Fixes #27732.
Assisted-by: Claude Fable 5.1
- - - - -
c71d5e23 by Alan Zimmerman at 2026-09-11T18:54:11-04:00
EPA: Add a Note for the exact print main loop
- - - - -
7a108e43 by Simon Jakobi at 2026-09-12T18:35:59-04:00
FastString: Drop mkFastStringWith's constructor callback
All three callers passed the same callback, a partial application of
mkNewFastStringShortByteString to the string being interned. That
partial application is allocated as a closure before the table lookup,
on the common hit path too, although the callback is needed only after
a miss.
Drop the parameter and call mkNewFastStringShortByteString directly
after a miss. Since nothing is passed "with" anymore, rename the
function to internSB.
Suggested by Simon PJ in #27528:
https://gitlab.haskell.org/ghc/ghc/-/work_items/27528#note_687031
Assisted-by: Claude Fable 5
- - - - -
82c73b22 by Alan Zimmerman at 2026-09-12T18:36:38-04:00
EPA: More targeted HsDo exact print annotation
HsDo is multi-purpose, as encoded in its HsDoFlavour field. Some of
these are in a layout context (DoExpr, MDoExpr), others are not
(ListComp, MonadComp).
We are moving towards using AnnList only in layout contexts, so we
switch the HsDo TTG annotation from holding an AnnList for this, to
holding
Either (EpToken "[", EpToken "]") AnnList
This also allows us to trim down AnnListBrackets to only have braces
or None, thereby opening the door for unification with the existing
layout context data type EpLayout.
- - - - -
749d2448 by Luite Stegeman at 2026-09-15T14:07:01-04:00
rts: handle large CONSTR closures in compacting GC
The function update_fwd_large in the compacting GC could run into
an unexpected object with the following error:
internal error: update_fwd_large: unknown/strange object 1
Closure type 1 is CONSTR. This patch adds cases for CONSTR and
CONSTR_NOCAF.
This is the same problem as #27434 (large AP closures, fixed by
cca0d58963), which missed this case.
Fixes #27649
- - - - -
177d6155 by Luite Stegeman at 2026-09-15T14:07:02-04:00
testsuite: fix T27434 test with compacting GC
Ensure that the interpreter is actually run with the compacting GC
- - - - -
5796aa63 by Luite Stegeman at 2026-09-15T14:07:49-04:00
rts: initialise the stack frame header for mask_frame and apply_mask_frame
We must leave the stack in consistent state before jumping to
mask_frame or apply_mask_frame because they may result. Failing
to do so could lead to a crash if there were waiting exceptions.
Fixes #27651
- - - - -
2486cc92 by Simon Peyton Jones at 2026-09-15T14:08:36-04:00
Re-introduce the "weird SpecDict" case
In this commit
commit f80375dd4945350a1d784e436975b48b9c736eaf
Author: Simon Peyton Jones <simon.peytonjones(a)gmail.com>
Date: Sun Jun 29 15:26:58 2025 +0100
Refactor of Specialise.hs
I removed a test for a dictionary with unbound type variables. This
turned out to be wrong; see #27629.
So this MR re-introduces it.
- - - - -
8e09a46f by Duncan Coutts at 2026-09-15T20:11:35-04:00
Refactor (and rename) removeFromQueues, to simplify I/O managers
Rename it to unblockAndAppendToRunQueue which better reflects what it is
intended to do.
The post-condition for unblockAndAppendToRunQueue is that the TSO is on
the run queue or it is in the process of migrating to another cap.
Previously it achieved that by always directly adding the TSO to the run
queue itself.
But this actually made things more complicated for the I/O managers,
because it meant they needed a separate code path for notifying for
cancellation compared to notifying for completion. The general
notification code would always add the TSO to the run queue itself.
So the improvement is to allow different cases in
unblockAndAppendToRunQueue to achieve the same outcome in different
ways: either directly adding to the run queue or calling helper
functions that do so themselves.
This then allows the new I/O managers to share code between the sync and
async cancellation, and to reuse their notifyIOCompletion helpers for
cancellation. This avoids a source of bugs where the completion path may
be updated but the cancellation path may be forgotten, or similarly in
future for sync/async operations.
Update all the existing in-RTS I/O managers, and the posix timeout code.
- - - - -
d668782c by Duncan Coutts at 2026-09-15T20:11:35-04:00
Document that awaitCompletedTimeoutsOrIO expects an empty run queue
This was true before but implicit and not relied on much. It's better to
be explicit, and allow things to depend on it.
- - - - -
11d938bb by Duncan Coutts at 2026-09-15T20:11:35-04:00
Store the I/O opcode and fd in the StgAsyncIOOp
This will be useful in several I/O managers and it is handy for logging
and debugging.
It also doesn't increase the size of the StgAsyncIOOp structure. There
was enough spare padding space already.
Update the poll I/O manager to set the new fields.
Add a helper function to convert the enum IOReadOrWrite into the enum
IOOpCode. Also change IOReadOrWrite to be an enum without a typedef, for
consistency with other enumerations in IOManager.h
- - - - -
bfa87882 by Duncan Coutts at 2026-09-15T20:11:36-04:00
Add a new I/O manager based on select()
Yes, this is the second such I/O manager, but it is a modern
re-implementation based on the new in-RTS I/O manager infrastructure. So
it is cleaner and faster than the old select I/O manager.
Why do we need another I/O manager based on select? Why isn't the poll()
one good enough as a baseline portable unix I/O manager? Because macOS.
Apple Inc. is why we cannot have nice things.
The man page for poll on macOS documents the fact that it does not work.
At least, it does not work for all files. Specifically, it does not work
for device files. Whereas macOS select() does work for device files.
Aaaaarg!
We _do_ want to deprecate and remove the old select I/O manager, but due to
macOS we cannot do that until we have a replacement. This is that
replacement. Until of course a nice new k-queue I/O manager arrives,
which could become the new default for macOS and FreeBSD.
Interestingly, this select I/O manager is actually faster than the poll
one, on Linix, in some circumstances: specifically when many Haskell
threads are waiting on the same fd. The poll I/O manager does O(n) work
for n threads waiting on I/O, whereas the select one does O(fds) work
for the number of fds that threads are waiting on. Usually this is 1:1,
so it's not noticable, but one can concoct extreme benchmarks to show
the difference.
- - - - -
8e9de15a by Duncan Coutts at 2026-09-15T20:11:36-04:00
Minor updates in the poll I/O manager to keep in sync with select
This keeps it in sync with select one. The changes are based on code review
while implementing the new select I/O manager. The two I/O managers are so
similar in structure that it makes sense to try to minimise the diff between
them. This should aid understanding, and fixes to both in future.
- - - - -
222668bb by Duncan Coutts at 2026-09-15T20:11:36-04:00
Document the new select I/O manager in the user guide
in the RTS section about I/O managers.
And add a changelog entry.
- - - - -
0f48735b by Cheng Shao at 2026-09-15T20:12:23-04:00
Revert "wasm: workaround WebKit bug in dyld"
This reverts commit c9b8465c2c338176fcab9d197e9d31f4aee11f68. The
underlying webkit bug has been fixed in
https://commits.webkit.org/314219@main. Closes #27564.
- - - - -
809294f1 by Luite Stegeman at 2026-09-15T20:13:08-04:00
rts: make stg_threadLabelzh return a valid pointer for unlabeled threads.
This fixes a segfault in the GC caused by stg_threadLabelzh returning
a 0 pointer in a GC pointer field.
stg_threadLabelzh returns a tuple of type (# Int#, ByteArray# #). If a
thread has no label, the second field is unused. We must still return
a valid heap object pointer.
Instead of returning 0, we now return stg_DEAD_SLOT_closure.
fixes #27618
- - - - -
e2d57026 by Luite Stegeman at 2026-09-15T20:13:54-04:00
JS: fix selector thunk handling
fix a bug where entering a selector thunk could lead to a crash
if the selected field was still a thunk.
fixes #27788
- - - - -
1b4a622f by sheaf at 2026-09-17T02:39:13-04:00
Improvements to type/data family handling
This commit makes several improvements to the treatment of type and data
families in GHC:
- We consistently use "type family" instead of "type synonym family"
to avoid a confusion with type synonyms. For example:
- OpenSynFamilyTyCon ==> OpenTypeFamilyTyCon
- ClosedSynFamilyTyCon => ClosedTypeFamilyTyCon
- Various functions that were specific to data families have been
renamed to make this clear. For example:
- tyConFamInst_maybe ==> tyConDataFamInst_maybe
- isFamInstTyCon ==> isDataFamInstTyCon
- 'FamTyConFlav' has been refactored so that all closed type families
share a single 'ClosedTypeFamilyTyCon' constructor.
The corresponding 'IfaceFamTyConFlav' type was updated similarly.
This is then used to tidy up the implementation of
GHC.Core.FamInstEnv.reduceTyFamApp_maybe.
- - - - -
c5aa9098 by sheaf at 2026-09-17T02:39:13-04:00
Small refactor of lookupFamInstEnv
This commit reworks the code for looking up family instances in
GHC.Core.FamInstEnv, reducing duplication a little bit.
No change in behaviour.
- - - - -
a3ad4588 by sheaf at 2026-09-17T02:39:14-04:00
Use a type family for boxing unboxed types
This commit overhauls the way in which unboxed types are boxed, as per
the updated Note [Boxing constructors] in GHC.Builtin.WiredIn.Types.Box.
The main change is to allow boxing to be parametrised by representation,
e.g. making 'Box ty' a valid type. We achieve this by implementing 'Box'
using a closed type family:
newtype Box (a :: TYPE r) = Box (BoxTF r)
type BoxTF :: RuntimeRep -> Type
type family BoxTF r where
BoxTF IntRep = BoxInt
BoxTF Int8Rep = BoxInt8
BoxTF WordRep = BoxWord
BoxTF LiftedRep = Any @Type
BoxTF (TupleRep [r1, r2]) = (BoxTF r1, BoxTF r2)
...
BoxTF (SumRep rs) = BoxSum rs
This new design solves the following problems:
- It allows boxing a type whose 'RuntimeRep' has not yet been
determined (e.g. because we only learn the 'RuntimeRep' after
constraint solving). That is, 'Box @r a' is a perfectly valid type
even if 'r' is an unfilled metavariable. This is a requirement
to fix #25065 (in which we need to box a type whose 'RuntimeRep'
is only filled in during constraint solving).
- It handles boxing of unboxed tuples and unboxed sums, via recursive
boxing. See Note [Boxing TupleRep and SumRep] in
GHC.Builtin.WiredIn.Types.Box.
'Box', 'BoxTF' and all of the boxing data constructors are defined in
a new 'ghc-internal' module, 'GHC.Internal.Box'. This module contains
nothing but wired-in declarations, and GHC never loads its interface on
account of a wired-in thing (GHC.Builtin.Modules.isWiredInOnlyModule);
see Note [Loading instances for wired-in things] in GHC.Iface.Load.
The individual boxing data constructors are deliberately left as an
internal implementation detail, and not exported. The intended API is
via the two new magic 'Id's:
box :: forall {r} (a :: TYPE r). a -> Box a
unbox :: forall {r} (a :: TYPE r). Box a -> a
exported from 'GHC.PrimOps' (in 'ghc-experimental'). The old boxing
data types (IntBox, WordBox, FloatBox, DoubleBox, DictBox) are no longer
exported from base (CLC proposal #421).
We use this new design to consistently desugar:
- parallel comprehensions (GHC.HsToCore.ListComp.{deListComp,dsMcStmt})
- then/group/using statements (GHC.HsToCore.ListComp.{dsTransStmt,dsMcStmt})
- recursive do blocks (mdo/rec) (GHC.HsToCore.Expr.dsDo)
- arrows (GHC.HsToCore.Arrows)
by consistently using 'box'/'unbox' to deal with unboxed types being put
into big tuples. We also adapt 'GHC.Tc.Gen.Match.{tcMcStmt,tcDoStmt}'
to create fresh /representation-polymorphic/ type variables for the
binders that we are going to put into a big tuple (previously, GHC only
allowed lifted types in that position).
These desugaring of box and unbox is explained in
Note [Desugaring box & unbox] in GHC.Core.Make.Box. Roughly speaking,
the desugaring looks like:
box @r @ty e ==> K e
unbox @r @ty e ==> case e of K x -> x
where 'K' is the boxing data constructor at RuntimeRep 'r'. It's
slightly more complicated than that in practice: we first need to
insert a cast (see Note [The canonical type of a RuntimeRep]) using the
new 'CanonicalProv' 'UnivCoProvenance', and unboxed tuples/sums need
recursive logic explained in Note [box/unbox for unboxed tuples and sums],
including a specific 'BoxSum' datatypes for unboxed sum (which also
needed a wired-in type-level list indexing type family (!!)).
The desugaring happens in two ways:
- Occurrences of 'box'/'unbox' emitted by the typechecker are
eliminated in the 'ds_app_var' case of GHC.HsToCore.Expr.
- Other code that needs to box/unbox emits the appropriate code inline.
This includes the big tuple machinery of GHC.Core.Make used by the
desugarer (GHC.HsToCore.{Utils,Binds,Arrows,ListComp}) as well as
the float-out pass (GHC.Core.Opt.SetLevels).
Core Lint checks that no occurrence of 'box'/'unbox' survives desugaring.
On the way, we overhaul the litany of big tuple functions by introducing
data BigTupleLayout = BoxedElements | BareElements
to distinguish the two kinds of "big tuples" that GHC routinely deals
with; for example 'mkBigCoreVarTupSolo' becomes 'mkBigCoreVarTup BareElements'.
All of this code is moved to the new module GHC.Core.Make.BigTuple.
Fixes #20864 #22336 #22473 #25065 #27331
-------------------------
Metric Decrease:
T9872a
-------------------------
- - - - -
4cf7628a by Evgeny Malyshev at 2026-09-17T02:39:56-04:00
Fix the CompactionFailed documentation link to compact
The old Haddock reference links into base instead of ghc-compact.
Use an explicit URL because ghc-compact depends on base, not vice versa.
Fixes #27558
Assisted-By: OpenAI Codex
- - - - -
098bba70 by Facundo DomĆnguez at 2026-09-17T14:57:41-04:00
Remove the call to hoistFlag from processCmdLineP
This call was undesirable because it was causing a reconstruction
of the list of flag processors.
Even relying on list fusion would not be sufficient because we want
to replace the list with a data structure with faster lookups to
address #25763.
The removal is done in two moves:
* We move CmdLineP to CmdLine.hs
* Then we move the effect of hoisting to processArgs via a new function
hoistEwM
- - - - -
e01799c7 by Facundo DomĆnguez at 2026-09-17T14:57:42-04:00
Do not create duplicate flag processors for the -W flag
This makes simpler implementing the command line parser with a trie map
holding flag processors. If we were to allow duplicate flag processors
for any flag, the trie map would need to be a multimap.
- - - - -
3875b257 by Facundo DomĆnguez at 2026-09-17T14:57:42-04:00
Replace the list of flag processors with a trie map in `processArgs`
Previously `GHC.Driver.CmdLine.findArg` was called for each
command-line argument, doing a linear search on the list of flag
processors each time. This was somewhat costly as the list of flag
processor has near 2000 elements.
A lookup with a trie map is faster in general, but the speed up is
only noticeable when calling `GHC.Driver.CmdLine.processArgs` sufficient
times, so the amount of lookups piles up. This could happen in large
projects with many units each having many dependencies. If only a
module needs to be recompiled, the user still needs to wait for all of
the flag parsing to complete.
The benchmark at testsuite/tests/perf/compiler/cmdline-parser shows a
10x speed up when using the trie.
The trie map is implemented in `GHC.Data.StringTrie`.
The design is explained in Note [Processing command line argument fast]
in GHC.Driver.Session.
The commit also:
* adds two property-based tests for trie map operations,
* adds a benchmark of the command line parser, and
* renames the predicate `arg_ok` to `valid_flag_suffix` to decide what
flag processor should be used when there are multiple matching
prefixes on a flag.
Fixes #25763.
- - - - -
5236634a by Andreas Klebinger at 2026-09-17T14:58:24-04:00
Compile Word64{Map,Set} with -O2 always.
This is the hottest code and even if we build GHC with -O0 otherwise -O2
pays off for these modules.
Fixes #27814.
- - - - -
545fd4fb by ARATA Mizuki at 2026-09-22T15:03:24-04:00
Change the C types of hs_{bitrev,bswap}{16,32} to match the Haskell types
bitReverse{16,32}# and byteSwap{16,32}# have the type
Word# -> Word#, but their C correspondents took and
returned StgWord{16,32}.
The mismatch on bitReverse16# led to the problem reported
in #27299. Although no similar issue is reported for
bitReverse32# and byteSwap{16,32}#, it seemed wise to
change them proactively.
This commit fixes the mismatch by changing the C type.
Fixes #27299
- - - - -
bf17f289 by fendor at 2026-09-22T15:04:05-04:00
Don't lose instances from shadowed imported modules with the same name
When we look for instances below the current module, we need to check
the unit id as well when we check for whether the module is the current
module, otherwise we ignore modules we import that have the same name as
the import module.
Adds regression test.
- - - - -
53eead15 by Wolfgang Jeltsch at 2026-09-24T20:12:03-04:00
Correct the documentation of `explicitUnits`
Resolves #27787.
- - - - -
35bf6f4b by Simon Jakobi at 2026-09-24T20:12:49-04:00
Remove stale specHeader bullet from Note [Don't make fillers for constraint types]
The Note said that Specialise.specHeader also calls mkAbsentFiller.
abfc224a27c removed that call: the specialiser no longer drops dead
arguments at all, see Note [Do not drop dead args from specialisations]
in GHC.Core.Opt.Specialise.
Assisted-by: Claude Fable 5.1
- - - - -
1abef1ef by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Improve the `mhu-closure` makefile
- - - - -
a79a68ea by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Make `ghci-multi` hide all unneeded packages
- - - - -
d6e72450 by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Improve the definition of the home unit closure property
- - - - -
c9a2766d by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Re-implement the home unit closure check
Compared to the previous implementation, the new one has the following
advantages:
* It is correct.
- It distinguishes between units that have the same unit ID but
different ABI hashes.
- When `-hide-all-packages` is not used, it considers as home unit
dependencies also units that are made implicitly available
because they are in the package database.
* It seems to be faster in usual settings.
- In particular, it does not have a preparation phase in which it
merges the dependency information from all home units, so that
its running time does not grow linearly with the size of the
package database in normal Cabal scenarios.
* It is (hopefully) clearer.
* It is better documented.
- - - - -
fa96acf8 by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Remove erroneous GHC flag in `hadrian-multi`
The flag was `-Werror=-Wno-error=incomplete-record-selectors`. Its
purpose was to permit incomplete record selectors, but because of the
illegal combination of `-Werror=` and `-Wno-error` it was ignored,
without any negative consequences.
- - - - -
9f48a5b9 by Alan Zimmerman at 2026-09-25T17:02:50-04:00
EPA: Add specific layout field to AnnList
Up to now AnnList has effectively served to represent lists of things
having layout, regardless of whether they do or not.
In Haskell, layout is optional in many places, as there is also an
alternative syntax using braces and semi-colons, which is free-form.
This commit introduces AnnListLayout, a data structure capturing this
distinction.
It is deliberately set up similarly to EpLayout, so that these two can
be merged in time.
The transition is done mechanically, where AnnListBraces is not used
yet, the original Nothing case maps to AnnListNoLayout, and the Just
case to AnnListLayout.
Later commits will fine tune these against the actual parser layout.
- - - - -
234bab08 by Vladislav Zavialov at 2026-09-29T17:22:54-04:00
Add regression test for #7803
Commit 2effe18ab5, first shipped with GHC 8.2.1, fixed #7803 "Superclass
methods are left unspecialized".
This change turns the example from the ticket description into a regression
test, checking that foo1 is fully specialised at Double, with no calls to the
overloaded exp5Tail.
Closes #7803
Assisted-by: Claude Opus 5
- - - - -
c406135c by Andreas Klebinger at 2026-10-01T06:57:28-04:00
RTS: Update flag parsing/handling:
Using 0 as argument to any of these flags now resets the flags setting to default:
- ``-n0`` disables nursery chunking.
- ``-K0`` (or a bare ``-K``) removes the stack size limit.
- ``-M0`` removes the heap size limit.
- ``-H0`` resets the suggested heap size, including the nursery scaling set by ``-H``.
- ``-AL0`` makes the large object allocation limit follow ``-A`` again.
GC Generations are now limited to 64.
-n larger than -A now emits a warning and disables chunking.
Fixes #27830 #27829
- - - - -
984ee82b by Andreas Klebinger at 2026-10-01T06:58:10-04:00
Fix MultiLayerModules timeout multiplier.
We accidentally used the compile multiplier for ghci commands which
use the run timeout setting to set the timeout.
Fixes #26263 and #27796.
- - - - -
50a9cf26 by Andreas Klebinger at 2026-10-01T06:58:10-04:00
testsuite: Include runtime in JUnit report.
- - - - -
e358619f by Alan Zimmerman at 2026-10-01T06:59:01-04:00
EPA: Use EpaLocation in EpVirtualBraces
Haddock processing uses EpLayout.EpVirtualBraces to record the current
layout column, for allocating haddock comments correctly.
For exact printing, we need the line as well as the col, so we know
how many lines to skip when the indented code block starts.
This commit updates EpLayout.EpVirtualBraces so that it carries an
EpaLocation instead of just the Int column, to allow it to be used for
both purposes.
It is a simple mechanical change, with no other impact, but it allows
us to use EpLayout instead of AnnListLayout in AnnList, in the next
commit in this series.
- - - - -
1d2a26ee by Andrew Lelechenko at 2026-10-01T20:22:04-04:00
Remove bitSize from MINIMAL pragma of class Bits
Cf. https://github.com/haskell/core-libraries-committee/issues/441
The function is deprecated for 12 years and has a default implementation,
yet it was never removed from the MINIMAL pragma, putting library authors
in a very awkward position. Let's finally remove bitSize from MINIMAL.
- - - - -
3cc21e4c by Hannes Siebenhandl at 2026-10-01T20:22:59-04:00
Add regression test for #27641
- - - - -
c35096f5 by Hannes Siebenhandl at 2026-10-01T20:23:00-04:00
Don't `:add` modules the loader will reject
Only home modules can be actually added to the loader context, thus we
only accept the module if it belongs to a home unit.
- - - - -
a563cb27 by Simon Jakobi at 2026-10-02T17:37:36-04:00
ci: accept modified changelog.d entries in lint-changelog
The changelog guide says to extend an existing entry rather than add a
new one when the feature is already documented. lint_changelog only
counted added files, so such MRs failed before the validator ran.
Fixes #27779.
Assisted-by: Claude Fable 5.1
- - - - -
03082cd4 by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix warning flag name in the semaphore-v2 entry
The entry refers to -Wsemaphore-version-mismatch, which does not exist.
The warning GHC emits when it cannot use a -jsem semaphore, including
on a protocol version mismatch, is -Wsemaphore-open-failure.
Context: !15729, #25087
Assisted-by: Claude Fable 5.1
- - - - -
a93705ee by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix the CLC proposal link in the T27455 entry
The entry used the Sphinx :ref: role with a URL as its target. :ref:
resolves only internal labels, so the generated release notes would
show the proposal name without a link. Use the plain hyperlink form
like the other entries.
Context: !16274, #27455
Assisted-by: Claude Fable 5.1
- - - - -
54381079 by Hannes Siebenhandl at 2026-10-02T17:39:01-04:00
Extend the `TrustOverlay` for wired-in units
The TrustOverlay only contained the `UnitId` of all on-disk units.
However, wired-in units are referred to by their wired-in unit id, which
is not the same as the on-disk unit id.
Thus, trust checks for wired-in units failed because the lookup was
using the wired-in unit, which wasn't present in the `TrustOverlay`.
We fix #27834, by copying the trust info for wired-in unit ids.
- - - - -
f8cfb1a5 by HƩcate Kleidukos at 2026-10-04T19:36:39+02:00
[CLC 341] Strict variants of mutable types
This commit is the implementation of CLC Proposal 341
https://github.com/haskell/core-libraries-committee/issues/341
- - - - -
575c4bc6 by Rodrigo Mesquita at 2026-10-05T12:32:02-04:00
ttg: HsModuleName in the AST, ModuleName in GHC
This commit makes the AST fully independent from GHC by parsing a
"module name" as an `HsModuleName (= HText)` rather than constructing an
`ModuleName (= FastString)` straight away.
In the GHC side, everything remains as a `ModuleName`. We turn AST
`HsModuleName`s into fast strings with the cheap `mkFastStringShortText`
when we process the AST for manipulation within the compiler.
There are no performance regressions introduced by this approach.
This is the final piece of #21592
Alternative plans were discussed in
gitlab.haskell.org/ghc/ghc/-/merge_requests/16546#note_694647,
but the Simon suggested one won in simplicity and performance when
compared against my attempt at implementing my original plan of having
a family `ModuleNameP`.
- - - - -
b3b89d32 by mangoiv at 2026-10-05T22:03:32-04:00
hadrian: Persist the used flavour name in the build root (#20650)
This executes the idea proposed in #20650, teaching Hadrian to persist
the flavour used to build a build root. This both makes use of multiple
build roots more ergonomic (as the user no longer needs to repeat
themselves) and avoids a tiresome foot-gun (forgetting to specify a
flavour, often wholly invalidating a build root).
Closes #20650.
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
- - - - -
f977837b by mangoiv at 2026-10-05T22:04:21-04:00
configure: fix sed script and subst tooldir script
Fixes #27672
Adds sanity checking for SUBST_TOOLDIR
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
f1cb08be by Hannes Siebenhandl at 2026-10-05T22:05:03-04:00
Prepend in-memory unit database for backpack
The packageDbFlags are stored in reverse order. Thus, prepending will
ensure that the in-memory unit database is the last item on the unit
database stack.
Further, the in-memory unit database needs to be able to shadow units
from earlier unit databases in the unit database stack.
Moreover, a `-clear-package-db` would remove the in-memory database if
it weren't the last item on the stack.
Closes #27835
- - - - -
8d49ed42 by Kazu Yamamoto at 2026-10-06T19:37:25-04:00
Do not leave standard file descriptors free at startup (#24450)
A process may be started with stdout closed -- `prog >&-` from a shell does
exactly that. Nothing then reserves descriptor 1, and open(), pipe() and
socket() hand out the lowest free descriptor, so the next descriptor the
runtime creates for itself takes it: the ticker's pipe, or a capability's IO
manager control pipe.
'GHC.Internal.IO.StdHandles.stdout' is a CAF, built the first time the program
writes to stdout, which is long after that has happened. It builds a 'Handle'
over descriptor 1, which now belongs to the runtime, and nothing reports an
error because the descriptor is perfectly good. The program then writes its
output into the runtime's own plumbing.
What that looks like from the outside is a hang. The descriptor the Handle has
taken over is the read end of a pipe, so poll() for POLLOUT on it never says
yes and epoll_ctl() accepts a registration for it; the thread waiting to write
blocks for ever. Closing the Handle at exit closes the runtime's descriptor,
which is worse: the ticker then fails on every tick.
'hs_init_ghc' now opens /dev/null onto whichever of descriptors 0, 1 and 2 are
closed, before the runtime creates any descriptor of its own. Each is opened
for the access that descriptor would normally have, read-only for 0 and
write-only for 1 and 2, so that writing to 'stdin' or reading from 'stdout'
still fails rather than quietly succeeding against /dev/null. See
Note [Standard file descriptors must be open].
Moving only the descriptors the runtime opens would not do: the first file the
program itself opened would land on the free number instead. The fix has to
leave no free number. A program run this way therefore finds stdout connected
to /dev/null rather than failing with EBADF on the first write, which is what
such a program would get from most other language runtimes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
65bcf9e9 by Simon Jakobi at 2026-10-06T19:38:09-04:00
changelog: Repair the sentence describing #27477
The description read "programs using could crash", the object of
"using" having been lost. The synopsis already says which programs are
affected, so drop the dangling word.
Assisted-by: Claude Fable 5.1
- - - - -
15ece296 by mangoiv at 2026-10-08T15:14:56-04:00
ci: move hadrian/ghci into the lint category so it can be picked up by more runners
Fixes #27817
- - - - -
c0823135 by mangoiv at 2026-10-08T15:14:56-04:00
ci: make lint-adjacent jobs into platform independent
- move lint jobs into lint-anyarch tag
- unify lint jobs under the same platform independent container
- - - - -
f76464cf by Zubin Duggal at 2026-10-08T15:15:39-04:00
DmdAnal: Make AbsDmd neutral in maxDmd
fixes #27845
- - - - -
ffa56ae4 by sheaf at 2026-10-09T17:15:59+02:00
Preserve sign of zero when parsing -0.0#
This commit leverages the recently added GHC.Types.Literal.Floating
module in order to preserve the sign of negative zero from
source-written floating-point literals.
Fixes #27545
- - - - -
d538cac9 by Facundo DomĆnguez at 2026-10-09T20:26:38-04:00
Propagate annotations to simple interfaces
This allows annotations to be visible to plugins when run by
haddock. The LiquidHaskell plugin needs the annotations, in particular.
Fixes #26761
- - - - -
32c4f4ab by meooow25 at 2026-10-09T20:27:28-04:00
Bump containers submodule to 0.8.1
And fix affected tests.
* T4086a: containers depends on template-haskell-lift now instead of
template-haskell.
* T22611: Updated to be less dependent on containers internals.
- - - - -
c786065e by sheaf at 2026-10-09T20:28:20-04:00
Use an explicit pattern match in toIfaceIdDetails
The old wildcard pattern let this code bit rot: it did not properly account
for recently added 'IdDetails' such as 'RepPolyId', which resulted in
spurious 'pprTrace' messages that could even pollute HLS sessions.
Fixes #23785
- - - - -
e7cacf59 by sheaf at 2026-10-09T20:29:09-04:00
Take into account ifKind in freeNamesIfDecl
Commit 3c2f4bb4 added the 'ifKind' field to various constructors
of 'IfaceDecl', which preserves the original kind (before type synonym
expansion) for better error messages.
However, that commit forgot to update 'freeNamesIfDecl' correspondingly.
This could result in a "urk! lookup local fingerpring" crash when e.g.
a type's kind uses a type synonym defined later, as we failed to add a
dependency on the type synonym during dependency analysis.
Fixes #27916
- - - - -
41e80f41 by Simon Peyton Jones at 2026-10-11T14:38:51-04:00
Simplify the error-suppression mechanism in GHC.Tc.Errors
In `GHC.Tc.Errors.reportWanteds` we suppress some errors in favour of
others. But the mechanism had grown crufty, and #27331 exposed a bug.
This MR makes it simpler and more uniform, by doing everything via
the `ei_suppress` field of the ErrorItem.
Claude then found another closely-related bug (see the review linked
on !16564). That bug is immortalised in new test T18851d.
I'm still not happy with `ignoreConstraint` but we can worry about
that another day; I have not touched it.
Main changes
* Instead of /predicting/ when an error will be reported, we set
`cec_error_reported` when an error is /actually/ reported. (I renamed
it from `cec_suppress` to reflect this change.)
Now errors are suppressed only when a preceding error has actually been
reported. Simpler and more robust.
See `Note [cec_error_reported: suppressing less-serious errors]`
The big changes are in `reportWanteds` which looks very different.
* New `Note [ei_suppress: suppressing confusing errors]` describes the
(quite separate) `ei_suppress` mechanism for suppressing confusing
errors, mainly arising from non-empty rewriter sets
* In `tryTypeClassDefaulting`, instead of switching off type-class defaulting
if there is an insoluble /anywhere/, we just switch it off locally when
we find an insoluble sub-tree. See Note [When to do type-class defaulting]
and (W5) in Note [ApproximateWC]
* Greatly simplify `insolubleWantedCt`.
* I made type-class-defaulting be a bit more eager, only switched off when
a peer or ancestor (but not child) constraint is insoluble. See
Note [When to do type-class defaulting].
Small refactorings
* Rename `askNoErrs` to `askErrsFound` and flip its polarity
* The code for "check if ei_suppress is true of all items" code is
moved to `mkErrorItems` rather than in the large `reportWanteds`.
* Code for `has_gadt_match` moves to `mkGivenErrorReporter`, rather than
polluting the large `reportWanteds`.
* Many tests with `-fdefer-type-errors` get more warnings, especially
about ambiguous (Num a) constraints. This is by-design: see
Note [Always warn with -fdefer-type-errors]. Previously GHC was not
honouring this Note but now it is, hence the extra errors.
- - - - -
f217fc31 by Cheng Shao at 2026-10-11T14:39:33-04:00
compiler: ensure cross ghc --info output target unit ids
Previously, for cross ghcs, the base/ghc/ghc-internal unit ids in
--info output do not match the target unit ids reported by ghc-pkg,
breaking cross ghc release builds with hash-unit-ids when being used
with cabal 3.18. This patch fixes it by making --info output target
unit ids. Fixes #27919.
Co-authored-by: Codex <codex(a)openai.com>
- - - - -
d07a5176 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Remove the Eq and Ord instances for ForAllTyFlag
In Note [Comparing visibility] in GHC.Core.TyCo.Compare we read that
"we always compare ForAllTyFlags with `eqForAllVis` or `cmpForAllVis`"
But alas there was an Eq and Ord instance for ForAllTyFlag, which made it
impossible to check this claim. So I made these changes:
* Move the definition of ForAllTyFlag and its related functions from
L.H.S.Specificity (where it did not belong, since L.H.S didn't use it)
into GHC.Types.Var.
* Remove the Eq and Ord instances for ForAllTyFlag
* Deal with the fallout, by using `eqForAllVis` or related functions.
* In interface files we use IfaceType as a key for a de-deduplication map
See Note [Deduplication during iface binary serialisation]
in GHC.Iface.Binary. For this we need /exact/ comparison, so we use a
newtype wrapper for IfaceForAllTyFlag, and give use `cmpForAllTyFlagExactly`
to implement its Ord instance. Tiresome but easy.
* Rename `toIfaceForAllBndrs` to `toIfaceForAllTyBndrs`
- - - - -
ea5c054d by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor type and coercion substitution
This MR refactors type and coercion substitution so that they use
TyCoMapper, rather than hand-rolled code. Fundamentally it's a simple
idea, but I had to do quite a bit of refactoring to make it fly.
I got Claude to help me this this refactoring, but I paid careful
attention to every line of code.
Main changes:
* New module GHC.Core.TyCo.Make which defines TyCoMapper, and a bunch of other
simple "smart constructors" for types and coercions. See
GHC.Core.TyCo.Rep Note [The Type-related module hierarchy], esp (TRM1)
* The new TyCoMapper has new fields `tcm_tcapp_ty` and `tcm_tcapp_co` to handle
type-constructor applications. These replace `tcm_tycon`.
* Rewrite GHC.Core.TyCo.Subst to use TyCoMapper
* Rewrite GHC.Core.Type.expandTypeSynonyms to use TyCoMapper.
* Implement `seqType` and `seqCo` with TyCoFolder. To to this I had to add
a `tcf_lit` field to TyCoFolder.
* A new module GHC.Utils.StrictIdentity to define a strict identity monad,
which itself is used for
substTyCoMapper :: TyCoMapper Subst StrictIdentity
* I removed an apparently-unused instance for Binary Levity
Refactoring `seq` functions
* In GHC.Core.Seq, redefine `seqOneShot`, `seqRuleInfo`, and friends to return
`SeqResult`, a new type defined in GHC.Types.Baseic, rather than `()`. We
can define a Monoid instance for `SeqResult` that does the right thing.
* This has knock-on effects across the compiler.
- - - - -
34165e23 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor TyCoMapper to take a single monad; add StrictReaderT
TyCoMapper used to be parameterised over both an environment and a
monad, with fields like
tcm_tyvar :: env -> TyVar -> m Type
Now it is parameterised over just the monad:
tcm_tyvar :: TyVar -> m Type
If the mapping needs an environment, `m` is a reader monad over that
environment. Many uses (e.g. zonkTcTypeMapper, swizzleMapper) need no
environment at all, and used to pass a dummy (). The binder field
becomes
tcm_tycobinder :: forall r. TyCoVar -> ForAllTyFlag
-> (TyCoVar -> m r) -> m r
and runs the continuation in the extended environment. mapTyCoX is gone;
only mapTyCo remains.
To make this efficient, the reader monad must use the one-shot trick and
be strict in the environment. So:
* New module GHC.Utils.Monad.StrictReader defines
newtype StrictReaderT r m a
with hand-written instances. The builder of the pattern synonym
`StrictReaderT` is a smart constructor that adds both `oneShot` and a
bang on the environment, so every StrictReaderT computation is strict
in the environment. See Note [Instances for StrictReaderT].
* ZonkT becomes type ZonkT = StrictReaderT ZonkEnv
ZonkM becomes type ZonkM = StrictReaderT ZonkGblEnv IO
replacing their own hand-written instances.
* Substitution uses
type SubstM = StrictReaderT Subst StrictIdentity
substTyCoMapper :: TyCoMapper SubstM
and similarly expandTypeSynonymMapper.
* zonk_tycomapper :: TyCoMapper (ZonkT TcM) is now much simpler.
* swizzleMapper uses StrictIdentity rather than Identity.
* Module renaming, so that the strict monads are all peers in GHC.Utils.Monad:
GHC.Utils.StrictIdentity ==> GHC.Utils.Monad.StrictIdentity
GHC.Utils.Monad.State.Strict ==> GHC.Utils.Monad.StrictState
alongside the new GHC.Utils.Monad.StrictReader.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
c0299e15 by Simon Jakobi at 2026-10-13T18:11:23-04:00
testsuite: Line-buffer the driver's stdout
Python block-buffers stdout when it is a pipe. This is the case for
example in CI. As a result there is often no indication of progress at
all until the run ends.
To fix this, we configure it explicitly to use line buffering instead.
stderr is reconfigured too, for consistency: Python line-buffers it by
default since 3.9.
The type-ignores are for mypy, which types these handles as TextIO ā an
interface without reconfigure.
Fixes #12934.
Assisted-by: Claude Fable 5
- - - - -
9b5beaa2 by Florian Ragwitz at 2026-10-13T18:12:05-04:00
hpc: Improve coverage semantics for instance methods and instances
Users care about which of their explicitly written methods are or aren't
covered, not whether all of the inherited methods are covered as well. Those
should be covered where they are implemented.
We therefore skip generating top-level boxes for inherited methods which will
appear as uncovered with no clear indication as to why, and no way to fix other
than exercising code the user has not written.
Previously, top-level boxes for those inherited methods would use the instance
head as their source span. Now that those boxes are gone, we can use that
source span for another purpose:
We introduce a new top-level box for each class instance with its instance head
as the source span, and use that to indicate whether or not an instance has
been covered at all.
We do this by making any method of the instance, inherited/generated or
otherwise, tick the box for the instance head. Excluded from this are
methodless classes, which could never be covered using the current mechanism.
This could be improved upon further.
These changes apply to ticking for program coverage only, and don't affect
source notes. Additionally, we update the scope of record selector ticking to
be limited to program coverage as well, as the oversight to also extend it to
source notes has previously caused bugs and because record selector ticking is
coverage-specific.
Fixes #17155, #15932.
- - - - -
836ec50a by Simon Peyton Jones at 2026-10-13T18:12:54-04:00
Refactor fundeps again
This MR fixes #27828; there was a bad scoping error in `trim_qtvs`.
The main changes are
* Refactor `trim_qtvs` completely to eliminate the bug.
* Remove a redundant `apartnessCheck` from `mkTopOpenFamEqFDs`.
* Lots of improvements to the Notes in FunDeps.hs
I also did a couple of pure refactors:
* I realised that we were carefully caching `cab_incomps` in each
`CoAxBranch`, to make it more efficient to reduce a type family application,
but we were not doing the same thing when computing relevance for functional
dependencies; see Note [Relevance] in GHC.Tc.Solver.FunDeps. So I added
`cab_overlaps`, which is now used in `noEarlierMatch`.
* Use a proper data types, `AmIUnifying` and `OuterKindsFlag`, for two
previously-Boolean arguments to `tc_unify_tys`. This is a pure refactor.
- - - - -
889ef371 by Simon Peyton Jones at 2026-10-13T18:13:36-04:00
Refactor and simplify solver's unification code
Ticket #27844 showed that GHC's constraint solver could miss an
occurs check, and thereby build an infinite type.
This patch significantly simplifes the code in
GHC.Tc.Solver.Equality.canEqCanLHSFinish_try_unification
GHC.Tc.Solver.Equality.canEqCanLHSFinish_no_unification
It is now significantly simpler, and requires much less subtle
reasoning to understand.
Main changes
* If `canEqCanLHSFinish_try_unification` fails to unify, it now /always/ calls
`canEqCanLHSFinish_no_unification` rather than trying to finish the job itself.
* `GHC.Tc.Solver.Monad.checkTypeEq` is moved from Monad into Equality, and renamed
to `GHC.Tc.Solver.Equality.checkTypeEqNoUnification`.
* `canEqCanLHSFinish_no_unification` calls `checkTypeEqNoUnification` to test
the invariants for an inert equality. Before this MR there was a special case for
`do_not_prevent_rewriting`, but that has gone; instead it's just a consequence of
the flags passed to `checkTyEqRhs`, documented in the `PuOK` case of
`canEqCanLHSFinish_no_unification`.
* There is only one bit of "swap back" code, in `finish_no_unify` in
`canEqCanLHSFinish_try_unification. Previously this code was duplicated.
* `kickOutAfterFillingCoercionHole` should account for equalities with a
TyFamLHS. See (KOC5) in Note [Kick out after filling a coercion hole]
* No need to gather coercion holes in the `PuOK` case of `canEqCanLHSFinish_no_unification`.
See documentation with that code.
- - - - -
f9193e53 by Simon Peyton Jones at 2026-10-13T18:13:37-04:00
One line fix to fallout from
...#27731, !16564, simplifying Tc.Errors machinery
There was an over-eager assert!
- - - - -
cdd56b7a by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Fix several sphinx errors and warnings from rendering the release notes
The extension references which are removed here are for extension which were
already previously undocumented, so just removing them seems fine for now.
- - - - -
4f00da25 by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Link to QualifiedStrings documentation
- - - - -
97adaf89 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Line up simpleUnifyCheck and check_ty_eq_rhs
Even after #26543 was allegedly fixed, the original repo case in the
Description continued to fail. The reason was that the QuickLook
unifier, `qlUnify`, used `simpleUnifyCheck` for checking unification
invariants; and `simpleUnifyCheck` conservatively rejected any RHS
with a coercion hole in it. The upshot was that QuickLook was not
as clever as it should be, wrongly failing to do an impredicative
instantiation.
Interestingly `check_ty_eq_rhs`, which does the same job during
constraint solving, was more liberal: it just looked at the free vars
of the coercion, and allowed coercion holes.
This MR lines them up, adding some careful notes. See
Note [simpleUnifyCheck]
Note [Occurs check and coercions]
Note [Unification preconditions] esp (COERCIONS)
Things are better than before, but I am still uncomfortable about the
possibilty that a hole might be filled with a coercion that mentions
the LHS type variable; for now I have left this discomfort documented
in Note [Occurs check and coercions].
Main changes
* `qlUnify` now only unifies /instantiation variables/ not regular unification
variables. This makes QuickLook more predictable. See (UQL6) in
Note [QuickLook unification].
* `qlUnify` no longer needs to call `simpleUnifyCheck`, so we can get rid of
`UC_QuickLook` and its code in `simpleUnifyCheck`.
* I found I could get rid of `mkOccFolders` in favour of `anyFreeVarsOfType`.
Hooray.
* Improve documentation of CycleBreakerTv, and rename it to GivenCycleBreakerTv
because they are only uesd for Givens!
* I accepted a 9% worsening in compile time allocation on T5030
because the newly-consistent story triggered #27934.
Other changes
* I refactored `atvFolder` so that it pairs the "interesting-var" function
with the in-scope set, to avoid building a closure with a free variable.
Now we get nice tight loops for `anyFreeVarsOfType` and friends.
See Note [Any-free-var folder].
Metric Increase:
T5030
- - - - -
5f7b3047 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Fix order-dependence in QuickLook
Ticket #27917 pointed out that QuickLook was order-dependent
-- very bad!
The solution is in `qlUnify`: spot when we are unifying a type with a
definite monotype, and then monomorphise any free instantiation
variables of that type.
See (UQL8) and (UQL9) in Note [QuickLook unification].
- - - - -
c391c70c by Simon Peyton Jones at 2026-10-14T00:07:28+01:00
Add some comments about RuntimeUnk
This commit just adds comments explaining why we don't need to worry about
RuntimeUnkTv in the constraint solver.
It also tightens up docmentation of earlier (overlapping) commits in
this MR.
- - - - -
7df3ba2f by Andrea Vezzosi at 2026-10-14T06:15:48-04:00
add runGhcWithSignalHandlers and remove handling from runGhc[T]
it only ever makes sense to call `withSignalHandlers` from `main`, otherwise
signals can be too easily swallowed without notification to the rest of your
process.
This commit takes withSignalHandlers out of `runGhc/runGhcT` and provides
`runGhcWithSignalHandlers` for the old behaviour.
- - - - -
3a72b8a2 by Hannes Siebenhandl at 2026-10-14T13:48:32-04:00
Fix #27836, normalise unit database path in ExternalUnitDatabases
Add a regression test, proofing that all variations:
- local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf/
are parsed only once.
- - - - -
8ddbc6f9 by Florian Ragwitz at 2026-10-14T13:49:28-04:00
Remove obsolete HPC types
Fixes #27946.
- - - - -
f34c79ee by Alan Zimmerman at 2026-10-15T04:54:47-04:00
EPA: Start using vocurly as basis for AnnListLayout
For the existing cases that populate AnnList.
This uses AnnListBraces when braces are explicitly supplied, and
AnnListLayout when vocurly is used
The change also shows up AnnList usages that can never capture layout,
these are cleared up later.
- - - - -
033ba59c by sheaf at 2026-10-15T04:55:44-04:00
Make exprFreeVars deep
exprFreeVars used to be a shallow free-variable finder (it didn't look
into kinds), but most callers wanted it to be deep. In particular,
'exprFreeVars' is often used to seed an 'InScopeSet', and that must
contain the /deep/ free variables.
This commit makes it deep, which allows us to get rid of calls to
'closeOverKinds' or other workarounds for shallowness in:
- 'GHC.Core.Opt.Simplify.Utils.abstractFloats'
- 'GHC.HsToCore.Binds.dsSpec_help'
- 'GHC.Core.Opt.Arity.etaBodyForJoinPoint'
- 'GHC.Core.FVs.freeVars'
- 'GHC.Core.Lint.lintCoreRule'
We also remove 'deepExprsFreeVarsDSet' and 'closeOverKindsDSet'.
Other places needed a little bit more care, in particular to properly
handle coercion variables free in kinds:
- 'GHC.Core.Opt.Specialise.specHeader' quantifies over the binder of
an unspecialised argument directly, instead of computing the free Ids
of the argument.
- 'GHC.HsToCore.dsWarnRuleShadowing' filters out 'CoVar's.
- 'GHC.Core.Opt.SpecConstr.callToPat' had some ad-hoc logic to compute
argument pattern types and a workaround with 'expandTypeSynonyms'.
That logic is removed in favour of a new 'argsToPats' function which
directly computes the argument pattern types by instantiating the
type of the head of the call pattern.
Fixes #27936
- - - - -
f93d523c by Luite Stegeman at 2026-10-15T04:56:34-04:00
testsuite: Use mkWeakMVar in memo001/memo002
mkWeakPtr in the memo001/memo001 tests created weak pointers
with the MVar box as the key, which is fragile in the presence
of optimization. The fix is using mkWeakMVar, keying on the
primitive MVar# instead.
Fixes #27924 and #27396
- - - - -
8c947573 by Simon Peyton Jones at 2026-10-16T13:11:53+01:00
Improve exprOkForSpeculation
Fixes #27910, which exposed an infelicity in exprOkForSpeculation
The new story is carefully described in new Note [exprOkForSpeculation],
esp (a-c) and (EOKS1).
- - - - -
7dedcf13 by Alan Zimmerman at 2026-10-16T19:03:17-04:00
EPA: Add TTG fields to FamilyInfo
This commit is a simple add, with unused extension fields.
It lays the groundwork for using them for exact print annotations
- - - - -
26b9a8a0 by Arkissa at 2026-10-17T16:04:10+00:00
ghci: Prefer exact source spans in :type-at
Prefer expression types for identical source spans.
Fixes #27412.
- - - - -
70dc4e61 by sheaf at 2026-10-18T18:15:15-04:00
Carefully implement coercion zapping
This commit implements coercion zapping in the rewriter, controlled by
the -fzap-coercions flag (on by default). This significantly reduces
the size of coercions produced when rewriting type family applications,
resulting in much faster compilation. See Note [Coercion zapping]
in GHC.Tc.Solver.Rewrite for an explanation and further details.
The rewriter now keeps track of the `CoVar`s and `CoercionHole`s it uses
when rewriting, which allows computing the dependencies of a zapped
coercion without traversing the coercion the rewriter produced, as
explained in Note [Computing coercion dependencies] in GHC.Tc.Solver.Rewrite.
Accompanying changes:
- Rework how dependencies of 'UnivCo's are tracked, purely for
performance reasons.
We now use the 'UnivCoDeps' datatype instead of '[Coercion]', and
we now insist that 'uco_deps' also contains the CoVars that appear
in the LHS and RHS types of the UnivCo (as a caching mechanism).
- Several performance improvements to the rewriter (e.g. increased
strictness).
- Improvements to the family application cache, including:
- Better documentation.
- Only cache a whole chain of reduction steps.
- Don't put coercion holes in the cache, fixing #27518.
- Allow Core Lint to be called from within the typechecker (and from
within the coercion optimiser).
- Move out "annotation linting" from Core Lint into the general Core
pipeline, to avoid the dependency GHC.Core.Coercion.Opt->GHC.Core.Lint
causing a regression in CountDepsParser due to transitive
dependencies of GHC.Core.Opt.Monad and GHC.Unit.Module.ModGuts.
Fixes #8095 #27336 #27518
Summary of performance numbers
Compile-time byte allocated in GHC's testsuite (0 regressions)
CoOpt_Singletons(normal) ghc/alloc 634,040,332 595,448,728 -6.1% GOOD
FamAppCachePerf(normal) ghc/alloc 495,629,812 191,612,920 -61.3% GOOD
LargeRecord(normal) ghc/alloc 1,226,806,434 966,260,976 -21.2% GOOD
SimplCastPerf(normal) ghc/alloc 160,505,678 148,112,688 -7.7% GOOD
T12227(normal) ghc/alloc 244,668,982 233,037,216 -4.8% GOOD
T12545(normal) ghc/alloc 697,804,842 424,705,152 -39.1% GOOD
T13386(normal) ghc/alloc 422,871,076 35,213,656 -91.7% GOOD
T15703(normal) ghc/alloc 288,402,364 273,692,560 -5.1% GOOD
T26426(normal) ghc/alloc 86,002,052 78,152,104 -9.1% GOOD
T27336(normal) ghc/alloc 498,932,268 35,886,016 -92.8% GOOD
T5030(normal) ghc/alloc 117,057,706 88,785,648 -24.2% GOOD
T5321Fun(normal) ghc/alloc 252,552,628 243,820,176 -3.5% GOOD
T8095(normal) ghc/alloc 768,198,564 127,779,520 -83.4% GOOD
T9872a(normal) ghc/alloc 1,655,675,020 1,406,017,008 -15.1% GOOD
T9872b(normal) ghc/alloc 1,864,180,628 1,644,706,696 -11.8% GOOD
T9872b_defer(normal) ghc/alloc 2,834,585,468 1,657,729,760 -41.5% GOOD
T9872c(normal) ghc/alloc 1,572,573,116 1,354,055,424 -13.9% GOOD
T9872d(normal) ghc/alloc 351,516,004 331,071,424 -5.8% GOOD
TcPlugin_RewritePerf(normal) ghc/alloc 2,063,065,680 1,847,464,272 -10.5% GOOD
Chesskell (github.com/Proxymoron461/chesskell/issues)
Typechecking that the first N plies of kholmovVsBronsteinShort
are a valid chess game:
Plies | GHC 9.14 time/alloc | This commit time/alloc |
-----:|---------------------|------------------------|
2 | 41s/20GB | 0.2s/19MB |
4 | 95s/49GB | 0.3s/25MB |
6 | timed out | 0.6s/522MB |
8 | timed out | 7s/673MB |
10 | timed out | timed out |
Compilation of singletons-base: compile time -28%, allocations -25%
-------------------------
Metric Decrease:
CoOpt_Singletons
FamAppCachePerf
LargeRecord
SimplCastPerf
T12227
T12545
T13386
T15703
T24984
T26426
T27336
T5030
T5321Fun
T8095
T9872a
T9872b
T9872b_defer
T9872c
T9872d
TcPlugin_RewritePerf
-------------------------
Co-Authored-By: Sylvain Henry <sylvain(a)haskus.fr>
- - - - -
3d326d7d by Sylvain Henry at 2026-10-18T18:16:09-04:00
JS: fix stack corruption in h$ap_gen_fast's pushAllRegs (#27624)
The loop added in 9e46990976 ("JS: support more than 128 registers
(#26558)") pushed register N to stack[sp - N - 2] while the switch it
falls through into, and every reader of the h$ap_gen frame, uses
stack[sp - (N - 2)]. Registers >= R32 were therefore written 4 slots
too low: the slots the readers consult were left stale and the frame
below was silently corrupted.
Fix the loop to use the same slot formula as the switch, and add a
regression test: an unknown call to a thunk with 35 argument register
slots, which goes through the generic apply.
Co-Authored-By: Claude Fable 5 <noreply(a)anthropic.com>
- - - - -
6bbca569 by Andreas Klebinger at 2026-10-21T10:01:10+00:00
Fix a few tag inference bugs.
* Treat bottoming functions and nullary join points as functions.
* When generating bytecode don't rely on imported tag sigs.
Fixes #27831, #27841 and #27842.
- - - - -
71808e29 by Sylvain Henry at 2026-10-22T04:50:24-04:00
Add GHC.Internal.Unboxed.Do: do-notation for unboxed values (#27944)
QualifiedDo operators can be representation-polymorphic: a do-block is
expanded into ordinary applications before typechecking, and the only
check on a bound variable is the deferred fixed-runtime-rep check. A
representation-polymorphic (>>=) cannot be defined directly, though,
because its body would bind a variable of unknown representation.
The new module provides such operators for State#-passing code as
methods of a class indexed by RuntimeRep, with one instance per
representation. With optimisation the dictionaries disappear and a
block compiles to the usual nested case expressions:
Ubx.do { x <- readWordArray# mba 0# -- x :: Word#
; writeWordArray# mba 1# x -- unit actions are statements
; Ubx.pure x }
Also add users guide documentation and tests.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
33247780 by Sylvain Henry at 2026-10-22T04:50:24-04:00
Bignum: use Ubx.do for State#-passing code (#27944)
Rewrite the State#-passing code of the GHC.Internal.Bignum modules
(Primitives, WordArray, BigNat, Natural, Integer, Backend.Native,
Backend.GMP) with the qualified do-notation of GHC.Internal.Unboxed.Do.
Nested case chains such as
case newWordArray# sz s of { (# s, mwa #) ->
case act mwa s of { s ->
unsafeFreezeByteArray# mwa s }}
become
Ubx.do
mwa <- newWordArray# sz
act mwa
unsafeFreezeByteArray# mwa
The optimised Core is unchanged (compared per top-level binding).
BigNat now enables MonoLocalBinds: local loops written with Ubx.do
must stay monomorphic in the state type, otherwise GHC does not turn
them into join points.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
593f5f5b by Sylvain Henry at 2026-10-22T04:51:16-04:00
JS: remove archive padding after wasm objects (#25665)
On Darwin hosts, emar (llvm-ar) writes archives in the Darwin format when
the first member is not a known object file, which is the case for the
archives of the JS backend. This format pads each member to 8 bytes with
'\n' and includes the padding in the member size. Wasm objects do not
accept trailing bytes: wasm-ld failed with "section too large".
The JS linker now removes this padding when it extracts a wasm object from
an archive. In addition, Hadrian passes --format=gnu to emar for the JS
target. See Note [Wasm objects in Darwin archives].
Also document the format of Cc (wasm) objects in Note [Cc object format].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
13dff5d0 by L0neGamer at 2026-10-22T21:37:31-04:00
add options for resizing bytearrays (#27244)
add five mutable bytearray resizing operations
for various kinds of pinnedness and aligning.
- prefer unpinned when allocating new array (``resizeMutableByteArrayPreferUnpinned#``; the ``resizeMutableByteArray#`` default)
- prefer pinned when allocating new array (``resizeMutableByteArrayPreferPinned#``)
- prefer aligned and pinned when allocating new array (``resizeMutableByteArrayPreferAlignedPinned#``)
- prefer same as input bytearray when allocating new array (``resizeMutableByteArrayKeepPinnedness#``)
- ensure the output array is aligned and pinned after operation (``resizeMutableByteArrayMakeAlignedPinned#``)
- - - - -
0c17201c by Sylvain Henry at 2026-10-22T21:38:23-04:00
JS: implement performMinorGC and performBlockingMajorGC (#28012)
GHC.Internal.System.Mem imports three C entry points: performMajorGC,
performGC (for performMinorGC) and performBlockingMajorGC. The JS RTS
only defined h$performMajorGC, so calling performMinorGC or
performBlockingMajorGC threw "ReferenceError: h$performGC is not
defined" at runtime.
The JS RTS has a single non-generational collector, so both missing
entry points are now aliases of h$performMajorGC.
Add a test that calls every GC entry point of System.Mem.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
7a631ff2 by L0neGamer at 2026-10-23T09:11:39-04:00
Mon(a|oi)d of No (Return|Mappend) progress (!15795)
Make non-canonical definitions of return and mappend
non-suppressible errors, and make canonical definitions
of those methods warnings.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/328
- - - - -
14656fd4 by Simon Jakobi at 2026-10-23T09:12:27-04:00
Cmm: keep the CBE substitution idempotent
When blocks are merged over multiple rounds during common block
elimination, a block that won a merge in an earlier round can still
lose a merge in a later round. The substitution map (Subst) used to
record this as a chain: the earlier loser mapped to a block that was
itself eliminated. In PLT terminology, the substitution became
*non-idempotent*. Applying such a substitution with a single lookup
left edges to unreachable blocks in the Cmm graph, eventually leading
to a setInfoTableStackMap panic (#27368).
With this patch, each round's fresh substitutions are applied to the old
ones as they are added (extendSubst), so every eliminated block maps
directly to its final replacement and the substitution stays idempotent.
Fixes #27368.
Assisted-by: Claude Fable 5.1
- - - - -
92848e61 by Evgeny Malyshev at 2026-10-23T20:26:04-04:00
hadrian: Include transitive dependencies in Haddock builds
Haddock needs indirect dependency interfaces to resolve references to
definitions outside a package's direct dependencies. Expose Cabal's
configured dependency closure through ContextData and use it alongside
the direct list, preserving direct-interface precedence.
Bump Shake's cache version for the serialized oracle change. Add a
Hadrian selftest requiring template-haskell's indirect ghc-prim interface.
Fixes #25850.
Fixes #27786.
Assisted-By: OpenAI Codex
Metric Increase:
haddock.Cabal
- - - - -
5e8ae81b by Zubin Duggal at 2026-10-23T20:26:47-04:00
WinIO: Don't confuse Win32 errors and NTSTATUS codes
WinIO misinterpreted NTSTATUS codes as Win32 errors, and had some ad hoc logic to deal with this.
However, this logic was incomplete and resulted in the mishandling of results of certain I/O operations
(see testcase).
Now the `ErrCode` argument in `CompletionCallback` is always the Win32 error code,
and we convert the NTSTATUS using RtlNtStatusToDosError.
Also when an overlapped/async operation such as ReadFile fails immediately,
with a Win32 error such as ERROR_BROKEN_PIPE, we don't get a further completion
notification, so we never recorded the failure. This worked by coincidence
earlier, because `STATUS_PENDING` happened to have the same numerical code as
`ERROR_NO_MORE_ITEMS`, but it doesn't now that we translate `STATUS_PENDING`
into the correct Win32 error code (`ERROR_IO_PENDING`). Fix this by using
the Win32 error value we obtained when an operation returns `STATUS_PENDING`.
Fixes #27971
- - - - -
c42ed66a by Martijn Bastiaan at 2026-10-24T16:00:42+02:00
Add single-threaded test for #27526 + #27123
Issue #27526 is a duplicate of #27123, which has already been fixed in
HEAD. The proposed patch in the former carries a "nicer" regression test
in that it doesn't rely on multi-threading to trigger.
Closes #27526
- - - - -
7f73f515 by Simon Peyton Jones at 2026-10-24T17:29:19-04:00
Refactor QuickLook a bit
This MR simply refactors QuickLook a bit. In particular, it
simplifies `tcApp`, and moves shared code into `finishApp`.
It also adds `Note [QuickLook: arguments before result]`
responding to #26599.
There should be no user-visible changes, except perhaps in error messages,
which improve marginally.
For some reason T24984 compiles 8% faster. I'll take the win!
Metric Decrease:
T24984
- - - - -
a4a3a964 by Alan Zimmerman at 2026-10-24T17:30:03-04:00
EPA: Use AnnList for XClosedTypeFamily
We now have TTG annotations for FamilyInfo.
Make use of it to store the AnnList annotations for a closed type
family.
- - - - -
953e4c7f by sheaf at 2026-10-26T18:19:10-04:00
Rework LogQueue to be a proper queue
Now 'LogQueue' uses a 'TQueue' with a separate 'TVar' to indicate
whether the log queue is finished logging, instead of the previous weird
data representation using a reverse-order '[Maybe Msg]' with 'Nothing'
denoting the end of the queue.
- - - - -
ec29c5fa by Rodrigo Mesquita at 2026-10-26T18:19:10-04:00
Refactor GHC.Driver.MakeAction
Pull out of 'runParPipelines' the logic for creating a 'MakeEnv' ready
to be used by multiple threads, as that will be useful for downsweep as
well (which doesn't fit the 'runPipelines' flow), rather than being just
for upsweep.
The code is moved and re-structured to match the export list, simplify
the sequentiality checks previously both in 'runPipelines' and
'runAllPipelines', which were weirdly similar and confusing; into the
two part step where we need these checks: (1) to construct the MakeEnv,
(2) to run the MakeActions in parallel. These two steps are separate and
used to be too mixed up.
Some additional little simplifications or clean ups here and there.
- - - - -
3fb22073 by Rodrigo Mesquita at 2026-10-26T18:19:11-04:00
Refactor GHC.Driver.Downsweep in preparation for parallel downsweep
Pure refactor to improve the code to facilitate implementing parallel
downsweep in the next commit.
This commit puts a MakeEnv into the DownsweepEnv, gives the fields
proper names and uses RecordWildcards to simplify, rather than passing
around all diagnostic wrappers, driver-message-things and using 10s of
positional fields.
No behavior changes here!
- - - - -
52f385a7 by sheaf at 2026-10-26T18:19:11-04:00
Driver: enableCodeGenForTH in load', not downsweep
enableCodeGenForTH modifies the module graph for planning, creating
fresh temporary paths. So it should only be run when we are about to
execute a build plan (e.g. in load'), so that consumers that want to
know facts about the module graph don't go looking for files that don't
exist yet (in particular 'haddock --no-compilation').
- - - - -
82402d14 by sheaf at 2026-10-26T18:19:11-04:00
2-phase Cache/Search Finder monad
This commit restructures the finder abstraction by introducing the
'FinderM' monad, which splits module lookup operations into two phases:
- a cache-only phase, performing no filesystem access,
- from the first cache miss onwards, a search action which may access
the filesystem.
This allows consumers to distinguish between quick cached results versus
more expensive filesystem search operations.
- - - - -
5c302b40 by sheaf at 2026-10-26T18:19:11-04:00
Separate Home/External finder caches
The caches for home modules and modules from external units have
different lifetimes, needing to be invalidated at different points.
This commit moves the cache for modules from external units into the
'UnitState' type, which keeps the cache correct whenever package flags
or package databases change (setSessionDynFlags, :set -package ...,
Backpack's addUnit).
This also makes it easier to clear the cache of home modules, as they
are now stored separately (obviating the 'isUnitEnvInstalledModule'
check we used to perform).
- - - - -
605fbb96 by sheaf at 2026-10-26T18:19:11-04:00
Add known home modules to the finder cache
The finder looks in the file system for the on-disk source that
corresponds to a Haskell module name. There are two kinds of modules
where we need to bypass this search:
- a file passed directly in the command line, which may not be in any
search path and whose module name may differ from the file name;
- Backpack signatures and modules, which do not exist as files at all.
This commit handles these two situations by adding an immutable
'KnownHomeModules' in the finder cache, which is always consulted first
before doing any search.
This removes the ad-hoc imperative logic which relied on mutating the
finder cache at careful points.
'setModuleGraph' now also takes the known home modules, so that the
module graph and the known home modules are always set consistently.
See Note [Known home modules] in GHC.Unit.Finder.Types.
- - - - -
82718f44 by sheaf at 2026-10-26T18:19:11-04:00
Make 'UnresolvedImport' into a suitable cache key
The goal of this commit is to make 'UnresolvedImport' suitable for use
as a cache key. Specifically, during downsweep we want to be able to
cache module resolution queries. We want to do this using some kind of
map, e.g. (roughly speaking):
Map UnresolvedImport ResolvedImport
For this to work, 'UnresolvedImport' must contain **precisely** the
input data to each resolution computation. In other words:
1. If something changes that materially affects resolution, it must
be stored in the cache key.
2. If changing some input does not materially affect the outcome,
then it must not be stored in the cache key.
To satisfy (1), we change 'UnitNode' to also keep track of the home
unit in whose unit state the unit's dependencies were looked up.
For (2), 'ImportResolution' now stores a 'ModuleLookupScope' instead of an
'UnresolvedImportOrigin'. Plugin imports are expressed with a new
'LookupPlugin' scope. The source location of an import, which is
immaterial to the resolution, is stored out of band outside
'UnresolvedImport', in 'ModSummary'.
- - - - -
d4635c7c by sheaf at 2026-10-26T18:19:11-04:00
Add GHC.Data.Dependent
This commit adds a minimal implementation of dependent sums
('Some', 'DSum') and dependent maps ('DMap').
The implementation is not entirely performance optimal, as there are a
few extraneous allocations compared to the full-blown implementation in
the 'dependent-map' package. For our use case (caching downsweep
computations), this does not matter much.
See GHC.Data.Dependent.
- - - - -
6759533e by sheaf at 2026-10-26T18:19:11-04:00
Driver: structured concurrent worker abstraction
This commit introduces a structured concurrency framework in the style
of the 'ki' library: a collection of threads within a scope.
We implement two kinds of concurrent workers on top of this framework:
- Independent workers cannot wait for one another at all. The only
scheduling operation is to wait for quiescence.
- Coordinating workers declare an STM readiness condition (waiting on
other workers to complete) which gates their start.
See Note [Deterministic concurrent workers] in GHC.Driver.Concurrency.
This commit ports upsweep to this new framework, with downsweep being
left as subsequent work.
Further changes along the way:
- Refactoring of how concurrency is acquired to avoid the footgun of
trying to use a no-op 'AbstractSem' as a lock in the serial case.
- The "re-run with -j1" logic for semaphore opening errors no longer
triggers on late semaphore failures (part-way through a lengthy
computation).
- Logger threads are properly cleaned up on exception, with each
concurrent worker's log queue and local TmpFs properly bracketed.
- The 'GhcMessage -> AnyGhcDiagnostic' and 'Maybe Messager'
arguments of 'depanalE', 'depanalPartial' and 'downsweep', which
were all dead in practice, have been dropped.
- Concurrent logging has been completely overhauled. Each worker has
its own log queue. Workers whose logs are printed as we go are
spawned in the order in which their logs must be printed, now using
a TQueue instead of the old complicated LogQueueQueue mechanism.
'logThread' is replaced by 'withLogPrinter', which runs the thread
that prints the log queues within a concurrent worker scope.
These changes allow us to fix issues with the exception handling:
we now always flush remaining log queues before exiting (even when
the action throws an exception), and exceptions that arise while
printing are properly rethrown. This fixes #28009.
- - - - -
38a99006 by sheaf at 2026-10-26T18:19:11-04:00
Rule-based deterministic concurrent downsweep
This commit rewrites downsweep as a single query-answering rule
(see 'DownsweepRule') that can be executed by concurrent worker threads.
The design allows every expensive operation (preprocessing files with CPP,
parsing headers, reading interfaces) to be performed concurrently
according to the -j<N>/-jsem flags.
See Note [Rules-based downsweep] in GHC.Driver.Downsweep.
The rules are run by "GHC.Driver.Concurrency.runRules" in a demand-driven
way: each worker can demand other workers to run, but never wait on
another worker. Every piece of work is done at most once.
Fixes #27514
Memory usage can increase due to doing more work concurrently:
-------------------------
Metric Increase:
MultiComponentModulesRecomp
MultiComponentModulesRecomp100
mhu-perf
-------------------------
- - - - -
9fa7b7be by sheaf at 2026-10-26T18:19:11-04:00
Acquire/release semaphore tokens more readily
This commit reworks GHC.Driver.MakeSem to use the scoped worker
abstraction of GHC.Utils.Concurrent.Scope. This allows us to get rid of
a lot of the tricky logic in GHC.Driver.MakeSem involving manual
exception handling, thread spawning and lifetime management, etc.
The main user-visible change is that token acquisition is no longer
rate limited (due to a bug, there previously was a 1s rate limit on
acquisition of semaphore tokens), with the release debounce period
shortened from 1s to 10ms.
Other changes:
- With -jsem, the number of capabilities is now capped at the number
of processors, bringing it in line with the -jN behaviour.
- Pending jobs whose wait for a token is interrupted by an exception
are now withdrawn from the jobserver, instead of acquiring a token
that it hung onto without doing useful work.
Fixes #27763
- - - - -
c83c6733 by Alan Zimmerman at 2026-10-26T18:19:55-04:00
EPA: Update AnnClsInstDecl to contain AnnList
It was already separately tracking the '{', '}' and leading ';' values.
This aligns it with layout-introducing parser productions ('vocurly'),
so the layout processing can be handled uniformly
- - - - -
ac870ad5 by Simon Jakobi at 2026-10-28T04:40:42-04:00
X86 NCG: use 32-bit POPCNT for sub-word popcounts
A 32-bit write zero-extends the result to the full register, so we
don't need to emit additional code for this.
We also skip emitting zero-extension instructions for the argument
when it is already visibly zero-extended.
For the byte-wise popcount loop from #24813, this shrinks the popcount
sequence from 5 instructions to 3.
Assisted-by: Claude Fable 5.1
- - - - -
53087373 by Facundo DomĆnguez at 2026-10-28T04:41:32-04:00
Use a ShortByteString in Serialized instead of [Word8]
This makes the in-memory representation 40x more compact for all values
stored in annotations.
A test is added to measure the representation size of annotations
specified in the compiler input.
The GHC API is modified. All functions that previously handled annotations
in [Word8] form now use ShortByteString. The following definitions have
modified types:
* GHC.findGlobalAnns
* GHC.Tc.Gen.Splice.getAnnotationsByTypeRep
* GHC.Core.Opt.Monad.getAnnotations
* GHC.Core.Opt.Monad.getFirstAnnotations
* GHC.Types.Annotations.deserializeAnns
* GHC.Types.Annotations.findAnns
* GHC.Types.Annotations.findAnnsByTypeRep
* GHC.Serialized.Serialized
* GHC.Serialized.toSerialized
* GHC.Serialized.fromSerialized
* GHC.Serialized.serializeWithData
* GHC.Serialized.deserializeWithData
* GHCi.Message.ReifyAnnotations
Fixes #28002.
- - - - -
cc533b66 by Sasha Bogicevic at 2026-10-31T09:18:15-04:00
Don't report -XStrict-generated bangs under -Wredundant-bang-patterns
The -XStrict flag causes the desugarer to insert bang patterns.
These are not user-written, so -Wredundant-bang-patterns must not
report them.
To achieve this, the desugarer now tracks whether it is desugaring
compiler-generated code (similar to the typechecker's 'tcl_in_gen_code').
Bangs inserted by -XStrict are given generated spans, which suppresses
the "redundant bang" warnings without otherwise affecting pattern-match
warnings.
Fixes #27323
- - - - -
13d38047 by Luite Stegeman at 2026-10-31T09:19:11-04:00
rts: tombstone Weak# copies that lose an evacuation race (#23160)
Mark the losing copy of a Weak# during an evacuation race in parallel
GC with stg_DEAD_WEAK_info. This ensures that the nonmoving GC
doesn't follow dangling pointers, leading to crashes.
Fixes #23160
- - - - -
63347328 by Zubin Duggal at 2026-10-31T09:19:52-04:00
ghci: Drop GHCi's exception context when rethrowing in ghc -e
Fixes #27847.
- - - - -
a85fef3f by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context in modifyIOError
Fixes #27851.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/446
- - - - -
1d60b591 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context in mapException
Fixes #27851.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/446
- - - - -
3c029a1b by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in Handle reads
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
ab2b317a by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in hClose
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
f5abf277 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in Windows openFile
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
d842c672 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in executablePath
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
c5a8bb9f by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Simplify a tc-trace which could crash the compiler
The trace formatted an error message, which prematurely
read the ExpType in a FunResCtxt.
Solution: don't put call the error message formatting
when tc-tracing.
- - - - -
ab49b1d2 by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Tiny comment change to uniqAway
- - - - -
6efe4ba3 by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Make niFixSubst idempotent
I discovered (when fixing #27994) that `niFixSubst` didn't actually
generate an idempotent subsitution despite its claims. It could
return a substitution that mentions domain variables on in its range,
when those variables are hidden inside the kind of a type variable
occurrence. As a result it can generate ill-kinded types. Boo!
The fix is simple, and uses deep substitution.
See Note [Finding the substitution fixpoint]
I don't think it actually /caused/ any bugs, so there is no
regression test.
- - - - -
3b60ae7e by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Fix a nasty bug in fundeps
This MR fixes #27994, which turned out to be very tricky.
See Note [Exploiting closed type famililes], especially (CF7). I was
ending up with TyVars (not TcTyVars) in the solver, because the
substitution computed in `getRelevantBranches` mixed the two.
The code was just too clever. I ended up simplifying it quite a bit.
For /closed/ families we no longer call `trimQtvs` (was `trim_qtvs`).
Open families still do use `trimQtvs`. See Note [trimQTvs]
This patch also fixes one other buglet in the same code.
* Over-saturated type families were being mis-handled.
See the new use of `saturatedFamApp_maybe`.
- - - - -
e4610f2d by Facundo DomĆnguez at 2026-10-31T09:21:24-04:00
Have haddock --incremental look for the module in -this-unit-id
- - - - -
bc6c0db6 by sheaf at 2026-10-31T09:22:20-04:00
mightBeFunTy: hotfix for #27979
ce01ccb6 refactored 'GHC.Types.RepType.mightBeFunTy' to look through
unary classes. That change introduced the helper function 'unwrap_type'
which was supposed to always return an unwrapped type, but its fallback
equation mistakenly returned the original type. This caused the
subsequent 'tyConAppTyCon_maybe' to fail in cases where it should
succeed (e.g. looking through foralls).
In this commit, we move all the unary class unwrapping logic into
'unwrapType' where it belonged from the start, and update the
documentation of 'unwrapType' to better explain what it should be used
for (#26695).
Fixes #27979 #26695
-------------------------
Metric Increase:
T5642
-------------------------
- - - - -
233cce46 by Alan Zimmerman at 2026-10-31T09:23:01-04:00
EPA: Tidy up ExactPrint.markAnnListA'
It takes an action which can modify the AnnList, but this
is never used. So remove it.
- - - - -
3594a908 by Sylvain Henry at 2026-10-31T09:23:51-04:00
gitmodules: ignore dirty libffi-clib submodule (#26785)
`./boot` runs autoreconf in libraries/libffi-clib, which leaves
`configure~` behind and rewrites the tracked `aclocal.m4` whenever the
local automake version differs from the one that generated it. Every
checkout then looks dirty. Ignore working-tree changes in the submodule
(`ignore = dirty`); a changed submodule commit is still reported.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
341223c0 by Rodrigo Mesquita at 2026-10-31T09:24:33-04:00
refactor: Keep the interactive Ids directly rather than Name
Removes things like
names <- map idName ids
map (\i -> let id = find (\x -> i==idName x) names) idso
and is more straightforward because there's less state going around (no
more updating HscEnv as an output)
It also kills `printTypeOfNames` completely, since now we just have the
Ids. No longer `lookupName` names to get back the ids...
```
printTypeOfName :: GHC.GhcMonad m => Name -> m ()
printTypeOfName n
= do maybe_tything <- GHC.lookupName n
case maybe_tything of
Nothing -> return ()
Just thing -> printTyThing thing
```
now is just `printTyThing . AnId`
Also:
```diff
- tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
- docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
+ docs <- mapM pprTypeAndContents idsSorted
```
(and yes, in ExecBreaks there are only Ids, no TyThings, bc they are
only constructed by the interpreter execution which can only bind ids.
for TyThings use runDecls which doesn't return execBreaks.)
There's some care to be had to make sure we use the "most refined" Ids,
whereas when using `Name`s we'd always fetch the most refined Id from
scratch.
Fixes #28052
- - - - -
54cf3c1e by sheaf at 2026-11-03T07:00:23-05:00
Consolidate all CPU feature handling
This commit introduces GHC.Platform.CpuFeatures which consolidates all
of the logic for implications between CPU feature flags (mainly X86):
- DynFlags now only records the set of -m<feature> flags that were
passed, as an EnumSet CpuFeature. That keeps it a simple record of
the flags the user passed, with no post-processing.
- GHC.Platform.CpuFeatures.initCpuFeatures turns this set into a
CpuFeatures value, applying all implications and the per-architecture
baseline. This is the single home for all of the feature implication
logic.
Some datatypes were reworked to better reflect the implication
structure in the types, e.g. SseAvxVersion has a strategically
placed 'FMA' boolean.
- The NCG, LLVM backend, StgToCmm, CPP defines and LLVM -mattr
flags all consult CpuFeatures, via targetCpuFeatures.
See Note [CPU features], which replaces
Note [Implications between X86 CPU feature flags].
Behaviour changes:
- x86 feature flags (-msse3, -mavx, -mavx512*, -mgfni, ...) passed
when targeting a non-x86 architecture no longer cause x86 CPP
macros (__SSE3__, __AVX512BW__, __GFNI__, ...) to be defined, nor
x86 attributes to be passed to LLVM.
- Error messages reported when required CPU features are not enabled
now print out the minimal set of flags required
(e.g. "-mavx512vl" rather than "-mavx512f -mavx512vl").
- - - - -
9af64305 by Luite Stegeman at 2026-11-03T07:01:23-05:00
rts: move stack check to the start of the stg_unpack_cstring thunks
fixes a deadlock
see #27272
- - - - -
a2208b21 by Simon Jakobi at 2026-11-03T07:02:05-05:00
Cmm: exclude the entry block from common block elimination
a1d8139054c had fixed #27722 only partially, because it didn't prevent
elimination of the entry block in later rounds, where the entry block is
no longer guaranteed to come first.
To close this loophole, we exclude the entry block from the CBE merge
logic. See Note [Retain entry block during common block elimination] for
details.
This also deletes a misleading comment regarding unreachable blocks: the
control-flow optimiser doesn't actually guarantee that no unreachable
blocks reach CBE.
Fixes #27722.
Assisted-by: Claude Fable 5.1
- - - - -
37ad4710 by Alan Zimmerman at 2026-11-03T07:02:46-05:00
EPA: Use AnnList for GADT declarations
Continuing the process of using AnnList to capture parser layout
- - - - -
56757900 by Sebastian Graf at 2026-11-04T20:36:47+01:00
Documentation for the Core data constructors
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
9f57c265 by Sylvain Henry at 2026-11-06T06:46:15-05:00
ghc-internal: avoid unnecessary allocations in bignum division (#27231)
Avoid unnecessary allocations in bignum division in the Haskell (native)
backend. The long-division loop used to allocate a fresh BigNat for the
partial product on every iteration, plus one more per quotient-digit
correction; it now subtracts the partial product in place and
materializes nothing.
The quotient-digit estimate is also refined against the second-highest
divisor word, so the add-back correction runs at most once per
iteration.
bignat_quotrem_normalized now requires a divisor of at least 2 words, so
bignat_quotrem dispatches 1-word divisors to bignat_quotrem_word.
See Note [Knuth division loop] and Note [Fused multiply-subtract for
long division] in GHC.Internal.Bignum.Backend.Native.
Measured on the new T27231 perf test (10000 native-backend 8192/2048-bit
Integer quotRem calls): bytes allocated drops from 305 MB to 52 MB (-83%).
Improvement on CI (x86-64-linux-deb13-int_native):
space_leak_001(normal) run/alloc 12,492,185,536 9,073,055,928 -27.4% GOOD
Metric Decrease:
space_leak_001
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
c5b80f4e by mangoiv at 2026-11-06T06:46:57-05:00
ci: build and test stage
Split up CI in a build and test stage:
1. in the build stage, just produce a bindist as well as running the
stage1 tests
2. in the test stage, install the bindist, then run the testsuite with
out of tree args
- - - - -
e4b1c892 by mangoiv at 2026-11-06T06:46:57-05:00
ci: reorder packaging and testing stages
- - - - -
19901b41 by mangoiv at 2026-11-06T06:46:57-05:00
ci: out of tree compiler does not imply no hadrian being available
- - - - -
83a860a7 by mangoiv at 2026-11-06T06:46:57-05:00
ci: don't do msys deps check on stage1 compiler
- - - - -
abf5b3af by mangoiv at 2026-11-06T06:46:57-05:00
testsuite: allow metric decreases on windows
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13253-spj
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
9185f1ab by mangoiv at 2026-11-06T06:46:57-05:00
ci: stop using ellipses in testsuite output and output env before invoking hadrian
- - - - -
bf9ece2b by Simon Jakobi at 2026-11-06T06:47:42-05:00
testsuite: Skip the changelog-d test in CI
Full-build validate jobs run the whole testsuite and thus repeated the
changelog validation that the dedicated lint-changelog job had already
reported in the early tool-lint stage.
Skip the test when GITLAB_CI is set, making lint-changelog the only CI
check of changelog.d while keeping the test available in local
testsuite runs.
Fixes #27325.
Assisted-by: Claude Fable 5
- - - - -
ef6adb30 by ARATA Mizuki at 2026-11-06T06:48:31-05:00
testsuite: Mark T367_letnoescape fragile for the optllvm way
It was marked broken, but it is now unexpectedly passing on aarch64-linux-deb13-validate+llvm.
Marking it fragile for now.
See #7292
- - - - -
1db5f9d7 by Rodrigo Mesquita at 2026-11-06T06:49:13-05:00
interp: Make resumeExec and ExecBreak use `Resume` directly
Previously, `Resume` contexts were just put directly in the global
interactive environment state, so they were only accessible through it.
However, in the context of multi-threaded debugging, in that many
threads may hit breakpoints, it no longer suffices to have a global
linear list of breakpoints hit. We need a per-breakpoint Resume context
and need to be able to wield it directly rather than going through a
global context.
The driving changes of this commit are:
- Put the Resume data in ExecBreak
- Make resumeExec receive a Resume as an argument
This also simplifies the interpreter in that we no longer necessarily
rely on the global interactive state to resume a thread. We can do it
directly from the ExecBreak.
The interactive context still maintains a stack of resumes, but
`resumeExec` can no longer pop the resume it resumes off of the
breakpoints stack, since it is no longer guaranteed to be resuming the
first in that list. Hence, callers of `resumeExec` must update ic_resume
on their own.
Fixes #28058
- - - - -
fd00a88c by Rodrigo Mesquita at 2026-11-06T06:49:54-05:00
Per-thread break-on exception (TSO_STOP_ON_EXCEPTION)
The `-fbreak-on-exception` flag allows the interactive interpreter to stop
when a synchronous exception is raised.
However, this is a global toggle backed by a global variable in the RTS
(rts_stop_on_exception) which is not compatible with a multi-threaded
debugger where we may want to stop if some threads raise a synchronous
exception but not other.
This commit makes -break-on-exception similar to step-next and step-out
where there is a per-thread toggle on each TSO (TSO_STOP_ON_EXCEPTION),
and that break-on-exception set in EvalOpts when resuming a statement
only affect the thread being resumed.
Fixes #28068
- - - - -
d735b507 by Andrea Vezzosi at 2026-11-06T06:50:35-05:00
driver: Don't let -dynamic unset -fsplit-sections
`addWay' WayDyn` used to unset Opt_SplitSections, so -fsplit-sections was
ignored if it came before -dynamic, but worked if it came after.
The -fsplit-sections -dynamic combination has legitimate uses, e.g. an
executable can be linked dynamically against libraries and still have dead code
from its own sources to eliminate. Or the same objects could be used for both
static archives and shared objects.
The removal of Opt_SplitSections was also motivated by problems on Darwin.
It is now done in `makeDynFlagsConsistent` instead, see Note [Split sections are not
supported on Mach-O].
For consistency, we also keep Opt_SplitSections when `dynamicNow` is activated.
There is a cost of larger .dyn_o (but not .so) files and slower link times (esp.
with ld.bfd), but does not seem significant enough to warrant special casing.
Fixes #28061
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
10e36bd2 by Alan Zimmerman at 2026-11-06T06:51:18-05:00
EPA: Use AnnList in AnnClassDecl
Capture parser layout
- - - - -
20334e1d by sheaf at 2026-11-06T06:52:06-05:00
Avoid panic in 'solveImplicationsUsingUnsatGiven'
Commit 52a4d1da refactored this code to use 'setWantedDict' which panics
for equality constraints. This commit fixes that by explicitly handling
HoleDest.
Fixes #28081
- - - - -
0423f413 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: add tests for the IO manager lock-up of #21969
T21969a 'closeFdWith' takes every 'EventManager''s 'callbackTableVar'
inside 'uninterruptibleMask_' and only puts them back on the paths
that do not throw, so a throw from 'closeFd_' leaves those MVars
empty for good. Afterwards every 'threadWaitRead' and
'closeFdWith' on an fd in the same bucket blocks forever.
T21969b 'closeFdWith' runs the fd's callbacks while asynchronous exceptions
are uninterruptibly masked, so a callback that blocks makes the
thread calling it permanently unkillable.
T21969c 'closeFd_' drops the registrations before telling the backend to
forget the fd, so when the backend throws the fd is never closed
and the threads waiting on it are never woken.
T21969d the cleanup handler of 'threadWait' calls 'unregisterFd_', which
throws on backend errors. It runs inside the handler for the
asynchronous exception being delivered, so its exception replaces
that one: 'killThread' returns but 'ThreadKilled' never arrives.
T21969e an exception from re-arming an fd escapes the poll loop, and 'loop'
turns it into 'cleanup mgr': the 'EventManager' of that capability
is shut down and every thread using it is left blocked. This is
the lock-up of #21969 itself.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5c197e2e by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Make the IO manager cope with errors from the polling backend (#21969)
Three changes in 'GHC.Internal.Event.Thread': 'closeFdWith' puts every
'callbackTableVar' back on the paths that throw too and no longer skips the
callbacks when 'close' fails, those callbacks now run under the 'mask_' of
'close_loop' rather than uninterruptibly masked, and the cleanup of
'threadWait' ignores a failure from 'unregisterFd_'.
This fixes T21969a, T21969b and T21969d, and clears their expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cb765ded by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let backend errors abandon the close of a file descriptor (#21969)
'closeFd_' and 'closeFd' now ignore errors from telling the backend to forget
the fd: the registration is being torn down and the error says it is already
gone. 'registerFd_' still reports them (!10643), where the caller has to
learn that the registration did not happen. Both also test
'I.elEvent oldEls /= mempty' rather than 'oldEls /= mempty'.
This fixes T21969c, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
9073bc43 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let a backend error take down a capability's IO manager (#21969)
A failure to re-arm an fd in 'selectCallbacks' is now handled the way
'registerFd_' handles one (!10643): the registrations are taken back out of
the callback table and returned, so their callbacks run and the waiting
threads find out for themselves instead of hanging. Checked on aarch64 Linux
(epoll) and aarch64 macOS (kqueue), 10 runs each way.
This fixes T21969e, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cdff4e76 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let the deregistration of threadWaitSTM throw either (#21969)
'threadWaitReadSTM' and 'threadWaitWriteSTM' return the action that gives up
interest in the fd as the second component of their pair, and it was
return (waitAction, unregisterFd_ mgr reg >> return ())
'unregisterFd_' talks to the polling backend, which throws on errors such as
ENOENT and EBADF -- which is how a backend reports an fd it no longer knows,
once that fd has been closed without going through 'closeFdWith'.
That is the same shape as the cleanup of 'threadWait', which the rest of this
series made quiet, and it is the same on both counts. There is nothing to
decide: the registration is being abandoned, and "the backend does not know
this fd" is the state the action is trying to reach. And it does harm: the
action is what a caller uses from the cleanup of a 'bracket', where an
exception out of it replaces whatever was being propagated.
It now goes through 'quietUnregisterFd', as the cleanup of 'threadWait' does,
and that function's comment covers both callers.
T21969f covers it, and is deterministic on both backends: dropping the only
registration changes the event set, so 'unregisterFd_' always reaches the
backend.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
a7ed305b by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: let T21969 run on FreeBSD, and unmark it (#21969, #25512)
T21969 now carries the descriptor from 'createPipe' instead of recovering it
with 'handleToFd', which rejects the 'DuplexHandle' that FreeBSD's
bidirectional pipes become and killed the test in setup there (#25512). The
expect_broken goes with it: with the descriptor problem out of the way the
test times out on master, so it can only be unmarked on top of this series.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
3074ae61 by Sylvain Henry at 2026-11-08T10:21:50-05:00
rts: heap census counts every small pinned object
Blocks of small pinned objects carry BF_LARGE as well as BF_PINNED but
hold many objects. heapCensusChain treated every BF_LARGE block whose
first object is an ARR_WORDS as holding that single object, a workaround
for the slop left by shrinkMutableByteArray# (#11627). So every heap
profile mode under-reported pinned byte arrays, i.e. ByteString payloads.
Shrinking now writes a slop marker that skipSlop understands (#19048,
#27585), so the block walk is safe for large and pinned blocks alike.
The block that a capability fills with small pinned objects stays
attached to the capability until it is full (see allocatePinned), so it
is on no generation list and the census never saw its objects. heapCensus
now walks cap->pinned_object_block too.
A pinned block is kept or freed as a whole (#28005), so dead pinned
objects are counted until their block is freed. T7275 gains one sample in
which its dead small arrays still show. The user guide and changelog
document this.
T7257 retains most of its pinned blocks and takes a census at every GC
(+RTS -i0 -hT), so walking every pinned object made it 7x slower and it
hit the CI timeout. It now runs 1000000 iterations instead of 5000000.
Metric Decrease:
T7257
Fixes #28000
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
16fd075a by Sylvain Henry at 2026-11-08T10:22:39-05:00
rts: fix GC CPU time accounting with idle GC threads (#26169)
stat_endGC summed gc_end_cpu - gc_start_cpu over every GC thread, but
only the threads that take part in a collection set these fields, and
new_gc_thread did not initialise them. With -qn below the capability
count, the first collection after setNumCapabilities added garbage to
the GC CPU time.
Let each participating thread add its own CPU time to an accumulator
in stat_endGCWorker, and let stat_endGC take the total. This removes
the loop over gc_threads, the reset from #21082 and the gc_end_cpu
field. Also drop the unused gc_end_elapsed field.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
0ef732e2 by Sylvain Henry at 2026-11-08T10:23:30-05:00
Serialized: encode numbers with LEB128
serializeWithData used the Binary instances of Data.Binary for the
numbers in a ConstrRep. They have a fixed width: 8 bytes for the
constructor index (an Int) and 5 bytes for a small Integer. Each
element of a [Int] cost 15 bytes.
Now the constructor representation is one unsigned LEB128 number that
also contains the index of an algebraic constructor, and the payloads
(Integer, Rational, Char) are LEB128 encoded. Most constructors take
one byte, and small numbers two. See Note [Serialized encoding].
Sizes measured by the T16841 test:
[1..100] :: [Int] 1509 -> 338 bytes
"helloworld" 119 -> 31 bytes
2^100 :: Integer 24 -> 16 bytes
Just True 18 -> 2 bytes
3.25 :: Double 11 -> 3 bytes
42 :: Int 6 -> 2 bytes
A new test, SerializedRoundTrip, round-trips values at the boundaries
of the encoding (negative numbers, big Integers, Rationals, Chars).
Follow-up to !16841 (#28002).
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
22344fbc by Sylvain Henry at 2026-11-08T10:24:21-05:00
docs: fix duplicate label in qualified_strings.rst
The file started with the label "multiline-strings", copied from
multiline_strings.rst. Sphinx warned about the duplicate label on every
build. Use the label "qualified-strings" instead.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
b7022624 by Alan Zimmerman at 2026-11-08T10:25:02-05:00
EPA: Use LHsLocalBinds instead of HsLocalBinds
This reverses an earlier change, and brings processing of local binds
into alignement with the exact printing principle that the LocatedA
contents provide the location and extent of the enclosed item,
together with any comments or context-specific trailing items like
commas or semi colons.
The internal TTG extension points only carry exact print annotations
related to printing the item within its bounds.
This change brings back the problem of EmptyLocalBinds, which by
definition cannot have a location. These get a noSrcSpan location,
which is ignored in the exact printing process.
- - - - -
bc2fae45 by Rodrigo Mesquita at 2026-11-08T18:37:40-05:00
Build EvalOpts once per exec rather than per breakpoint stop
We were unnecessarily constructing `eval_opts` in `handleRunStatus`
(which is run many times in a loop until we hit a breakpoint we care
about, e.g. when :steplocal), despite the `eval_opts` being constant
across all these runs.
So, construct `eval_opts` outside `handleRunStatus` and share the value
in all loop calls. The loop always uses the same eval_opts, so no point
in constructing them inside `handleRunStatus` from scratch every time.
I found out about the significance of this re-construction of `EvalOpts`
when I added a record update of `eval_opts` *after* the construction
from scratch inside `handleRunStatus` that regressed allocations
significantly.
This improves the performance of `interpreter_steplocal` on my machine:
Baseline
Test Metric value New value Change
-------------------------------------------------------------------------
interpreter_steplocal(ghci) ghc/alloc 459,845,696 449,843,480 -2.2%
Fixes #28068
- - - - -
ba579288 by Rodrigo Mesquita at 2026-11-08T18:38:21-05:00
refactor: move and order helper functions in GHCi.Run
A small refactor to the order of top-level functions in GHCi.Run
- - - - -
24927752 by Luite Stegeman at 2026-11-09T09:21:24-05:00
rts: add missing nonmoving write barrier in out-of-line array copies
The out-of-line entries stg_copyArrayzh/stg_copyMutableArrayzh (taken
whenever the element count of copyArray#/copyMutableArray# is not a
compile-time constant) didn't push the overwritten elements to the
nonmoving collector's remembered set.
Fixes #27376
- - - - -
6dbcca65 by Rodrigo Mesquita at 2026-11-09T09:22:06-05:00
interp: Set per-thread break flags consistently on eval/resume
Currently, the per-thread flags are:
- Single-step: Stop at the immediate next breakpoint in this thread
- Step-out: Stop at the next continuation with a breakpoint this thread
returns to.
- Break-on-exception: Stop the next time a synchronous exception is
raised in this thread.
Originally, these flags were all set globally across all threads. More
recently, these flags are set per-thread when `resume`ing that thread,
but globally when starting the evaluation of a new expression
(`evalStmt`).
With this commit, we now use per-TSO flags in both scenarios evaluating
expressions in the interpreter (`evalStmt` and `resumeStmt`).
- In `resumeStmt` we set the `EvalOpts` specifically in the `ThreadId`
being resumed.
- In `evalStmt`, we set the `EvalOpts` exclusively on the sandbox thread
we fork to evaluate the given expression
- When not using the sandbox thread (i.e. -fno-ghci-sandbox), we
don't support the debugger anyway, so the break flags are
irrelevant.
We do this by consistently calling `setBreakFlags` when starting,
resuming, or killing the evaluation.
See Note [Always setBreakFlags on running thread].
This slightly changes the behavior of evaluating a new expression in
the debugger (resuming a thread behaves the same as before). Namely,
`:step <expr>`, where <expr> forks a thread, will stop at the immediate
next breakpoint in the <expr> main thread, not on a breakpoint of any
forked thread.
NB: the forked thread may still stop at breakpoint, if it is enabled by
index specifically, and then :step-ing from that thread's breakpoint
will toggle per-thread stepping for that forked thread.
We will want to control stepping in "all threads, regardless of whether
we control them or if they were spawned by the debuggee" separately from
the commands which trigger evaluation of just an expression. Namely,
we'll likely want a "break at the next immediate breakpoint hit on ANY
thread" command that the user can execute before launching a debuggee
which is multi-threaded. This may even be the default for GHCi.
Towards #26064
Fixes #28080
- - - - -
19ff36f2 by Simon Jakobi at 2026-11-09T09:22:47-05:00
testsuite: Mark T8209 fragile for the ghci ways on FreeBSD and darwin
A shutdown race in the I/O manager intermittently fails T8209(ghci) on
x86_64-freebsd14-validate and aarch64-darwin-validate, recently killing
several Marge batches. Mark it fragile there until the race is fixed.
See #27948.
Assisted-by: Claude Opus 5.5
- - - - -
212c292f by Rajkumar Natarajan at 2026-11-11T13:54:08-05:00
document what ->>> stands for in heap profile
updates the profiling section of the user's guide to explain how types
are approximated when using -hy. Also adds haddocks to getTyDescription
with the same information.
Fixes #26754
- - - - -
c64fc319 by Jonathan at 2026-11-11T13:54:55-05:00
Fix AArch64 veneer target for relocations with an addend
Fixes #27807
The RTS linker would construct invalid relocation veneers on AArch64 if
the addend was non-zero, which typically caused SIGILL crashes. This
could be triggered by evaluating Template Haskell in a package with a
large number of dependencies using a static build of GHC.
- - - - -
cd4dce19 by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
testsuite: add a test for registerFd_ trusting the callback table (#27821)
registerFd001 shows a 'threadWaitRead' that never finishes after an fd is
closed with 'closeFd' rather than 'closeFdWith'. Darwin is the only platform
this reaches -- one-shot registrations are implemented but not used there
(#7651) -- so the test is expect_broken on Darwin only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5ab442ee by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
registerFd_: always tell the polling backend (#27821)
Where the backend has no one-shot registrations, 'registerFd_' now tells it
about every registration, rather than only when the events differ from the
ones the callback table records: the table alone cannot say whether the
backend still knows the fd. The 'modify' it returns is unchanged. See Note
[Do not trust the callback table].
This fixes registerFd001 and clears its expect_broken.
Changelog wording from Duncan Coutts in review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
ab8b5b06 by Vladislav Zavialov at 2026-11-11T13:56:27-05:00
Curried contexts in prefix GADT constructors (#27424)
Prefix GADT constructor declarations now accept multiple consecutive
contexts, equivalent to a single conjoined context:
data G a where
MkCurried :: C a => (D a, E a) => G a
MkConjoined :: (C a, D a, E a) => G a
This is a step towards GHC Proposal #402 "Stable GADT constructor syntax".
To represent multiple contexts, the `con_mb_cxt` field of `ConDeclGADT` has
been replaced by `con_cxts`, which stores a list instead of a Maybe:
- con_mb_cxt :: Maybe (LHsContext pass)
+ con_cxts :: [LHsContext pass]
The rest of this patch follows from this change.
Note that in ConDeclH98, the optional context is still stored as a Maybe.
To accommodate this difference, a few helper functions were generalised over
a Foldable container `t`:
hsConDeclTheta :: Foldable t => t (LHsContext ...) -> [LHsType ...]
pprLHsContext :: (Foldable t, ...) => t (LHsContext ...) -> SDoc
repContexts :: Foldable t => t (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))
tcHsContext :: Foldable t => t (LHsContext GhcRn) -> TcM [PredType]
In practice, the instantiations of `t` are either `Maybe` or `[]`.
Record-style GADT constructors continue to accept at most one context.
`splitLHsGadtTy` accounts for this by splitting off only the first context
if it detects record syntax, leaving the offending part of the type in the
body for the renamer to reject later on.
Test cases: T12087a T27424a T27424b T27424c T27424d GadtConSigs_th_dump1
- - - - -
d2f135ff by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: cache register usage in liveness annotations
regUsageOfInstr allocates fresh register lists on every call, and on the
linear allocator path it was called three times per instruction: in the
backward liveness pass, in the forward liveness pass and in the allocator
itself. Store the usage computed by the backward pass in the Liveness
annotation and reuse it in the other passes (and in the graph allocator's
spill passes). patchRegsLiveInstr recomputes it for the patched
instruction.
See Note [Cached register usage in liveness annotations].
Part of #28008.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
ff0a5d32 by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: describe register usage with a small DSL
This new register usage DSL (see Note [Register usage DSL] in
GHC.CmmToAsm.RegUsage) reduces allocation compared to the previous
list-based approach.
Fixes #28008.
Metric Decrease:
ManyAlternatives
T12707
T13035
T13379
T13960
T18698b
T19695
T21839c
T3064
T3294
T4801
T5321FD
T5321Fun
T783
T9198
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
51f38f3a by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock-library: fix the build of the spec and fixtures test suites
The documentation pipeline moved from String to Text (commit 202ed264141)
but the two test suites of haddock-library were left behind and no
longer compiled. They are not run by GHC's CI (see #16206), so this went
unnoticed.
The fixtures suite still has four pre-existing failures (list-blocks1,
table1, table4, table5) that are not addressed here.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
394d9d6d by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: parse backtick spans as monospaced text
A backtick span whose content is not a valid Haskell identifier, such as
`foo bar`, was rendered as plain text with literal backticks. It is now
parsed as monospaced text, like @foo bar@. A closed backtick span whose
whole content is one identifier keeps its meaning as a hyperlinked
identifier. A span such as `foldl' f z xs` is code: it is no longer read
as the identifier foldl between a backtick and a single quote. The
TeX-style form `foo' stays an identifier when no backtick closes the
span on the same line.
Code spans follow the CommonMark rules: a span opened by a run of N
backticks ends at the next run of exactly N backticks on the same line,
so ``x `plus` y`` is code "x `plus` y". One space is removed at each end
when both are present, and an unclosed opening run is plain text. The
content is literal: no markup is parsed and backslashes are kept, so
`\x -> x` renders as written.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Fixes #28090
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7ae41c37 by Sylvain Henry at 2026-11-11T13:58:14-05:00
Use 'T' instead of `T' in Haddock comments next to backtick spans
With backtick code spans, a TeX-style quote `T' followed by a backtick on
the same line opens a code span up to that backtick. Use the 'T' form in
the Haddock comments where this happens.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
ce96f0b6 by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: do not parse backtick spans inside @...@
Text between @...@ is already code, so backtick code spans are no longer
parsed there. Thus in
@x <- f -- of type `M Bool`@
the backticks stay as text. Inline markup inside @...@, such as /.../,
passes this context down.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
744b3036 by Sylvain Henry at 2026-11-11T13:58:15-05:00
haddock: keep the backticks of infix identifiers inside @...@
A backticked identifier inside @...@ was always rendered without its
backticks, so @f `elem` xs@ rendered as "f elem xs". Now an identifier
in an infix application or an operator section, such as @f `elem` xs@
or @(`elem` xs)@, is parsed in infix form, as if written ``elem``, and
renders with its backticks and with elem linked. Elsewhere, as in
@`foldlM` :: ...@, the backticks still only mark the link.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
0d8e1f8d by Sylvain Henry at 2026-11-11T13:59:05-05:00
PPC NCG: print non-standard NaN literals in target byte order
The PowerPC NCG printed a non-standard NaN literal byte by byte with
floatToBytes/doubleToBytes, which use the byte order of the host. This
is wrong when the host and the target have a different endianness (e.g.
from x86_64 to big-endian PowerPC). Print the bits with `.long`/`.quad`
instead, so that the assembler uses the target byte order.
Also make `ppr_item` print its argument: some clauses printed the
literal of `pprDataItem` instead.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
5a9db1ed by Sylvain Henry at 2026-11-11T13:59:05-05:00
Print all NaN literals as integer bits (#28101)
The x86 and PowerPC NCGs printed the quiet NaNs 0x7fc00000 and
0x7ff8000000000000 as `.float NaN`/`.double NaN`. GNU as and clang
encode these with all mantissa bits set, so constant-folded bit casts
of these values gave 0x7fffffff/0x7fffffffffffffff. The C backend
printed every NaN as `NAN`, losing its sign and payload.
Now the NCGs print all NaNs with `.long`/`.quad` and the C backend with
hs_bitcastword2float/hs_bitcastword642double.
See Note [Printing NaN literals].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b4ceb6a9 by mangoiv at 2026-11-11T13:59:47-05:00
ci: fix ghcup nightly script misbehaviour
- download all jobs instead of just the first 100
- stop using a canary job to detect whether it's a nightly or release
pipeline
- - - - -
aefa0c1b by Alan Zimmerman at 2026-11-11T14:00:28-05:00
EPA: Use AnnList in HsMultiIf
It introduces layout, capture it
- - - - -
d72505e4 by Simon Jakobi at 2026-11-12T15:26:14-05:00
testsuite: Fix T17088 flakiness and restore bug coverage
T17088 reads and prints a byte from an uninitialized array. Debug RTS
ways fill allocated memory with 0xaa, so the test can fail due to an
output mismatch unrelated to the pointer-tagging bug it covers.
Initialize the byte to zero to make the output deterministic.
The original bug requires the compacting collector and particular
compiler and RTS settings. Run the test only in the compacting_gc way
with -O1 and -A128k. Also disable STG lambda lifting because it removes
the closure shape needed to reproduce the pointer-tagging failure.
This makes the test reliable while ensuring it remains an effective
reproducer for #17088.
Closes #27534.
Assisted-by: gpt-5.6-sol via Codex CLI
- - - - -
5a7591b3 by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: Fix python type errors
These errors appear when using the VSCode python extension which uses
Pylance under the hood.
- - - - -
52f129f8 by David Eichmann at 2026-11-12T15:26:56-05:00
Add test modifier to test over all IO Managers
- - - - -
22e8b92a by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: include custom IO Manager in test name
- - - - -
82c34ccd by Simon Jakobi at 2026-11-12T15:27:40-05:00
Make T2464 actually test #ifdef'd pragmas
The test guarded a LANGUAGE EmptyDataDecls pragma behind #if, but
EmptyDataDecls is on by default since Haskell2010, so the module
compiled even when the guarded pragma was ignored. Guard MagicHash
instead, which is unlikely to be included in a future default language.
The test also checks that warnings from file-header pragmas are emitted
only once, even though the pragmas are parsed both before and after
CPP, using the -fffi deprecation warning as the canary. Use an
unrecognised warning flag instead, so the test no longer depends on a
deprecated flag that is about to be removed.
Context: #27939
Assisted-by: Claude Fable 5.1
- - - - -
419f2a12 by Simon Jakobi at 2026-11-12T15:27:40-05:00
Remove command-line flags deprecated in GHC 8.2 or earlier
Also remove the INCLUDE file-header pragma, which only expanded to
the now-removed -#include.
Closes #27939.
Assisted-by: Claude Fable 5.1
- - - - -
adc294d0 by Erik de Castro Lopo at 2026-11-12T15:28:21-05:00
TimerManager: publish only evaluated timeout queues (#9809)
The issue in #9809 was triggered by many threads registering timeouts
at the same time and those timeouts being stored as unevaluated thunks
in the shared list. When say 100,000 timeouts are registered at the
same time, the program can be slowed down considerably and the memory
usage grow unacceptably large.
The commit that caused the problem was 2d5eccdf1c, a 2013 change that
fixed #7653.
The fix is to add a modifyTimeouts function which applies an edit to a
copy of the list and fully evaluates the result before replacing the
shared list with a CAS operation.
Performance has improved for the threaded case and not regressed for
the single thread case:
Forked registrations of 100k timeouts (median of 5 runs):
-N4: 0.577 s, 428 MB -> 0.078 s, 39 MB
-N12: 1.227 s, 479 MB -> 0.127 s, 80 MB
Forked registrations of 1M timeouts on -N1 (median of 3 and 10 runs):
5.21 s (range 0.67-9.47 s), 1613 MB -> 0.67 s, 250 MB
Single-thread registrations are unchanged or slightly faster, and timer
latency during registration storms improves (p99 lateness of a 1 ms
threadDelay during 100k forked registrations on -N4: 302-394 ms ->
3.5-4.1 ms).
The registration code still runs in constant stack, so #7653 stays fixed;
T7653 and the concurrent, base and ghc-internal testsuites pass.
modifyTimeouts is OPAQUE so that the optimiser cannot expose the edit
function's inspection of the old queue next to the compare-and-swap and
replace the expected pointer with the evaluated queue, which would make the
compare-and-swap keep failing when the MutVar# holds a thunk or indirection.
Regression test T9809.hs included.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b294b82f by Moritz Angermann at 2026-11-12T15:28:21-05:00
testsuite: give pause_resume_via_safe_ffi_concurrent 60s on Darwin CI
The 10s System.Timeout watchdog was a false deadlock: five serialized
1s pauses plus rts_pause waiting on threadDelay/timer-manager traffic
overruns that budget on loaded Mac runners. Keep a watchdog so a real
hang still fails.
- - - - -
1543f834 by Simon Jakobi at 2026-11-12T15:29:03-05:00
testsuite/README: Don't append new tests at the end of all.T
Patches that each add a test at the end of the same all.T conflict
with each other. Tests added elsewhere in the file usually merge cleanly.
Context: #26285
Assisted-by: Claude Opus 5.5
- - - - -
9ad25cb2 by Sven Tennie at 2026-11-14T06:20:13-05:00
hadrian: Add Stage3 cross-compiled target bindist (#26924)
Add a `binary-dist-stage3` Hadrian target that packages target
executables (produced by the stage2 compiler) into a separate
'_build/bindist-stage3/' folder, distinct from the stage2 regular or
cross-compiler bindist in '_build/bindist/'.
This allows a single CI pipeline job to produce both a cross-compiler
bindist (e.g. x86_64 -> RISC-V) and a target-architecture bindist (e.g.
RISC-V -> RISC-V) that can be installed and run natively on the target.
To avoid issues with stale files or race-conditions on them, generate
the `configure` script per stage in `_build/<stage>/distrib`
directories.
- - - - -
ca91017d by Sven Tennie at 2026-11-14T06:20:13-05:00
ci: Build Stage3 and Stage2 bindists for cross targets in one job (#26924)
Building the stage3 target bindist already produces most of the stage2
cross-compiler bindist as a byproduct, so building them in separate jobs
duplicates the build efforts for no benefit. Instead of a separate
CROSS_STAGE=3 job, the stage3 job now also builds and publishes the
stage2 bindist.
The stage3 tarball is named and versioned as if it were built natively
on the target (target triple prefix, non-cross opsys), so its artifact
name stays what downstream consumers already expect and no changes are
needed on their side.
For now, this is only enabled for the RISC-V job. Others can easily
follow.
- - - - -
71b41e09 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: model cross targets as structured TargetPlatform triples (#26924)
Storing the cross target as a raw triple forced ad-hoc parsing at every
use, and broke the single responsibility rule. Modelling it as a
structured `TargetPlatform`` instead, avoids parsing and provides a
clear separation of concerns.
- - - - -
8067c2f9 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: extract the cross smoke tests into a separate smoke_test command (#26924)
This reduces if-nesting and complexity of the main `test_hadrian`
command. The decision how to test is now made by the caller. This is a
fair choice, because most test cases can run under emulation - they are
just very slow then.
The Stage3 smoke test also checks that the target compiler does not report
itself as cross-compiling and, when supported, runs a small GHCi expression.
- - - - -
7ece99a7 by fendor at 2026-11-14T06:20:57-05:00
Add `-dep-json` flag to `ghc -M`
Add an optional flag to `ghc -M` that allows to write the dependency
information in JSON Lines format.
The JSON Lines format enables us to stream the output of the dependency
generation to a consumer.
The output of `-dep-json` is streamed to a temporary file and then
copied to the final destination to avoid partial writes.
Each line contains one of two possible json objects:
1. A Home Unit Dependency
* Contains the name of the home module, its unit, where it is
located, whether a preprocessor is used, and all of its imports.
Importantly, the imports include `-XExplicitLevelImports`
information.
* If requested via `-include-pkg-deps`, includes imports of external
units, e.g. modules from `base`.
* If requested via `-include-cpp-deps`, files included via CPP.
2. External Unit Dependency
* Only if `-include-pkg-deps` is given
* Contains unit-id, its package name and package id.
---
This PR refactors the Makefile generation to use phases appropriately.
We introduce an intermediate data structure that is generated based on
the module graph nodes, and only then generate the Makefile rules.
This allows the dep-json and dep-makefile generation to use the same
dependency processing.
- - - - -
0f6e0146 by fendor at 2026-11-14T06:20:57-05:00
Add multiple home unit support to `ghc -M`
Allows to process the module graph of multiple home units at once using
the same syntax as `--make` and `--interactive`:
ghc -M -unit @unitA -unit @unitB
The semantics are identical to `--make` and `--interactive`.
Each home unit can declare individually to use `-include-cpp-deps` and
`-include-pkg-deps`.
However, there can only be one output file, and `-dep-json` and
`-dep-makefile` can only be provided at the top of the cli invocation.
We introduce a new GHC API `doMkDepend` that allows to use multiple home
units conveniently.
The output of `-dep-json` and `-dep-makefile` does not change, since we
were careful to choose a format that supports multiple home units from
the start.
Single home units are still accepted like before with no changes.
- - - - -
5598e6a0 by fendor at 2026-11-14T06:20:57-05:00
Deprecate `doMkDependHS` in favour of `doMkDepend`
- - - - -
39f2943e by David Eichmann at 2026-11-14T06:21:41-05:00
rts: Expose getRtsSymbols() and store redirect labels and external symbols tag
- - - - -
aa159605 by David Eichmann at 2026-11-14T06:21:41-05:00
hadrian: when running tests, properly set have_gdb and have_readelf
- - - - -
ff826da4 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: add have_ldd() test modifier
- - - - -
b9f0b7e2 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite driver: on windows, ensure PATH correctly contains mingw and ghc-pkg libraries
- - - - -
543c108e by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: driver now sets WAY_FLAGS variable for makefile tests
- - - - -
13408a2b by David Eichmann at 2026-11-14T06:21:41-05:00
Add golden test for rts/RtsSymbols.c
This test compares declared symbols against symbols observed
in the rts DSO (.so file).
- - - - -
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
cbe0a6bf by fendor at 2026-11-17T09:25:55-05:00
Add support for streaming `ghc -M` to stdout
Adds the flags `-dep-json-stdout` and `-dep-makefile-stdout` which
streams dependency information line-by-line to stdout.
Each dependency generation can be redirected to separate outputs.
Providing any extra `-dep-{json,makefile}[-stdout]` disables the default
generation of the `Makefile` file.
Allows consumers to start processing the dependency information as it
comes in and not waiting for the dependency generation to finish.
`DepStream` abstracts over the possible output handles, which is either
a file or the stdout handle.
Writing to a file requires temporary file paths, thus `DepStream` must
provide a way to perform clean up when dependency processing finished or
when an error is thrown for any reason.
We further decouple the rendering and writing of the result from the
dependency generation, localising side effects and making the code
slightly more readable.
The testsuite now also handles `ghc -M` writing to stdout.
We add a test for each combination of writing to stdout and file,
except for writing both makefile and json.
While it probably works, is really undefined behaviour.
Closes #27937
- - - - -
fbd49db2 by Sylvain Henry at 2026-11-17T09:27:09-05:00
Link the on-demand iserv without --gc-sections
GHC links an iserv program each time a session needs the external
interpreter. The link is static, against the ghci library and the boot
libraries. Like all executable links, it passed -Wl,--gc-sections to a
GNU linker. On libraries built with -split-sections (the release
bindists), the section garbage collection of ld.bfd is the largest part
of that link: with binutils 2.45, the link takes 3 times longer with
--gc-sections than without. The program is temporary and its size is
not important. Thus the iserv link does not use --gc-sections. Other
executable links do not change.
In CI, each ext-interp or ghci-ext test takes 12 to 18 times longer in
the x86_64-linux-fedora43-release test job (split sections) than in the
x86_64-linux-deb13-validate test job (no split sections) on the same
runner, while a normal-way test takes the same time in both. This link
is most of that difference.
See Note [No --gc-sections for the on-demand iserv] in
GHC.Runtime.Interpreter.C.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
09c965e2 by mangoiv at 2026-11-17T09:27:51-05:00
ci: make tests-primops run on marge CI
test primops dispatch was disabled on the *full-ci
group label to avoid dispatching for some of its configs
but wasn't reenabled for marge ci runs which it ought to
run
Fixes #27765
- - - - -
83038fbe by David Eichmann at 2026-11-17T09:28:32-05:00
test driver refactor: replace `.format(**locals())` with f-string
- - - - -
26d671fd by fendor at 2026-11-20T16:21:01+01:00
Add more .hie file tests for OverloadedRecordDot
Add 'selectRange' function to get the type of a selection.
- - - - -
828c4935 by fendor at 2026-11-20T16:21:02+01:00
Record `FieldLabel` source span in AST node
We attach evidence variables based on the source span of the concrete
AST node in the HIE file.
The evidence for the `HasField` constraint has the source span of the
field selector, e.g. the AST node that gave rise to the `HasField`
constraint.
Since the AST node doesn't show up in the HIE file, the evidence for
`HasField` was also not recorded for the span. Thus, `getEvidenceTree`
wouldn't even list `HasField` as evidence, even in the perfectly normal
case of:
baz :: HasField "foo" f Int => f -> Int
baz f = f.foo
Requesting the evidence tree for `.foo` should point to the definition
of `baz`, but since we omitted the source span for the field selector `.foo`
from the AST node, the HIE file doesn't list it as evidence.
By using the source spans of the individual field selectors, there are two consequences:
* We can see the `HasField` evidence for record dot syntax at the field
selector span
* The reported type of `.foo` is `Foo -> Int` instead of just `Int`
The latter is a change of behaviour that is unfortunate but the right
behaviour, since there is now a source span for the whole expression
`x.foo`, one for `x` and one for the selector `.foo`.
If you query for the type at span `x.foo`, then the correct type `Int`
is shown, but in downstream tooling (such as HLS), such requests are not
possible in LSP. Thus, the behaviour changes.
- - - - -
42d9406c by fendor at 2026-11-20T16:21:02+01:00
Allow any `Id` to be used for HIE evidence
HIE evidence is used to show how a constraint has been solved and allows
users to go directly to the definition or introduction of a particular
evidence variable.
So far, we only looked at evidence introduced by type class variables,
but some evidence terms refer to other variables as well, such as record selectors.
Such evidence terms add additional details and source locations.
For generated evidence, such as `HasField` evidence to support
`-XRecordDotSyntax`, the type class evidence is lacking and doesn't
give us any usable source span pointing to the actual record selector.
See this example evidence:
$dHasField_aLw
= GHC.Internal.Records.C:HasField
@GHC.Internal.Types.Symbol
@GHC.Internal.Types.LiftedRep
@GHC.Internal.Types.LiftedRep
@"foo"
@Foo
@Int
(foo `cast` (<Foo -> Int>_R :: (Foo -> Int) ~R# (Foo -> Int)))
The free variables of this term are `{C:HasField, foo}`.
`foo` is the record selector from the type `Foo` and is crucial to guide
users how this evidence is constructed, as the evidence `HasField` is
not helpful.
During HIE generation, we now take any `Id` into account to provide
additional source spans to point to user to the definition site of the
record selector.
As a direct consequence, this allows HLS to implement a limited form of
`Goto Definition` for expressions of the form `x.foo`, where `x :: Foo`.
Capturing more `Id`s for evidence may have some side effects that are
somewhat tricky to predict, since the tests are quite lacking.
- - - - -
b7d5997a by fendor at 2026-11-20T16:21:02+01:00
Add additional details to evidence bindings
Evidence bindings can be all sorts of things, such as tpe class
evidence, a record selector or other builtin constructs such as
`Typeable`.
For some special evidence binding dependencies, we can include
additional information for the user.
For example, when we have a record selector, we can say from which type
the record selector originates from.
- - - - -
1220 changed files:
- .gitignore
- .gitlab-ci.yml
- .gitlab/ci.sh
- .gitlab/common.sh
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/hello.hs
- .gitlab/jobs.yaml
- .gitlab/rel_eng/mk-ghcup-metadata/mk_ghcup_metadata.py
- .gitmodules
- + changelog.d/21969
- + changelog.d/24450
- + changelog.d/25665
- + changelog.d/25763-cmdline-opt
- + changelog.d/25850
- + changelog.d/26169.md
- + changelog.d/26610
- changelog.d/26616
- + changelog.d/26761
- + changelog.d/27368
- + changelog.d/27624
- + changelog.d/27641
- + changelog.d/27732
- + changelog.d/27821
- + changelog.d/27845
- + changelog.d/27892
- + changelog.d/27936
- + changelog.d/27971
- + changelog.d/28002-leb128
- + changelog.d/28012
- + changelog.d/28080
- + changelog.d/28081
- + changelog.d/28101
- + changelog.d/T23785
- + changelog.d/T26543
- + changelog.d/T26754
- + changelog.d/T27323
- changelog.d/T27329
- + changelog.d/T27412
- changelog.d/T27455
- + changelog.d/T27545
- + changelog.d/T27629
- changelog.d/T27722-cbe-entry-block.md
- + changelog.d/T27731
- + changelog.d/T27763
- + changelog.d/T27788-js-selector
- + changelog.d/T27828
- + changelog.d/T27830-rts-flag-bounds
- + changelog.d/T27831-bottoming-strict-field
- + changelog.d/T27842-bytecode-imported-tags
- + changelog.d/T27844
- + changelog.d/T27847
- + changelog.d/T27916
- + changelog.d/T27979
- + changelog.d/T27994
- + changelog.d/T28002
- + changelog.d/T28002-api
- + changelog.d/T28123
- + changelog.d/T4162
- + changelog.d/T9809-timer-manager-contention
- changelog.d/allow-gadt-prefix-con-parens
- + changelog.d/bignum-quotrem-no-alloc
- + changelog.d/boxing-family
- + changelog.d/caf-deadlock-27272
- + changelog.d/clc-341-strict-mutable-data-types
- + changelog.d/clc-421
- + changelog.d/clc-446
- + changelog.d/clc-447
- + changelog.d/fix-aarch64-veneer-target-16686
- + changelog.d/fix-compacting-gc-constr-27649
- + changelog.d/fix-control0-mask-trampoline
- + changelog.d/fix-copyarray-nonmoving-barrier-27376
- + changelog.d/fix-cross-ghc-info-unit-id
- + changelog.d/fix-heap-census-pinned-blocks.md
- + changelog.d/fix-nonmoving-weak-evacuation-race-23160
- changelog.d/fix-parallel-gc-selector-race-27477
- + changelog.d/fix-threadlabel-segfault-27618
- + changelog.d/gadt-curried-contexts-27424
- + changelog.d/ghc-api-exec-break-resume
- + changelog.d/ghc-api-interactive-ids
- + changelog.d/hadrian-persist-flavour
- + changelog.d/hpc-classinsts
- + changelog.d/hpc-cleanup
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-deprecate-doMkDependHS
- + changelog.d/make-depends-json
- + changelog.d/make-depends-multiple-home-units
- + changelog.d/make-depends-streaming-output
- + changelog.d/monad-of-no-return-canonical
- + changelog.d/ncg-reg-usage.md
- + changelog.d/ncg-x86-subword-popcnt
- + changelog.d/parallel-downsweep
- + changelog.d/record-dot-evidence
- + changelog.d/remove-long-deprecated-flags.md
- + changelog.d/resizeMutableByteArray-pinnedness
- + changelog.d/select-io-manager
- changelog.d/semaphore-v2
- + changelog.d/split-sections-dynamic
- + changelog.d/stage3-cross-bindists
- changelog.d/tcplugin_init.md
- + changelog.d/unboxed-do
- changelog.d/unit-index
- + changelog.d/zap-coercions
- compiler/GHC.hs
- compiler/GHC/Builtin.hs
- compiler/GHC/Builtin/KnownKeys.hs
- compiler/GHC/Builtin/Modules.hs
- compiler/GHC/Builtin/Uniques.hs
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/Builtin/WiredIn/Prim.hs
- compiler/GHC/Builtin/WiredIn/TypeLits.hs
- compiler/GHC/Builtin/WiredIn/Types.hs
- + compiler/GHC/Builtin/WiredIn/Types/Box.hs
- compiler/GHC/Builtin/primops.txt.pp
- compiler/GHC/ByteCode/Asm.hs
- compiler/GHC/ByteCode/Show.hs
- compiler/GHC/Cmm/CallConv.hs
- compiler/GHC/Cmm/CommonBlockElim.hs
- compiler/GHC/Cmm/GenericOpt.hs
- compiler/GHC/Cmm/UniqueRenamer.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/CFG/Dominators.hs
- compiler/GHC/CmmToAsm/Config.hs
- compiler/GHC/CmmToAsm/Dwarf/Types.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Ppr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- + compiler/GHC/CmmToAsm/RegUsage.hs
- compiler/GHC/CmmToAsm/Wasm/Asm.hs
- compiler/GHC/CmmToAsm/Wasm/Types.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/CmmToLlvm/CodeGen.hs
- compiler/GHC/CmmToLlvm/Config.hs
- compiler/GHC/Core.hs
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Coercion.hs-boot
- compiler/GHC/Core/Coercion/Axiom.hs
- compiler/GHC/Core/Coercion/Opt.hs
- compiler/GHC/Core/DataCon.hs
- compiler/GHC/Core/FVs.hs
- compiler/GHC/Core/FamInstEnv.hs
- compiler/GHC/Core/Lint.hs
- + compiler/GHC/Core/Lint.hs-boot
- compiler/GHC/Core/Make.hs
- + compiler/GHC/Core/Make/BigTuple.hs
- + compiler/GHC/Core/Make/Box.hs
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/CallerCC.hs
- compiler/GHC/Core/Opt/CallerCC/Types.hs
- compiler/GHC/Core/Opt/Exitify.hs
- compiler/GHC/Core/Opt/Monad.hs
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Core/Opt/SetLevels.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Core/Predicate.hs
- compiler/GHC/Core/Reduction.hs
- compiler/GHC/Core/Seq.hs
- compiler/GHC/Core/SimpleOpt.hs
- compiler/GHC/Core/Subst.hs
- compiler/GHC/Core/TyCo/Compare.hs
- compiler/GHC/Core/TyCo/FVs.hs
- compiler/GHC/Core/TyCo/FVs.hs-boot
- + compiler/GHC/Core/TyCo/Make.hs
- + compiler/GHC/Core/TyCo/Make.hs-boot
- compiler/GHC/Core/TyCo/Ppr.hs
- compiler/GHC/Core/TyCo/Rep.hs
- compiler/GHC/Core/TyCo/Rep.hs-boot
- compiler/GHC/Core/TyCo/Subst.hs
- compiler/GHC/Core/TyCo/Tidy.hs
- compiler/GHC/Core/TyCon.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Type.hs-boot
- compiler/GHC/Core/Unify.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToIface.hs-boot
- compiler/GHC/CoreToStg.hs
- compiler/GHC/CoreToStg/AddImplicitBinds.hs
- + compiler/GHC/Data/Dependent.hs
- compiler/GHC/Data/FastString.hs
- compiler/GHC/Data/OrdList.hs
- compiler/GHC/Data/OsPath.hs
- compiler/GHC/Data/Pair.hs
- + compiler/GHC/Data/StringTrie.hs
- compiler/GHC/Data/Word64Map/Internal.hs
- compiler/GHC/Data/Word64Map/Strict/Internal.hs
- compiler/GHC/Data/Word64Set/Internal.hs
- compiler/GHC/Driver/Backpack.hs
- compiler/GHC/Driver/CmdLine.hs
- + compiler/GHC/Driver/Concurrency.hs
- compiler/GHC/Driver/Config.hs
- compiler/GHC/Driver/Config/CmmToAsm.hs
- compiler/GHC/Driver/Config/CmmToLlvm.hs
- + compiler/GHC/Driver/Config/Concurrency.hs
- compiler/GHC/Driver/Config/Core/Lint.hs
- compiler/GHC/Driver/Config/StgToCmm.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Errors/Ppr.hs
- compiler/GHC/Driver/Errors/Types.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeAction.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/MakeSem.hs
- compiler/GHC/Driver/Pipeline.hs-boot
- compiler/GHC/Driver/Pipeline/Execute.hs
- compiler/GHC/Driver/Pipeline/LogQueue.hs
- compiler/GHC/Driver/Pipeline/Phases.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Driver/Session/Units.hs
- compiler/GHC/Hs/Binds.hs
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/Doc.hs
- compiler/GHC/Hs/Dump.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/ImpExp.hs
- compiler/GHC/Hs/Lit.hs
- compiler/GHC/Hs/Pat.hs
- compiler/GHC/Hs/Type.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Arrows.hs
- compiler/GHC/HsToCore/Binds.hs
- compiler/GHC/HsToCore/Docs.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Expr.hs-boot
- compiler/GHC/HsToCore/ListComp.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- compiler/GHC/HsToCore/Pmc/Desugar.hs
- compiler/GHC/HsToCore/Pmc/Types.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/HsToCore/Types.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Iface/Decl.hs
- compiler/GHC/Iface/Errors/Types.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Iface/Ext/Debug.hs
- compiler/GHC/Iface/Ext/Types.hs
- compiler/GHC/Iface/Ext/Utils.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Iface/Rename.hs
- compiler/GHC/Iface/Syntax.hs
- compiler/GHC/Iface/Tidy.hs
- compiler/GHC/Iface/Type.hs
- compiler/GHC/Iface/Type.hs-boot
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/JS/Opt/Simple.hs
- compiler/GHC/Linker/Deps.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/Errors/Ppr.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Parser/String.hs
- compiler/GHC/Platform.hs
- + compiler/GHC/Platform/CpuFeatures.hs
- compiler/GHC/Platform/Ways.hs
- compiler/GHC/Rename/Bind.hs
- compiler/GHC/Rename/Env.hs
- compiler/GHC/Rename/Expr.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Names.hs
- compiler/GHC/Rename/Unbound.hs
- compiler/GHC/Rename/Utils.hs
- compiler/GHC/Runtime/Context.hs
- compiler/GHC/Runtime/Debugger.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Heap/Inspect.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- compiler/GHC/Runtime/Interpreter/JS.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Settings.hs
- compiler/GHC/Settings/IO.hs
- compiler/GHC/Stg/BcPrep.hs
- compiler/GHC/Stg/Debug.hs
- compiler/GHC/Stg/EnforceEpt.hs
- compiler/GHC/Stg/EnforceEpt/Rewrite.hs
- compiler/GHC/Stg/EnforceEpt/TagSig.hs
- compiler/GHC/Stg/EnforceEpt/Types.hs
- compiler/GHC/Stg/Lint.hs
- compiler/GHC/Stg/Make.hs
- compiler/GHC/Stg/Subst.hs
- compiler/GHC/StgToCmm/Closure.hs
- compiler/GHC/StgToCmm/Config.hs
- compiler/GHC/StgToCmm/Prim.hs
- compiler/GHC/StgToJS/Apply.hs
- compiler/GHC/StgToJS/CodeGen.hs
- compiler/GHC/StgToJS/ExprCtx.hs
- compiler/GHC/StgToJS/Linker/Linker.hs
- compiler/GHC/StgToJS/Object.hs
- compiler/GHC/StgToJS/Prim.hs
- compiler/GHC/StgToJS/Symbols.hs
- compiler/GHC/SysTools/Cpp.hs
- compiler/GHC/Tc/Deriv.hs
- compiler/GHC/Tc/Deriv/Functor.hs
- compiler/GHC/Tc/Deriv/Generate.hs
- compiler/GHC/Tc/Deriv/Generics.hs
- compiler/GHC/Tc/Errors.hs
- compiler/GHC/Tc/Errors/Ppr.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/App.hs
- compiler/GHC/Tc/Gen/Arrow.hs
- compiler/GHC/Tc/Gen/Export.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Match.hs
- compiler/GHC/Tc/Gen/Pat.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Instance/FunDeps.hs
- compiler/GHC/Tc/Instance/Typeable.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Plugin.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/Equality.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Tc/Solver/InertSet.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/Solver/Rewrite.hs
- compiler/GHC/Tc/Solver/Solve.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/TyCl/PatSyn.hs
- compiler/GHC/Tc/Types.hs
- compiler/GHC/Tc/Types/Constraint.hs
- compiler/GHC/Tc/Types/ErrCtxt.hs
- compiler/GHC/Tc/Utils/Backpack.hs
- compiler/GHC/Tc/Utils/Monad.hs
- compiler/GHC/Tc/Utils/TcMType.hs
- compiler/GHC/Tc/Utils/TcType.hs
- compiler/GHC/Tc/Utils/Unify.hs
- compiler/GHC/Tc/Zonk/Env.hs
- compiler/GHC/Tc/Zonk/Monad.hs
- compiler/GHC/Tc/Zonk/TcType.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Annotations.hs
- compiler/GHC/Types/Arity.hs
- compiler/GHC/Types/Basic.hs
- compiler/GHC/Types/CompleteMatch.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Demand.hs
- compiler/GHC/Types/Error/Codes.hs
- compiler/GHC/Types/Hint.hs
- compiler/GHC/Types/Hint/Ppr.hs
- compiler/GHC/Types/Id.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Types/Id/Make.hs
- compiler/GHC/Types/Literal/Floating.hs
- compiler/GHC/Types/Name/Env.hs
- compiler/GHC/Types/Name/Occurrence.hs
- compiler/GHC/Types/RepType.hs
- compiler/GHC/Types/Tickish.hs
- compiler/GHC/Types/TyThing.hs
- compiler/GHC/Types/TyThing/Ppr.hs
- compiler/GHC/Types/Unique.hs
- compiler/GHC/Types/Unique/DSM.hs
- compiler/GHC/Types/Unique/DSet.hs
- compiler/GHC/Types/Unique/FM.hs
- compiler/GHC/Types/Unique/Map.hs
- compiler/GHC/Types/Unique/Set.hs
- compiler/GHC/Types/Unique/Supply.hs
- compiler/GHC/Types/UnresolvedImport.hs
- compiler/GHC/Types/Var.hs
- compiler/GHC/Types/Var.hs-boot
- compiler/GHC/Types/Var/Env.hs
- compiler/GHC/Types/Var/FV.hs
- compiler/GHC/Types/Var/Set.hs
- compiler/GHC/Unit/Env.hs
- compiler/GHC/Unit/External/Database.hs
- compiler/GHC/Unit/External/ModuleOrigin.hs
- compiler/GHC/Unit/External/Visibility.hs
- compiler/GHC/Unit/External/Wired.hs
- compiler/GHC/Unit/Finder.hs
- + compiler/GHC/Unit/Finder/Cache.hs
- compiler/GHC/Unit/Finder/Types.hs
- compiler/GHC/Unit/Home.hs
- compiler/GHC/Unit/Module.hs
- compiler/GHC/Unit/Module/Env.hs
- compiler/GHC/Unit/Module/Graph.hs
- compiler/GHC/Unit/Module/ModSummary.hs
- + compiler/GHC/Unit/Module/Name.hs
- compiler/GHC/Unit/Module/WholeCoreBindings.hs
- compiler/GHC/Unit/Parser.hs
- compiler/GHC/Unit/State.hs
- compiler/GHC/Unit/Types.hs
- compiler/GHC/Unit/Types.hs-boot
- compiler/GHC/Utils/Binary.hs
- + compiler/GHC/Utils/Concurrent/Scope.hs
- compiler/GHC/Utils/Json.hs
- compiler/GHC/Utils/Monad/Codensity.hs
- + compiler/GHC/Utils/Monad/StrictIdentity.hs
- + compiler/GHC/Utils/Monad/StrictReader.hs
- compiler/GHC/Utils/Monad/State/Strict.hs ā compiler/GHC/Utils/Monad/StrictState.hs
- compiler/GHC/Utils/Outputable.hs
- compiler/GHC/Utils/Panic.hs
- compiler/GHC/Utils/Ppr/Colour.hs
- compiler/GHC/Utils/TmpFs.hs
- compiler/Language/Haskell/Syntax.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Decls/Foreign.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/Extension.hs
- compiler/Language/Haskell/Syntax/ImpExp.hs
- compiler/Language/Haskell/Syntax/Lit.hs
- compiler/Language/Haskell/Syntax/Module/Name.hs
- compiler/Language/Haskell/Syntax/Specificity.hs
- compiler/Language/Haskell/Syntax/Text.hs
- compiler/Language/Haskell/Syntax/Type.hs
- compiler/ghc.cabal.in
- distrib/configure.ac.in
- docs/users_guide/codegens.rst
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/extending_ghc.rst
- docs/users_guide/exts/control.rst
- docs/users_guide/exts/ffi.rst
- docs/users_guide/exts/gadt_syntax.rst
- docs/users_guide/exts/literals.rst
- docs/users_guide/exts/pragmas.rst
- docs/users_guide/exts/qualified_do.rst
- docs/users_guide/exts/qualified_strings.rst
- docs/users_guide/exts/type_data.rst
- docs/users_guide/exts/type_families.rst
- docs/users_guide/ghc.rst
- + docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/phases.rst
- docs/users_guide/profiling.rst
- docs/users_guide/runtime_control.rst
- docs/users_guide/separate_compilation.rst
- docs/users_guide/using-warnings.rst
- ā docs/users_guide/what_glasgow_exts_does.rst
- ghc/GHC/Driver/Session/Mode.hs
- ghc/GHCi/UI.hs
- ghc/GHCi/UI/Info.hs
- ghc/GHCi/UI/Monad.hs
- ghc/Main.hs
- ghc/ghc-bin.cabal.in
- hadrian/bindist/Makefile
- hadrian/bindist/config.mk.in
- hadrian/doc/cross-compile.md
- hadrian/doc/flavours.md
- hadrian/ghci-multi-cabal.in
- hadrian/src/Base.hs
- hadrian/src/BindistConfig.hs
- hadrian/src/Builder.hs
- hadrian/src/Context.hs
- hadrian/src/Flavour.hs
- hadrian/src/Hadrian/Haskell/Cabal/Parse.hs
- hadrian/src/Hadrian/Haskell/Cabal/Type.hs
- hadrian/src/Hadrian/Haskell/Hash.hs
- hadrian/src/Hadrian/Package.hs
- hadrian/src/Main.hs
- hadrian/src/Oracles/Flag.hs
- hadrian/src/Oracles/Setting.hs
- hadrian/src/Oracles/TestSettings.hs
- hadrian/src/Packages.hs
- hadrian/src/Rules.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Documentation.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Rules/Program.hs
- hadrian/src/Rules/Selftest.hs
- hadrian/src/Rules/Test.hs
- hadrian/src/Settings.hs
- hadrian/src/Settings/Builders/Ar.hs
- hadrian/src/Settings/Builders/DeriveConstants.hs
- hadrian/src/Settings/Builders/RunTest.hs
- hadrian/src/Settings/Packages.hs
- hadrian/src/Settings/Warnings.hs
- libraries/base/base.cabal.in
- libraries/base/changelog.md
- libraries/base/src/Control/Concurrent/Chan.hs
- + libraries/base/src/Control/Concurrent/Chan/Strict.hs
- libraries/base/src/Control/Concurrent/MVar.hs
- + libraries/base/src/Control/Concurrent/MVar/Strict.hs
- libraries/base/src/Data/Foldable.hs
- libraries/base/src/Data/IORef.hs
- + libraries/base/src/Data/IORef/Strict.hs
- libraries/base/src/GHC/Base.hs
- libraries/base/src/GHC/Exts.hs
- libraries/base/src/GHC/RTS/Flags.hs
- libraries/base/tests/.gitignore
- + libraries/base/tests/IO/T27971.hs
- + libraries/base/tests/IO/T27971.stdout
- libraries/base/tests/IO/all.T
- libraries/base/tests/Memo1.lhs
- libraries/base/tests/Memo2.lhs
- + libraries/base/tests/T9809.hs
- libraries/base/tests/all.T
- libraries/containers
- libraries/ghc-boot/GHC/Serialized.hs
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingDisabled.hsc
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingEnabled.hsc
- libraries/ghc-heap/tests/parse_tso_flags.hs
- libraries/ghc-internal/CHANGELOG.md
- libraries/ghc-internal/ghc-internal.cabal.in
- libraries/ghc-internal/include/RtsIfaceSymbols.h
- libraries/ghc-internal/src/GHC/Internal/Base.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Backend/GMP.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Backend/Native.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/BigNat.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Integer.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Natural.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Primitives.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/WordArray.hs
- libraries/ghc-internal/src/GHC/Internal/Bits.hs
- + libraries/ghc-internal/src/GHC/Internal/Box.hs
- libraries/ghc-internal/src/GHC/Internal/Conc/IO.hs
- libraries/ghc-internal/src/GHC/Internal/Control/Exception/Base.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Manager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Thread.hs
- libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Windows.hsc
- libraries/ghc-internal/src/GHC/Internal/Event/Windows/FFI.hsc
- libraries/ghc-internal/src/GHC/Internal/Exts.hs
- libraries/ghc-internal/src/GHC/Internal/Heap/Closures.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Exception.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Text.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Windows.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Windows/Handle.hsc
- libraries/ghc-internal/src/GHC/Internal/RTS/Flags.hsc
- libraries/ghc-internal/src/GHC/Internal/System/Environment/ExecutablePath.hsc
- libraries/ghc-internal/src/GHC/Internal/System/IO/Error.hs
- libraries/ghc-internal/src/GHC/Internal/TypeNats.hs
- libraries/ghc-internal/src/GHC/Internal/Types.hs
- + libraries/ghc-internal/src/GHC/Internal/Unboxed/Do.hs
- libraries/ghci/GHCi/Debugger.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Run.hs
- libraries/ghci/GHCi/TH.hs
- libraries/ghci/GHCi/TH/Binary.hs
- linters/lint-codes/LintCodes/Static.hs
- m4/subst_tooldir.m4
- rts/ContinuationOps.cmm
- rts/Exception.cmm
- rts/IOManager.c
- rts/IOManager.h
- rts/IOManagerInternals.h
- rts/Interpreter.c
- rts/Interpreter.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/Prelude.h
- rts/PrimOps.cmm
- rts/ProfHeap.c
- rts/RaiseAsync.c
- rts/RtsFlags.c
- rts/RtsStartup.c
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.c
- rts/Stats.c
- rts/Stats.h
- rts/StgMiscClosures.cmm
- rts/StgStdThunks.cmm
- rts/configure.ac
- rts/include/Cmm.h
- rts/include/Rts.h
- rts/include/rts/Constants.h
- rts/include/rts/Flags.h
- + rts/include/rts/RtsSymbols.h
- rts/include/rts/RtsToHsIface.h
- rts/include/rts/storage/Closures.h
- rts/include/rts/storage/GC.h
- rts/include/stg/MiscClosures.h
- rts/include/stg/Prim.h
- rts/js/environment.js
- rts/linker/PEi386.c
- rts/linker/elf_reloc_aarch64.c
- rts/posix/Poll.c
- rts/posix/Poll.h
- + rts/posix/SelectBis.c
- + rts/posix/SelectBis.h
- rts/posix/Timeout.c
- rts/posix/Timeout.h
- rts/prim/bitrev.c
- rts/prim/bswap.c
- rts/rts.cabal
- rts/sm/Compact.c
- rts/sm/Evac.c
- rts/sm/GC.c
- rts/sm/GCThread.h
- rts/sm/NonMovingMark.c
- rts/sm/Storage.c
- testsuite/README.md
- testsuite/config/ghc
- testsuite/driver/junit.py
- testsuite/driver/my_typing.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/driver/testutil.py
- testsuite/mk/test.mk
- testsuite/tests/MiniQuickCheck.hs
- testsuite/tests/ado/ado-optimal.hs
- testsuite/tests/ado/ado001.hs
- testsuite/tests/annotations/should_run/Makefile
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.hs
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout-ws-32
- + testsuite/tests/annotations/should_run/T16841.hs
- + testsuite/tests/annotations/should_run/T16841.stdout
- testsuite/tests/annotations/should_run/all.T
- testsuite/tests/arrows/should_run/all.T
- + testsuite/tests/arrows/should_run/arrowrun005.hs
- + testsuite/tests/arrows/should_run/arrowrun005.stdout
- + testsuite/tests/backpack/should_compile/T27835.bkp
- + testsuite/tests/backpack/should_compile/T27835.stderr
- testsuite/tests/backpack/should_compile/all.T
- + testsuite/tests/bytecode/T27842.hs
- + testsuite/tests/bytecode/T27842.stdout
- + testsuite/tests/bytecode/T27842A.hs
- + testsuite/tests/bytecode/T27842N.hs
- testsuite/tests/bytecode/all.T
- + testsuite/tests/cmm/should_run/T27722.hs
- + testsuite/tests/cmm/should_run/T27722_cmm.cmm
- + testsuite/tests/cmm/should_run/T28101.hs
- + testsuite/tests/cmm/should_run/T28101.stdout
- + testsuite/tests/cmm/should_run/T28101_cmm.cmm
- testsuite/tests/cmm/should_run/all.T
- + testsuite/tests/codeGen/should_compile/T27368.hs
- + testsuite/tests/codeGen/should_compile/T27979.hs
- + testsuite/tests/codeGen/should_compile/T27979.stderr
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_gen_asm/T24813.asm
- + testsuite/tests/codeGen/should_gen_asm/T24813.cmm
- testsuite/tests/codeGen/should_gen_asm/all.T
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.hs
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.hs
- + testsuite/tests/codeGen/should_run/T27624.hs
- + testsuite/tests/codeGen/should_run/T27624.stdout
- testsuite/tests/codeGen/should_run/all.T
- testsuite/tests/concurrent/T13615/Parallel.hs
- testsuite/tests/concurrent/should_run/T21651.hs
- testsuite/tests/concurrent/should_run/T21969.hs
- + testsuite/tests/concurrent/should_run/T21969a.hs
- + testsuite/tests/concurrent/should_run/T21969a.stdout
- + testsuite/tests/concurrent/should_run/T21969b.hs
- + testsuite/tests/concurrent/should_run/T21969b.stdout
- + testsuite/tests/concurrent/should_run/T21969c.hs
- + testsuite/tests/concurrent/should_run/T21969c.stdout
- + testsuite/tests/concurrent/should_run/T21969d.hs
- + testsuite/tests/concurrent/should_run/T21969d.stdout
- + testsuite/tests/concurrent/should_run/T21969e.hs
- + testsuite/tests/concurrent/should_run/T21969e.stdout
- + testsuite/tests/concurrent/should_run/T21969f.hs
- + testsuite/tests/concurrent/should_run/T21969f.stdout
- testsuite/tests/concurrent/should_run/all.T
- + testsuite/tests/concurrent/should_run/registerFd001.hs
- + testsuite/tests/concurrent/should_run/registerFd001.stdout
- testsuite/tests/concurrent/should_run/setnumcapabilities001.hs
- testsuite/tests/corelint/T27374.hs
- testsuite/tests/count-deps/CountDepsAst.stdout
- testsuite/tests/count-deps/CountDepsParser.stdout
- testsuite/tests/cpranal/should_run/T20598a.hs
- + testsuite/tests/deSugar/should_compile/T25065a.hs
- testsuite/tests/deSugar/should_compile/all.T
- + testsuite/tests/deSugar/should_run/T20864.hs
- + testsuite/tests/deSugar/should_run/T20864.stdout
- + testsuite/tests/deSugar/should_run/T25065b.hs
- + testsuite/tests/deSugar/should_run/T25065b.stdout
- testsuite/tests/deSugar/should_run/all.T
- testsuite/tests/default/default-fail05.stderr
- testsuite/tests/dependent/should_compile/T14729.stderr
- testsuite/tests/deriving/should_compile/T13758.hs
- testsuite/tests/deriving/should_run/all.T
- + testsuite/tests/deriving/should_run/drvrun-canonical-methods.hs
- + testsuite/tests/deriving/should_run/drvrun-canonical-methods.stderr
- + testsuite/tests/deriving/should_run/drvrun-canonical-methods.stdout
- testsuite/tests/determinism/determ017/A.hs
- testsuite/tests/diagnostic-codes/codes.stdout
- testsuite/tests/dmdanal/should_compile/T9208.hs
- + testsuite/tests/dmdanal/should_run/T27845.hs
- + testsuite/tests/dmdanal/should_run/T27845.stdout
- + testsuite/tests/dmdanal/should_run/T27845_Lib.hs
- + testsuite/tests/dmdanal/should_run/T27845b.hs
- + testsuite/tests/dmdanal/should_run/T27845b.stdout
- + testsuite/tests/dmdanal/should_run/T27845b_Lib.hs
- testsuite/tests/dmdanal/should_run/all.T
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/T2464.hs
- testsuite/tests/driver/T2464.stderr
- testsuite/tests/driver/T27461/Makefile
- + testsuite/tests/driver/T27461/T27461c.stderr
- testsuite/tests/driver/T27461/all.T
- + testsuite/tests/driver/T27461/src/Wrong.hs
- + testsuite/tests/driver/T27836/A.hs
- + testsuite/tests/driver/T27836/B.hs
- + testsuite/tests/driver/T27836/C.hs
- + testsuite/tests/driver/T27836/Makefile
- + testsuite/tests/driver/T27836/T27836.stdout
- + testsuite/tests/driver/T27836/all.T
- + testsuite/tests/driver/T27836/unitA
- + testsuite/tests/driver/T27836/unitB
- + testsuite/tests/driver/T27836/unitC
- + testsuite/tests/driver/T28009.hs
- testsuite/tests/driver/all.T
- + testsuite/tests/driver/mkdepend/Makefile
- + testsuite/tests/driver/mkdepend/README.md
- + testsuite/tests/driver/mkdepend/T24384/A.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/D.hs
- + testsuite/tests/driver/mkdepend/T24384/E.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/DepInternal.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/dep-internal.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep-public/DepPublic.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-public/dep-public.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep/Dep.hs
- + testsuite/tests/driver/mkdepend/T24384/dep/dep.pkg
- + testsuite/tests/driver/mkdepend/T24384/foo.h
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/preproc.sh
- + testsuite/tests/driver/mkdepend/T24384a.stdout
- + testsuite/tests/driver/mkdepend/T24384b.stdout
- + testsuite/tests/driver/mkdepend/T24384c.stdout
- + testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/format_json.sh
- + testsuite/tests/driver/mkdepend/format_makefile.sh
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs-boot
- + testsuite/tests/driver/mkdepend/mhu01/a/A/TH.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Normal.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Splice.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/c/C.hs
- + testsuite/tests/driver/mkdepend/mhu01/unitA
- + testsuite/tests/driver/mkdepend/mhu01/unitB
- + testsuite/tests/driver/mkdepend/mhu01/unitC
- + testsuite/tests/driver/mkdepend/mhu02/A.hs
- + testsuite/tests/driver/mkdepend/mhu02/B.hs
- + testsuite/tests/driver/mkdepend/mhu02/pp.sh
- + testsuite/tests/driver/mkdepend/mhu02/unitA
- + testsuite/tests/driver/mkdepend/mhu02/unitB
- + testsuite/tests/driver/mkdepend/mhu03/pkg/A.hs
- + testsuite/tests/driver/mkdepend/mhu03/pkg/pp.sh
- + testsuite/tests/driver/mkdepend/mhu03/unitA
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend01/A.hs
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu03.dep-json
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/Makefile
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/mhu-closure.stderr
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/mhu-closure.stdout
- + testsuite/tests/driver/stringtrie.hs
- + testsuite/tests/driver/stringtrie.stdout
- + testsuite/tests/exceptions/T27851.hs
- + testsuite/tests/exceptions/T27851.stderr
- + testsuite/tests/exceptions/T27851b.hs
- + testsuite/tests/exceptions/T27851b.stderr
- + testsuite/tests/exceptions/T27851c.hs
- + testsuite/tests/exceptions/T27851c.stdout
- + testsuite/tests/exceptions/T27851d.hs
- + testsuite/tests/exceptions/T27851d.stdout
- + testsuite/tests/exceptions/T27851d.stdout-javascript-unknown-ghcjs
- testsuite/tests/exceptions/all.T
- testsuite/tests/ffi/should_run/T2594.hs
- testsuite/tests/ffi/should_run/ffi015.hs
- testsuite/tests/ffi/should_run/fptr01.hs
- testsuite/tests/ffi/should_run/fptrfail01.hs
- ā testsuite/tests/gadt/T12087.stderr
- + testsuite/tests/gadt/T12087a.hs
- testsuite/tests/gadt/T12087.hs ā testsuite/tests/gadt/T12087b.hs
- + testsuite/tests/gadt/T12087b.stderr
- + testsuite/tests/gadt/T27424a.hs
- + testsuite/tests/gadt/T27424b.hs
- + testsuite/tests/gadt/T27424b.stderr
- testsuite/tests/gadt/all.T
- testsuite/tests/generics/T27245.hs
- testsuite/tests/generics/T27245.stdout
- testsuite/tests/ghc-api/T25121_status.stdout
- + testsuite/tests/ghc-api/T4162.hs
- + testsuite/tests/ghc-api/T4162.stdout
- testsuite/tests/ghc-api/all.T
- testsuite/tests/ghc-api/downsweep/IncrementalDownsweep.hs
- testsuite/tests/ghc-api/downsweep/OldModLocation.hs
- testsuite/tests/ghc-api/downsweep/PartialDownsweep.hs
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghc-api/fixed-nodes/FixedNodes.hs
- testsuite/tests/ghc-api/fixed-nodes/InterfaceModuleGraph.hs
- testsuite/tests/ghc-api/fixed-nodes/ModuleGraphInvariants.hs
- testsuite/tests/ghc-e/should_fail/T18441fail7.stderr
- testsuite/tests/ghc-e/should_run/ghc-e005.stderr
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.hs
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.script
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.stdout
- testsuite/tests/ghci.debugger/scripts/T14628.stderr
- testsuite/tests/ghci.debugger/scripts/all.T
- + testsuite/tests/ghci.debugger/scripts/break037.hs
- + testsuite/tests/ghci.debugger/scripts/break037.script
- + testsuite/tests/ghci.debugger/scripts/break037.stdout
- testsuite/tests/ghci/linking/T25155_iserv_main.c
- testsuite/tests/ghci/prog-mhu001/prog-mhu001c.stdout
- testsuite/tests/ghci/prog-mhu002/prog-mhu002d.stdout
- + testsuite/tests/ghci/prog-mhu008/Makefile
- + testsuite/tests/ghci/prog-mhu008/a/M.hs
- + testsuite/tests/ghci/prog-mhu008/all.T
- + testsuite/tests/ghci/prog-mhu008/b/M.hs
- + testsuite/tests/ghci/prog-mhu008/prog-mhu008.script
- + testsuite/tests/ghci/prog-mhu008/prog-mhu008.stdout
- + testsuite/tests/ghci/prog-mhu008/unitA
- + testsuite/tests/ghci/prog-mhu008/unitB
- testsuite/tests/ghci/prog020/ghci.prog020a.stderr
- testsuite/tests/ghci/prog020/ghci.prog020b.stderr
- testsuite/tests/ghci/prog021/prog021a.stderr
- testsuite/tests/ghci/prog021/prog021b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022a.stderr
- testsuite/tests/ghci/prog022/ghci.prog022b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022c.stderr
- testsuite/tests/ghci/prog022/ghci.prog022d.stderr
- testsuite/tests/ghci/prog022/ghci.prog022e.stderr
- testsuite/tests/ghci/prog022/ghci.prog022f.stderr
- testsuite/tests/ghci/scripts/Defer02.stderr
- testsuite/tests/ghci/scripts/T16575.script
- testsuite/tests/ghci/scripts/T16575.stdout
- testsuite/tests/ghci/scripts/T16804.stdout
- testsuite/tests/ghci/scripts/T20150.stdout
- + testsuite/tests/ghci/scripts/T27412.hs
- + testsuite/tests/ghci/scripts/T27412.script
- + testsuite/tests/ghci/scripts/T27412.stdout
- + testsuite/tests/ghci/scripts/T27641.script
- + testsuite/tests/ghci/scripts/T27641.stderr
- + testsuite/tests/ghci/scripts/T27641.stdout
- + testsuite/tests/ghci/scripts/T27834.hs
- + testsuite/tests/ghci/scripts/T27834.script
- + testsuite/tests/ghci/scripts/T27834.stdout
- testsuite/tests/ghci/scripts/all.T
- + testsuite/tests/haddock/haddock_testsuite/IncrementalUnitId.hs
- testsuite/tests/haddock/haddock_testsuite/Makefile
- testsuite/tests/haddock/haddock_testsuite/all.T
- + testsuite/tests/haddock/haddock_testsuite/haddockIncrementalUnitId.stdout
- testsuite/tests/haddock/perf/Fold.hs
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T24221.stderr
- testsuite/tests/hiefile/should_compile/hie002.hs
- + testsuite/tests/hiefile/should_run/HasFieldQueries.hs
- + testsuite/tests/hiefile/should_run/HasFieldQueries.stdout
- + testsuite/tests/hiefile/should_run/NoFieldSelectorQueries.hs
- + testsuite/tests/hiefile/should_run/NoFieldSelectorQueries.stdout
- testsuite/tests/hiefile/should_run/RecordDotTypes.hs
- testsuite/tests/hiefile/should_run/RecordDotTypes.stdout
- testsuite/tests/hiefile/should_run/T23492.stdout
- testsuite/tests/hiefile/should_run/T24544.hs
- testsuite/tests/hiefile/should_run/all.T
- + testsuite/tests/hpc/instmeths/instmeths.hs
- + testsuite/tests/hpc/instmeths/instmeths.stdout
- + testsuite/tests/hpc/instmeths/test.T
- testsuite/tests/hpc/raytrace/Eval.hs
- + testsuite/tests/impredicative/T27917.hs
- testsuite/tests/impredicative/all.T
- + testsuite/tests/indexed-types/should_compile/T27828.hs
- + testsuite/tests/indexed-types/should_compile/T27828a.hs
- + testsuite/tests/indexed-types/should_compile/T27828b.hs
- testsuite/tests/indexed-types/should_compile/T3787.hs
- + testsuite/tests/indexed-types/should_compile/ZapDeps.hs
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/SkolemOccursLoop.hs
- testsuite/tests/indexed-types/should_fail/T1897b.stderr
- testsuite/tests/indexed-types/should_fail/T7729.hs
- testsuite/tests/indexed-types/should_fail/T7729a.hs
- testsuite/tests/indexed-types/should_fail/T9662.stderr
- + testsuite/tests/indexed-types/should_run/T27331.hs
- + testsuite/tests/indexed-types/should_run/T27331.stdout
- + testsuite/tests/indexed-types/should_run/T27331b.hs
- + testsuite/tests/indexed-types/should_run/T27331b.stdout
- + testsuite/tests/indexed-types/should_run/T27331b_Plugin.hs
- testsuite/tests/indexed-types/should_run/all.T
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-prim-exports.stdout
- testsuite/tests/interface-stability/ghc-prim-exports.stdout-mingw32
- testsuite/tests/javascript/Makefile
- + testsuite/tests/javascript/T25665.hs
- + testsuite/tests/javascript/T25665.pkg
- + testsuite/tests/javascript/T25665.stdout
- + testsuite/tests/javascript/T25665Lib.hs
- + testsuite/tests/javascript/T25665_c.c
- + testsuite/tests/javascript/T25665_js.js
- + testsuite/tests/javascript/T27788.hs
- + testsuite/tests/javascript/T27788.stdout
- testsuite/tests/javascript/all.T
- testsuite/tests/linters/all.T
- testsuite/tests/linters/notes.stdout
- testsuite/tests/llvm/should_compile/all.T
- + testsuite/tests/llvm/should_compile/split-sections-darwin.hs
- testsuite/tests/module/mod130.stderr
- testsuite/tests/module/mod133.hs
- testsuite/tests/module/mod185.stderr
- + testsuite/tests/numeric/should_run/T27545.hs
- + testsuite/tests/numeric/should_run/T27545.stdout
- testsuite/tests/numeric/should_run/all.T
- testsuite/tests/overloadedstrings/should_fail/T25926.stderr
- testsuite/tests/overloadedstrings/should_fail/T27124.stderr
- testsuite/tests/package/T4806a.stderr
- testsuite/tests/package/all.T
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/DumpTypecheckedAst.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T14189.stderr
- testsuite/tests/parser/should_compile/T15279.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20718b.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/parser/should_compile/T23315/T23315.stderr
- testsuite/tests/patsyn/should_fail/records-nofieldselectors.stderr
- testsuite/tests/perf/compiler/T13253.hs
- testsuite/tests/perf/compiler/T14683.hs
- testsuite/tests/perf/compiler/T16473.hs
- testsuite/tests/perf/compiler/T18730_A.hs
- testsuite/tests/perf/compiler/T25723.hs
- + testsuite/tests/perf/compiler/T25763.stderr
- testsuite/tests/perf/compiler/all.T
- testsuite/tests/perf/compiler/hard_hole_fits.stderr
- testsuite/tests/perf/compiler/large-project/all.T
- + testsuite/tests/perf/compiler/large-project/large-project-mhu.sh
- + testsuite/tests/perf/should_run/T27231.hs
- + testsuite/tests/perf/should_run/T27231.stdout
- testsuite/tests/perf/should_run/T7257.hs
- testsuite/tests/perf/should_run/T7257.stdout
- testsuite/tests/perf/should_run/all.T
- + testsuite/tests/plugins/T26761.hs
- + testsuite/tests/plugins/T26761.stderr
- + testsuite/tests/plugins/T26761Plugin.hs
- + testsuite/tests/plugins/T26761a.hs
- testsuite/tests/plugins/all.T
- testsuite/tests/plugins/defaulting-plugin/DefaultLifted.hs
- testsuite/tests/pmcheck/should_compile/T11276.hs
- + testsuite/tests/pmcheck/should_compile/T27323.hs
- + testsuite/tests/pmcheck/should_compile/T27323b.hs
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- + testsuite/tests/primops/should_run/ResizeByteArrayPinnedness.hs
- + testsuite/tests/primops/should_run/ResizeByteArrayPinnedness.stdout
- + testsuite/tests/primops/should_run/T27299.hs
- + testsuite/tests/primops/should_run/T27299.stdout
- testsuite/tests/primops/should_run/all.T
- testsuite/tests/printer/AnnotationNoListTuplePuns.stdout
- testsuite/tests/printer/Makefile
- testsuite/tests/printer/T17697.stderr
- testsuite/tests/printer/T18791.stderr
- + testsuite/tests/printer/T27424c.hs
- testsuite/tests/printer/Test20297.hs
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/printer/all.T
- testsuite/tests/profiling/should_compile/T19894/StreamK.hs
- testsuite/tests/profiling/should_run/T3001-2.hs
- testsuite/tests/profiling/should_run/T7275.stdout
- testsuite/tests/profiling/should_run/caller-cc/CallerCcParser.hs
- testsuite/tests/programs/galois_raytrace/Eval.hs
- testsuite/tests/qualifieddo/should_compile/all.T
- + testsuite/tests/qualifieddo/should_compile/qdocompile003.hs
- + testsuite/tests/qualifieddo/should_compile/qdocompile003.stderr
- testsuite/tests/qualifieddo/should_fail/all.T
- + testsuite/tests/qualifieddo/should_fail/qdofail006.hs
- + testsuite/tests/qualifieddo/should_fail/qdofail006.stderr
- testsuite/tests/qualifieddo/should_run/all.T
- + testsuite/tests/qualifieddo/should_run/qdorun008.hs
- + testsuite/tests/qualifieddo/should_run/qdorun008.stdout
- testsuite/tests/rebindable/rebindable2.hs
- + testsuite/tests/rename/should_fail/Noncanonical.hs
- + testsuite/tests/rename/should_fail/Noncanonical.stderr
- testsuite/tests/rename/should_fail/T15607.stderr
- testsuite/tests/rename/should_fail/T19843b.stderr
- testsuite/tests/rename/should_fail/all.T
- testsuite/tests/rename/should_fail/rnfail026.hs
- testsuite/tests/rep-poly/RepPolyRule3.stderr
- testsuite/tests/rts/Makefile
- testsuite/tests/rts/T17088.hs
- + testsuite/tests/rts/T23160.hs
- + testsuite/tests/rts/T23160.stdout
- + testsuite/tests/rts/T24450.hs
- + testsuite/tests/rts/T24450.stderr
- + testsuite/tests/rts/T26169.hs
- + testsuite/tests/rts/T27272.hs
- + testsuite/tests/rts/T27272_gen.py
- + testsuite/tests/rts/T27376.hs
- + testsuite/tests/rts/T27376.stdout
- + testsuite/tests/rts/T27526.hs
- + testsuite/tests/rts/T27526.stdout
- + testsuite/tests/rts/T27618.hs
- + testsuite/tests/rts/T27618.stdout
- + testsuite/tests/rts/T27649.hs
- + testsuite/tests/rts/T27649.stdout
- + testsuite/tests/rts/T28012.hs
- + testsuite/tests/rts/T28012.stdout
- testsuite/tests/rts/all.T
- + testsuite/tests/rts/census_pinned.hs
- + testsuite/tests/rts/census_pinned.stdout-ws-32
- + testsuite/tests/rts/census_pinned.stdout-ws-64
- + testsuite/tests/rts/census_pinned.stdout-ws-64-mingw32
- + testsuite/tests/rts/continuations/T27651.hs
- + testsuite/tests/rts/continuations/T27651.stdout
- testsuite/tests/rts/continuations/all.T
- testsuite/tests/rts/ipe/IpeStats/Fold.hs
- testsuite/tests/rts/linker/Makefile
- + testsuite/tests/rts/linker/T27807.s
- + testsuite/tests/rts/linker/T27807.stdout
- testsuite/tests/rts/linker/all.T
- testsuite/tests/rts/pause-resume/all.T
- testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs
- testsuite/tests/rts/rtsflags001.stderr-ws-32
- testsuite/tests/rts/rtsflags001.stderr-ws-64
- + testsuite/tests/rts/symbols/Main.hs
- + testsuite/tests/rts/symbols/Makefile
- + testsuite/tests/rts/symbols/all.T
- + testsuite/tests/rts/symbols/dumpDeclaredSymbols.c
- + testsuite/tests/rts/symbols/rts-check-symbols.sh
- + testsuite/tests/rts/symbols/rts-check-symbols.stdout
- testsuite/tests/safeHaskell/ghci/p4.stderr
- testsuite/tests/safeHaskell/ghci/p6.stderr
- testsuite/tests/simplCore/should_compile/Makefile
- testsuite/tests/simplCore/should_compile/T14908_Deps.hs
- testsuite/tests/simplCore/should_compile/T22375.stderr
- testsuite/tests/simplCore/should_compile/T22375DataFamily.stderr
- testsuite/tests/simplCore/should_compile/T22611.hs
- testsuite/tests/simplCore/should_compile/T22611.stderr
- + testsuite/tests/simplCore/should_compile/T22611a.hs
- testsuite/tests/simplCore/should_compile/T26051.stderr
- + testsuite/tests/simplCore/should_compile/T27629.hs
- + testsuite/tests/simplCore/should_compile/T27629.stderr
- + testsuite/tests/simplCore/should_compile/T27629Plugin.hs
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T27910.hs
- + testsuite/tests/simplCore/should_compile/T27910.stderr
- + testsuite/tests/simplCore/should_compile/T27936.hs
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- + testsuite/tests/simplCore/should_compile/T7803.hs
- + testsuite/tests/simplCore/should_compile/T7803.stderr
- + testsuite/tests/simplCore/should_compile/T7803a.hs
- testsuite/tests/simplCore/should_compile/all.T
- testsuite/tests/simplCore/should_compile/simpl017.hs
- testsuite/tests/simplStg/should_compile/all.T
- + testsuite/tests/simplStg/should_compile/inferTags005.hs
- + testsuite/tests/simplStg/should_compile/inferTags005.stderr
- + testsuite/tests/simplStg/should_compile/inferTags006.hs
- + testsuite/tests/simplStg/should_compile/inferTags006.stderr
- + testsuite/tests/simplStg/should_run/InferTags007_A.hs
- + testsuite/tests/simplStg/should_run/T27831.hs
- + testsuite/tests/simplStg/should_run/T27831.stdout
- + testsuite/tests/simplStg/should_run/T27857.hs
- + testsuite/tests/simplStg/should_run/T27857.stdout
- testsuite/tests/simplStg/should_run/all.T
- + testsuite/tests/simplStg/should_run/inferTags007.hs
- + testsuite/tests/simplStg/should_run/inferTags007.stdout
- testsuite/tests/splice-imports/SI35.hs
- testsuite/tests/th/GadtConSigs_th_dump1.hs
- testsuite/tests/th/GadtConSigs_th_dump1.stderr
- + testsuite/tests/th/T27424d.hs
- + testsuite/tests/th/T27424d.stderr
- testsuite/tests/th/all.T
- + testsuite/tests/type-data/should_fail/T27732a.hs
- + testsuite/tests/type-data/should_fail/T27732a.stderr
- + testsuite/tests/type-data/should_fail/T27732b.hs
- + testsuite/tests/type-data/should_fail/T27732b.stderr
- + testsuite/tests/type-data/should_fail/T27732c.hs
- + testsuite/tests/type-data/should_fail/T27732c.stderr
- + testsuite/tests/type-data/should_fail/T27732d.hs
- + testsuite/tests/type-data/should_fail/T27732d.stderr
- + testsuite/tests/type-data/should_fail/T27732e.hs
- + testsuite/tests/type-data/should_fail/T27732e.stderr
- + testsuite/tests/type-data/should_fail/T27732f.hs
- + testsuite/tests/type-data/should_fail/T27732f.stderr
- testsuite/tests/type-data/should_fail/TDStrictnessGADT.stderr
- testsuite/tests/type-data/should_fail/TDStrictnessH98.stderr
- testsuite/tests/type-data/should_fail/all.T
- testsuite/tests/typecheck/should_compile/DeepSubsumption02.hs
- testsuite/tests/typecheck/should_compile/LocalGivenEqs.hs
- testsuite/tests/typecheck/should_compile/T11254.stderr
- testsuite/tests/typecheck/should_compile/T15370.stderr
- + testsuite/tests/typecheck/should_compile/T26543_orig.hs
- + testsuite/tests/typecheck/should_compile/T27916.hs
- + testsuite/tests/typecheck/should_compile/T27994.hs
- + testsuite/tests/typecheck/should_compile/T27994a.hs
- + testsuite/tests/typecheck/should_compile/T27994b.hs
- testsuite/tests/typecheck/should_compile/T4524.hs
- testsuite/tests/typecheck/should_compile/T4969.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_compile/valid_hole_fits.stderr
- testsuite/tests/typecheck/should_fail/ClassOperator.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion2.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion3.stderr
- testsuite/tests/typecheck/should_fail/FunDepOrigin1b.hs
- testsuite/tests/typecheck/should_fail/T12785b.stderr
- testsuite/tests/typecheck/should_fail/T18851.stderr
- + testsuite/tests/typecheck/should_fail/T18851e.hs
- + testsuite/tests/typecheck/should_fail/T18851e.stderr
- + testsuite/tests/typecheck/should_fail/T18851f.hs
- + testsuite/tests/typecheck/should_fail/T18851f.stderr
- testsuite/tests/typecheck/should_fail/T22707.hs
- testsuite/tests/typecheck/should_fail/T22940.stderr
- testsuite/tests/typecheck/should_fail/T25950.stderr
- + testsuite/tests/typecheck/should_fail/T26543a.hs
- + testsuite/tests/typecheck/should_fail/T26543a.stderr
- testsuite/tests/typecheck/should_fail/T26823.stderr
- + testsuite/tests/typecheck/should_fail/T27731.hs
- + testsuite/tests/typecheck/should_fail/T27731.stderr
- + testsuite/tests/typecheck/should_fail/T27844.hs
- + testsuite/tests/typecheck/should_fail/T27844.stderr
- testsuite/tests/typecheck/should_fail/T5691.stderr
- testsuite/tests/typecheck/should_fail/T7019.hs
- testsuite/tests/typecheck/should_fail/T7437.stderr
- testsuite/tests/typecheck/should_fail/T8450.stderr
- testsuite/tests/typecheck/should_fail/T8603.hs
- testsuite/tests/typecheck/should_fail/all.T
- testsuite/tests/typecheck/should_fail/mc24.stderr
- testsuite/tests/typecheck/should_fail/tcfail019.stderr
- testsuite/tests/typecheck/should_fail/tcfail189.stderr
- + testsuite/tests/unsatisfiable/T28081.hs
- testsuite/tests/unsatisfiable/all.T
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
- testsuite/tests/warnings/should_compile/Overflow.stderr-ws-32
- testsuite/tests/warnings/should_compile/Overflow.stderr-ws-64
- + testsuite/tests/warnings/should_compile/RedundantCanonicalMethods.hs
- + testsuite/tests/warnings/should_compile/RedundantCanonicalMethods.stderr
- testsuite/tests/warnings/should_compile/T13256.stderr-ws-32
- testsuite/tests/warnings/should_compile/T13256.stderr-ws-64
- testsuite/tests/warnings/should_compile/WarnNoncanonical.hs
- testsuite/tests/warnings/should_compile/WarnNoncanonical.stderr
- testsuite/tests/warnings/should_compile/all.T
- + testsuite/tests/warnings/should_fail/WExpectedNoArgError.stderr
- testsuite/tests/warnings/should_fail/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Parsers.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
- utils/check-ppr/Main.hs
- utils/count-deps/Main.hs
- utils/dump-decls/Main.hs
- utils/haddock/CHANGES.md
- utils/haddock/doc/markup.rst
- utils/haddock/haddock-api/haddock-api.cabal
- utils/haddock/haddock-api/src/Haddock.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Parser.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Renderer.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Utils.hs
- utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/GhcUtils.hs
- utils/haddock/haddock-api/src/Haddock/Interface.hs
- utils/haddock/haddock-api/src/Haddock/Interface/ParseModuleHeader.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-api/src/Haddock/Types.hs
- utils/haddock/haddock-api/src/Haddock/Utils/Json.hs
- utils/haddock/haddock-api/test/Haddock/Backends/Hyperlinker/ParserSpec.hs
- utils/haddock/haddock-library/CHANGES.md
- utils/haddock/haddock-library/fixtures/Fixtures.hs
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.parsed
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.parsed
- utils/haddock/haddock-library/haddock-library.cabal
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser.hs
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser/Identifier.hs
- utils/haddock/haddock-library/test/Documentation/Haddock/ParserSpec.hs
- utils/haddock/haddock.cabal
- utils/jsffi/dyld.mjs
- utils/runghc/Main.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/047ccb4531b170eeb2ea6c26204a8dā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/047ccb4531b170eeb2ea6c26204a8dā¦
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/has-field-hie] Deleted 1 commit: Typeable test
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
20 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/has-field-hie at Glasgow Haskell Compiler / GHC
WARNING: The push did not contain any new commits, but force pushed to delete the commits and changes below.
Deleted commits:
6a08787c by fendor at 2026-09-17T11:55:40+02:00
Typeable test
- - - - -
4 changed files:
- compiler/GHC/Iface/Ext/Types.hs
- + testsuite/tests/hiefile/should_run/HieTypeable.hs
- + testsuite/tests/hiefile/should_run/HieTypeable.stdout
- testsuite/tests/hiefile/should_run/all.T
Changes:
=====================================
compiler/GHC/Iface/Ext/Types.hs
=====================================
@@ -616,17 +616,23 @@ data EvBindDep
-- ^ 'Name' of the record selector
Name
-- ^ 'Name' of the parent type.
+ | TypeableEvidence
+ -- ^ Evidence of a @Typeable@ constraint.
+ Name
+ -- ^ Name of the type the evidence was generated for.
deriving (Eq, Ord)
instance Outputable EvBindDep where
ppr = \ case
EvidenceVar n -> ppr n
RecordField sel parent -> ppr sel <+> text "of Record" <+> ppr parent
+ TypeableEvidence n -> ppr n <+> text "bound by Typeable"
evBindDepName :: EvBindDep -> Name
evBindDepName = \ case
EvidenceVar n -> n
RecordField selector _record -> selector
+ TypeableEvidence n -> n
evBindDepHieName :: EvBindDep -> HieName
evBindDepHieName = toHieName . evBindDepName
@@ -640,11 +646,15 @@ instance Binary EvBindDep where
putByte bh 1
put_ bh n
put_ bh sel
+ TypeableEvidence n -> do
+ putByte bh 2
+ put_ bh n
get bh =
getByte bh >>= \ case
0 -> EvidenceVar <$> get bh
1 -> RecordField <$> get bh <*> get bh
+ 2 -> TypeableEvidence <$> get bh
t -> fail $ "EvBindDep: Unknown tag: " ++ show t
-- | Eq/Ord instances compare on the converted HieName,
=====================================
testsuite/tests/hiefile/should_run/HieTypeable.hs
=====================================
@@ -0,0 +1,28 @@
+module Main where
+
+import Data.Dynamic
+import Data.Typeable
+import TestUtils
+
+data Thing = Thing {field1 :: Char, field2 :: Bool}
+ deriving (Show, Eq)
+
+castFromDynamic :: Dynamic -> Maybe Thing
+castFromDynamic d = fromDynamic d
+ -- ^ this is the point
+
+rep :: Thing -> TypeRep
+rep d = typeOf d
+ -- ^ this is the point
+
+points =
+ [ (11,21)
+ , (15,10)
+ ]
+
+main = do
+ (df, hf) <- readTestHie "HieTypeable.hie"
+ let refmap = generateReferencesMap $ getAsts $ hie_asts hf
+
+ traverse (explainEv df hf refmap) points
+ return ()
=====================================
testsuite/tests/hiefile/should_run/HieTypeable.stdout
=====================================
@@ -0,0 +1,30 @@
+==========================
+At point (11,21), we found:
+==========================
+ā
+ā $dTypeable at HieTypeable.hs:1:1, of type: Typeable Thing
+ā is an evidence variable bound by a let, depending on: [$dTypeable]
+ā with scope: ModuleScope
+ā
+ā Defined at <no location info>
+ā
+|
+`- ā
+ ā $dTypeable at HieTypeable.hs:1:1, of type: Typeable Thing
+ ā is an evidence variable bound by a let, depending on: []
+ ā with scope: ModuleScope
+ ā
+ ā Defined at <no location info>
+ ā
+
+==========================
+At point (15,10), we found:
+==========================
+ā
+ā $dTypeable at HieTypeable.hs:1:1, of type: Typeable Thing
+ā is an evidence variable bound by a let, depending on: []
+ā with scope: ModuleScope
+ā
+ā Defined at <no location info>
+ā
+
=====================================
testsuite/tests/hiefile/should_run/all.T
=====================================
@@ -12,3 +12,4 @@ test('HieGadtConSigs', [extra_run_opts('"' + config.libdir + '"'), extra_files([
test('T25709', [extra_run_opts('"' + config.libdir + '"'), extra_files(['TestUtils.hs'])], compile_and_run, ['-package ghc -fwrite-ide-info'])
test('HasFieldQueries', [extra_run_opts('"' + config.libdir + '"'), extra_files(['TestUtils.hs'])], compile_and_run, ['-package ghc -fwrite-ide-info'])
test('NoFieldSelectorQueries', [extra_run_opts('"' + config.libdir + '"'), extra_files(['TestUtils.hs'])], compile_and_run, ['-package ghc -fwrite-ide-info'])
+test('HieTypeable', [extra_run_opts('"' + config.libdir + '"'), extra_files(['TestUtils.hs'])], compile_and_run, ['-package ghc -fwrite-ide-info'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/6a08787cb2b231e77018dbf962e37e7ā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/6a08787cb2b231e77018dbf962e37e7ā¦
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc] Pushed new branch wip/fendor/has-field-hie-typeable
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
20 Nov '26
Hannes Siebenhandl pushed new branch wip/fendor/has-field-hie-typeable at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/fendor/has-field-hie-typeable
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: Make Haddock avoid the PIT
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
by Hannes Siebenhandl (ļ¼ fendor) 20 Nov '26
20 Nov '26
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC
Commits:
c18b3e6f by Wolfgang Jeltsch at 2026-11-20T16:06:07+01:00
Make Haddock avoid the PIT
To this end, Haddock has been using `loadSysInterface` to fetch module
interfaces. The `loadSysInterface` operation is very complex, containing
many bits that do not seem to be needed by Haddock. In particular,
storing interface data in and potentially retrieving it from the PIT
seems to be superfluous. This interaction with the PIT limits how much
we can statically shrink the amount of information that is stored in the
PIT. Therefore, we drop the use of `loadSysInterface` and implement the
necessary bits of interface fetching directly in `loadHiFile`, where
`loadSysInterface` used to be invoked.
- - - - -
56cd7264 by Hannes Siebenhandl at 2026-11-20T16:06:07+01:00
WIP: one-shot uses home loader state
- - - - -
21 changed files:
- compiler/GHC/Core/Opt/Monad.hs
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Core/Opt/Simplify.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Rules.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Linker/Deps.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Utils/Env.hs
- compiler/GHC/Tc/Utils/Instantiate.hs
- compiler/GHC/Tc/Utils/Monad.hs
- compiler/GHC/Unit/External.hs
- compiler/GHC/Unit/Home/PackageTable.hs
- compiler/GHC/Unit/Module/Env.hs
- utils/haddock/haddock-api/src/Haddock/Interface.hs
Changes:
=====================================
compiler/GHC/Core/Opt/Monad.hs
=====================================
@@ -16,8 +16,8 @@ module GHC.Core.Opt.Monad (
-- ** Reading from the monad
getModule,
- initRuleEnv, getExternalRuleBase,
- getDynFlags, getPackageFamInstEnv,
+ initRuleEnv, getExternalRuleBase, getLazyHomeRuleBase,
+ getDynFlags, getPackageFamInstEnv, getLazyHomeFamInstEnv,
getInteractiveContext,
getUniqTag,
getNamePprCtx, getSrcSpanM,
@@ -44,7 +44,7 @@ import GHC.Driver.Errors ( reportDiagnostic, reportError )
import GHC.Driver.Config.Diagnostic ( initDiagOpts )
import GHC.Driver.Env
-import GHC.Core.Rules ( RuleBase, RuleEnv, mkRuleEnv )
+import GHC.Core.Rules ( RuleBase, RuleEnv, mkRuleEnv, unionRuleBase )
import GHC.Core.Opt.Stats ( SimplCount, zeroSimplCount, plusSimplCount )
import GHC.Types.Annotations
@@ -73,6 +73,9 @@ import Data.Dynamic
import Data.Maybe (listToMaybe)
import Control.Monad
import Control.Applicative ( Alternative(..) )
+import GHC.Unit.Home.PackageTable (HomePackageTable)
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import GHC.Core.FamInstEnv
data FloatOutSwitches = FloatOutSwitches
{ floatOutLambdas :: Maybe Int -- ^ Just n <=> float lambdas to top level, if
@@ -248,7 +251,10 @@ instance HasHscEnv CoreM where
getHscEnv = read cr_hsc_env
getHomeRuleBase :: CoreM RuleBase
-getHomeRuleBase = read cr_rule_base
+getHomeRuleBase = do
+ hptRules <- read cr_rule_base
+ extraRules <- getLazyHomeRuleBase
+ pure $ hptRules `unionRuleBase` extraRules
initRuleEnv :: ModGuts -> CoreM RuleEnv
initRuleEnv guts
@@ -259,6 +265,9 @@ initRuleEnv guts
getExternalRuleBase :: CoreM RuleBase
getExternalRuleBase = eps_rule_base <$> get_eps
+getLazyHomeRuleBase :: CoreM RuleBase
+getLazyHomeRuleBase = get_hpt HomePackageTable.hptLoadedRuleBase
+
getNamePprCtx :: CoreM NamePprCtx
getNamePprCtx = read cr_name_ppr_ctx
@@ -302,11 +311,20 @@ getInteractiveContext = hsc_IC <$> getHscEnv
getPackageFamInstEnv :: CoreM PackageFamInstEnv
getPackageFamInstEnv = eps_fam_inst_env <$> get_eps
+getLazyHomeFamInstEnv :: CoreM FamInstEnv
+getLazyHomeFamInstEnv = get_hpt HomePackageTable.hptLoadedFamInstEnv
+
get_eps :: CoreM ExternalPackageState
get_eps = do
hsc_env <- getHscEnv
liftIO $ hscEPS hsc_env
+get_hpt :: (HomePackageTable -> IO a) -> CoreM a
+get_hpt f = do
+ hsc_env <- getHscEnv
+ a <- liftIO $ f $ hsc_HPT hsc_env
+ pure a
+
{-
************************************************************************
* *
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -449,8 +449,9 @@ doCorePass pass guts = do
dflags <- getDynFlags
us <- getUniqueSupplyM
p_fam_env <- getPackageFamInstEnv
+ l_fam_env <- getLazyHomeFamInstEnv
let platform = targetPlatform dflags
- let fam_envs = (p_fam_env, mg_fam_inst_env guts)
+ let fam_envs = (p_fam_env `unionFamInstEnv` l_fam_env, mg_fam_inst_env guts)
let updateBinds f = return $ guts { mg_binds = f (mg_binds guts) }
let updateBindsM f = f (mg_binds guts) >>= \b' -> return $ guts { mg_binds = b' }
let updateBindsAndRulesM f = f (mg_binds guts) (mg_rules guts) >>= \(b',r') -> return $ guts { mg_binds = b', mg_rules = r' }
=====================================
compiler/GHC/Core/Opt/Simplify.hs
=====================================
@@ -30,7 +30,7 @@ import GHC.Utils.Logger as Logger
import GHC.Utils.Outputable
import GHC.Utils.Constants (debugIsOn)
-import GHC.Unit.Env ( UnitEnv, ueEPS )
+import GHC.Unit.Env ( UnitEnv, ueEPS, ue_hpt )
import GHC.Unit.External
import GHC.Unit.Module.ModGuts
@@ -44,6 +44,7 @@ import GHC.Types.Unique.FM
import Control.Monad
import Data.Foldable ( for_ )
+import GHC.Unit.Home.PackageTable (hptLoadedRuleBase, HomePackageTable)
{-
************************************************************************
@@ -63,13 +64,14 @@ data SimplifyExprOpts = SimplifyExprOpts
simplifyExpr :: Logger
-> ExternalUnitCache
+ -> HomePackageTable
-> SimplifyExprOpts
-> CoreExpr
-> IO CoreExpr
-- ^ Simplify an expression using 'simplExprGently'.
--
-- See 'simplExprGently' for details.
-simplifyExpr logger euc opts expr
+simplifyExpr logger euc hpt opts expr
= withTiming logger (text "Simplify [expr]") (const ()) $
do { eps <- eucEPS euc ;
; let fam_envs = ( eps_fam_inst_env eps
@@ -81,7 +83,8 @@ simplifyExpr logger euc opts expr
base_env = mkSimplEnv (se_mode opts) fam_envs
top_env_cfg = se_top_env_cfg opts
read_eps_rules = eps_rule_base <$> eucEPS euc
- read_ruleenv = updExternalPackageRules emptyRuleEnv <$> read_eps_rules
+ read_home_rules = hptLoadedRuleBase hpt
+ read_ruleenv = (\ home_rules eps_rules -> updExternalPackageRules (updHomePackageRules emptyRuleEnv home_rules) eps_rules) <$> read_home_rules <*> read_eps_rules
; let sz = exprSize expr
@@ -285,8 +288,11 @@ simplifyPgm logger unit_env name_ppr_ctx opts
; read_eps_rules :: IO PackageRuleBase
; read_eps_rules = eps_rule_base <$> ueEPS unit_env
+ ; read_home_rules :: IO RuleBase
+ ; read_home_rules = hptLoadedRuleBase (ue_hpt unit_env)
+
; read_rule_env :: IO RuleEnv
- ; read_rule_env = updExternalPackageRules base_rule_env <$> read_eps_rules
+ ; read_rule_env = (\ home_rules eps_rules -> updExternalPackageRules (updHomePackageRules base_rule_env home_rules) eps_rules) <$> read_home_rules <*> read_eps_rules
; fam_envs = (eps_fam_inst_env eps, fam_inst_env)
; simpl_env = mkSimplEnv mode fam_envs } ;
=====================================
compiler/GHC/Core/Opt/Specialise.hs
=====================================
@@ -854,7 +854,8 @@ spec_import env callers dict_binds cis@(CIS fn _)
-- We keep doing this in case we "page-fault in"
-- more rules as we go along
; eps_rules <- getExternalRuleBase
- ; let rule_env = se_rules env `updExternalPackageRules` eps_rules
+ ; home_rules <- getLazyHomeRuleBase
+ ; let rule_env = se_rules env `updHomePackageRules` home_rules `updExternalPackageRules` eps_rules
-- ; debugTraceMsg (text "specImport1" <+> vcat
-- [ text "function:" <+> ppr fn
=====================================
compiler/GHC/Core/Rules.hs
=====================================
@@ -13,8 +13,9 @@ module GHC.Core.Rules (
-- ** RuleBase, RuleEnv
RuleBase, RuleEnv(..), mkRuleEnv, emptyRuleEnv,
- updExternalPackageRules, addLocalRules, updLocalRules,
- emptyRuleBase, mkRuleBase, extendRuleBaseList,
+ updExternalPackageRules, updHomePackageRules,
+ addLocalRules, updLocalRules,
+ emptyRuleBase, mkRuleBase, extendRuleBaseList, unionRuleBase,
pprRuleBase,
-- ** Checking rule applications
@@ -398,6 +399,10 @@ extendRuleBase rule_base rule
lookupRuleBase :: RuleBase -> Unique -> Maybe [CoreRule]
lookupRuleBase = lookupUFM
+unionRuleBase :: RuleBase -> RuleBase -> RuleBase
+unionRuleBase
+ = plusUFM
+
pprRuleBase :: RuleBase -> SDoc
pprRuleBase rules = pprUFM rules $ \rss ->
vcat [ pprRules (tidyRules emptyTidyEnv rs)
@@ -433,6 +438,10 @@ updExternalPackageRules :: RuleEnv -> RuleBase -> RuleEnv
updExternalPackageRules rule_env eps_rules
= rule_env { re_eps_rules = eps_rules }
+updHomePackageRules :: RuleEnv -> RuleBase -> RuleEnv
+updHomePackageRules rule_env eps_rules
+ = rule_env { re_home_rules = (re_home_rules rule_env ) `unionRuleBase` eps_rules }
+
updLocalRules :: RuleEnv -> [CoreRule] -> RuleEnv
-- Completely over-ride the local rules in RuleEnv
updLocalRules rule_env local_rules
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -98,6 +98,7 @@ import GHC.Builtin.Modules( gHC_PRIM )
import Data.IORef
import qualified Data.Set as Set
import GHC.Types.Name.Reader (ExactRdrName(..))
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env hsc = do
@@ -348,10 +349,11 @@ prepareAnnotations hsc_env mb_guts = do
home_pkg_anns <- fromMaybe (hugAllAnns (hsc_unit_env hsc_env))
$ uncurry (hugAnnsBelow hsc_env)
. get_mod <$> mb_guts
+ more_home_pkg_anns <- HomePackageTable.hptLoadedAnnEnv $ hsc_HPT hsc_env
let
other_pkg_anns = eps_ann_env eps
!ann_env = maybe id plusAnnEnv mb_this_module_anns $!
- plusAnnEnv home_pkg_anns other_pkg_anns
+ plusAnnEnv home_pkg_anns (plusAnnEnv more_home_pkg_anns other_pkg_anns)
return ann_env
-- | Find the 'TyThing' for the given 'Name' by using all the resources
@@ -374,12 +376,9 @@ lookupTypeInPTE hsc_env pte name = ty
then mkHomeModule (hsc_home_unit hsc_env) (moduleName (nameModule name))
else nameModule name
- ty = if isOneShot (ghcMode (hsc_dflags hsc_env))
- -- in one-shot, we don't use the HPT
- then return $! lookupNameEnv pte name
- else HUG.lookupHugByModule mod hpt >>= \case
- Just hm -> pure $! lookupNameEnv (md_types (hm_details hm)) name
- Nothing -> pure $! lookupNameEnv pte name
+ ty = HUG.lookupHugByModule mod hpt >>= \case
+ Just hm -> pure $! lookupNameEnv (md_types (hm_details hm)) name
+ Nothing -> pure $! lookupNameEnv pte name
-- | Find the 'ModIface' for a 'Module', searching in both the loaded home
-- and external package module information
=====================================
compiler/GHC/Driver/Main/Passes.hs
=====================================
@@ -1546,7 +1546,7 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do
let unit_env = hsc_unit_env hsc_env
let simplify_expr_opts = initSimplifyExprOpts dflags ic
- simpl_expr <- simplifyExpr logger (ue_eps unit_env) simplify_expr_opts ds_expr
+ simpl_expr <- simplifyExpr logger (ue_eps unit_env) (ue_hpt unit_env) simplify_expr_opts ds_expr
-- Create a unique temporary binding
--
=====================================
compiler/GHC/HsToCore/Monad.hs
=====================================
@@ -131,6 +131,7 @@ import GHC.Data.OrdList
import Data.IORef
import GHC.IO.Unsafe (unsafeInterleaveIO)
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{-
************************************************************************
@@ -385,6 +386,7 @@ mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
-- ToDo: what becomes of the values put into these ref-cells?
; eps <- liftIO $ hscEPS hsc_env
+ ; extra_matches <- liftIO $ HomePackageTable.hptLoadedCompleteMatches $ hsc_HPT hsc_env
; let unit_env = hsc_unit_env hsc_env
this_mod = tcg_mod tcg_env
type_env = tcg_type_env tcg_env
@@ -406,7 +408,7 @@ mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
-- Relevant test case: MultiLayerModulesTH_Make, which regresses
-- in allocations by ~5% if we don't do this.
traverse (lookupCompleteMatch type_env hsc_env) =<<
- localAndImportedCompleteMatches tcg_comp_env eps
+ localAndImportedCompleteMatches (tcg_comp_env ++ extra_matches) eps
; tcm_plugins <- liftIO $ readIORef (tcg_plugins tcg_env)
-- Pass the running 'TcM' plugins to the desugarer, so that the pattern-match
@@ -469,6 +471,7 @@ initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds
; statics_var <- newIORef nilOL
; known_key_maps_var <- newIORef Nothing
; eps <- liftIO $ hscEPS hsc_env
+ ; extra_matches <- liftIO $ HomePackageTable.hptLoadedCompleteMatches $ hsc_HPT hsc_env
; let unit_env = hsc_unit_env hsc_env
type_env = typeEnvFromEntities ids tycons patsyns fam_insts
ptc = initPromotionTickContext (hsc_dflags hsc_env)
@@ -476,7 +479,7 @@ initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds
bindsToIds (Rec binds) = map fst binds
ids = concatMap bindsToIds binds
; ds_complete_matches <- traverse (lookupCompleteMatch type_env hsc_env) =<<
- localAndImportedCompleteMatches local_complete_matches eps
+ localAndImportedCompleteMatches (local_complete_matches ++ extra_matches) eps
; let
tcm_plugins = emptyTcMPluginsRun
envs = mkDsEnvs unit_env this_mod rdr_env type_env
@@ -842,8 +845,8 @@ dsGetFamInstEnvs :: DsM FamInstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
dsGetFamInstEnvs
- = do { eps <- getEps; env <- getGblEnv
- ; return (eps_fam_inst_env eps, ds_fam_inst_env env) }
+ = do { eps <- getEps; env <- getGblEnv; lazy_env <- queryHpt HomePackageTable.hptLoadedFamInstEnv
+ ; return (eps_fam_inst_env eps, ds_fam_inst_env env `unionFamInstEnv` lazy_env) }
dsGetMetaEnv :: DsM (NameEnv DsMetaVal)
dsGetMetaEnv = do { env <- getLclEnv; return (dsl_meta env) }
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -152,6 +152,13 @@ import Data.Function ((&))
import Data.Map ( toList )
import System.FilePath
import System.Directory
+import GHC.Types.DefaultEnv (DefaultEnv)
+import GHC.Core (CoreRule)
+import GHC.Unit.Module.ModDetails (ModDetails(..))
+import GHC.Unit.Home.ModInfo (HomeModInfo(..), emptyHomeModInfoLinkable)
+import qualified Data.Set as Set
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import Control.Applicative ((<|>))
{- *********************************************************************
@@ -513,8 +520,9 @@ importDecl name
; Succeeded _ -> do
-- Now look it up again; this time we should find it
- { eps <- getEps
- ; case lookupTypeEnv (eps_PTE eps) name of
+ { eps <- getEps -- @fendor: DONE
+ ; loaderTypeEnv <- queryHpt HomePackageTable.hptLoadedTypeEnv
+ ; case lookupTypeEnv loaderTypeEnv name <|> lookupTypeEnv (eps_PTE eps) name of
Just thing -> return $ Succeeded thing
Nothing -> return $ Failed $
Can'tFindNameInInterface name
@@ -789,7 +797,9 @@ loadInterface doc_str mod from
_ -> do {
-- READ THE MODULE IN
- ; read_result <- case wantHiBootFile mhome_unit eps mod from of
+ ; hpt <- getHpt
+ ; hls <- liftIO (hptLoaderState hpt)
+ ; read_result <- case wantHiBootFile mhome_unit hls mod from of
Failed err -> return (Failed err)
Succeeded hi_boot_file -> do
hsc_env <- getTopEnv
@@ -818,108 +828,37 @@ loadInterface doc_str mod from
let
loc_doc = text (ml_hi_file loc)
in
- initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $
-
- dontLeakTheHUG $ do
-
- -- Load the new ModIface into the External Package State
- -- Even home-package interfaces loaded by loadInterface
- -- (which only happens in OneShot mode; in Batch/Interactive
- -- mode, home-package modules are loaded one by one into the HPT)
- -- are put in the EPS.
- --
- -- The main thing is to add the ModIface to the PIT, but
- -- we also take the
- -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules,
- -- out of the ModIface and put them into the big EPS pools
-
- -- NB: *first* we do tcIfaceDecls, so that the provenance of all the locally-defined
- --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
- -- If we do loadExport first the wrong info gets into the cache (unless we
- -- explicitly tag each export which seems a bit of a bore)
-
- -- Crucial assertion that checks if you are trying to load a HPT module into the EPS.
- -- If you start loading HPT modules into the EPS then you get strange errors about
- -- overlapping instances.
- ; massertPpr
- ((isOneShot (ghcMode (hsc_dflags hsc_env)))
- || moduleUnitId mod `notElem` hsc_all_home_unit_ids hsc_env
- || mod == gHC_PRIM)
- (text "Attempting to load home package interface into the EPS" $$ ppr (HUG.allUnits hug) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod))
- ; ignore_prags <- goptM Opt_IgnoreInterfacePragmas
- ; new_eps_decls <- tcIfaceDecls ignore_prags (mi_decls iface)
- ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
- ; new_eps_defaults <- tcIfaceDefaults mod (mi_defaults iface)
- ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
- ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
- ; new_eps_anns <- tcIfaceAnnotations (mi_anns iface)
- ; new_eps_complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
- ; purged_hsc_env <- getTopEnv
-
- ; let final_iface = iface
- & set_mi_decls (panic "No mi_decls in PIT")
- & set_mi_insts (panic "No mi_insts in PIT")
- & set_mi_defaults (panic "No mi_defaults in PIT")
- & set_mi_fam_insts (panic "No mi_fam_insts in PIT")
- & set_mi_rules (panic "No mi_rules in PIT")
- & set_mi_anns (panic "No mi_anns in PIT")
- & set_mi_simplified_core (panic "No mi_simplified_core in PIT")
-
- bad_boot = mi_boot iface == IsBoot
- && isJust (lookupKnotVars (if_rec_types gbl_env) mod)
- -- Warn against an EPS-updating import
- -- of one's own boot file! (one-shot only)
- -- See Note [Loading your own hi-boot file]
-
- -- Create an IO action that loads and compiles bytecode from Core
- -- bindings.
+ initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $ do
+
+ ; if fromMaybe False $ fmap (`isHomeModule` mod) mhome_unit -- TODO @fendor: horrible code
+ then do -- TODO @fendor: document that we don't want/need 'dontLeakTheHUG' here
+ massertPpr (moduleUnitId mod `Set.member` hsc_all_home_unit_ids hsc_env)
+ (text "Attempting to non-home package interface into the Home Loader State" $$ ppr (HUG.allUnits $ hsc_HUG hsc_env) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod))
+ tcParts <- tcPartsOfTheIface mod iface
+ addModIfacePartsToHpt gbl_env mod loc iface tcParts
+ else dontLeakTheHUG $ do
+ -- Load the new ModIface into the External Package State
--
- -- See Note [Interface Files with Core Definitions]
- add_bytecode old
- | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls)
- = extendModuleEnv old mod action
- -- Don't add an entry if the iface doesn't have 'extra_decls'
- -- so 'get_link_deps' knows that it should load object code.
- | otherwise
- = old
-
- ; warnPprTrace bad_boot "loadInterface" (ppr mod) $
- updateEps_ $ \ eps ->
- if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface
- then eps
- else if bad_boot
- -- See Note [Loading your own hi-boot file]
- then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls }
- else
- eps {
- eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
- eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
- eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
- eps_rule_base = extendRuleBaseList (eps_rule_base eps)
- new_eps_rules,
- eps_complete_matches
- = eps_complete_matches eps ++ new_eps_complete_matches,
- eps_inst_env = extendInstEnvList (eps_inst_env eps)
- new_eps_insts,
- eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
- new_eps_fam_insts,
- eps_ann_env = extendAnnEnvList (eps_ann_env eps)
- new_eps_anns,
- eps_mod_fam_inst_env
- = let
- fam_inst_env =
- extendFamInstEnvList emptyFamInstEnv
- new_eps_fam_insts
- in
- extendModuleEnv (eps_mod_fam_inst_env eps)
- mod
- fam_inst_env,
- eps_stats = addEpsInStats (eps_stats eps)
- (length new_eps_decls)
- (length new_eps_insts)
- (length new_eps_rules),
- eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults
- }
+ -- The main thing is to add the ModIface to the PIT, but
+ -- we also take the
+ -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules,
+ -- out of the ModIface and put them into the big EPS pools
+
+ -- NB: *first* we do tcIfaceDecls, so that the provenance of all the locally-defined
+ --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
+ -- If we do loadExport first the wrong info gets into the cache (unless we
+ -- explicitly tag each export which seems a bit of a bore)
+
+ -- Crucial assertion that checks if you are trying to load a HPT module into the EPS.
+ -- If you start loading HPT modules into the EPS then you get strange errors about
+ -- overlapping instances.
+
+ massertPpr
+ (moduleUnitId mod `Set.notMember` hsc_all_home_unit_ids hsc_env
+ || mod == gHC_PRIM)
+ (text "Attempting to load home package interface into the EPS" $$ ppr (HUG.allUnits $ hsc_HUG hsc_env) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod))
+ tcParts <- tcPartsOfTheIface mod iface
+ addModIfacePartsToEps gbl_env mod loc iface tcParts
; -- invoke plugins with *full* interface, not final_iface, to ensure
-- that plugins have access to declarations, etc.
@@ -927,6 +866,134 @@ loadInterface doc_str mod from
; return (Succeeded res)
}}}}
+tcPartsOfTheIface :: Module -> ModIface -> IfL ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], CompleteMatches)
+tcPartsOfTheIface mod iface = do
+ ignore_prags <- goptM Opt_IgnoreInterfacePragmas
+ new_eps_decls <- tcIfaceDecls ignore_prags (mi_decls iface)
+ new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
+ new_eps_defaults <- tcIfaceDefaults mod (mi_defaults iface)
+ new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
+ new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
+ new_eps_anns <- tcIfaceAnnotations (mi_anns iface)
+ new_eps_complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
+ pure
+ ( new_eps_decls
+ , new_eps_insts
+ , new_eps_defaults
+ , new_eps_fam_insts
+ , new_eps_rules
+ , new_eps_anns
+ , new_eps_complete_matches
+ )
+
+addModIfacePartsToHpt :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToHpt gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) = do
+ ; hsc_env <- getTopEnv
+ ; let details = ModDetails
+ { md_types = mkNameEnv new_eps_decls
+ , md_exports = mi_exports iface
+ , md_defaults = new_eps_defaults
+ , md_insts = mkInstEnv new_eps_insts
+ , md_fam_insts = new_eps_fam_insts
+ , md_rules = new_eps_rules
+ , md_anns = new_eps_anns
+ , md_complete_matches = new_eps_complete_matches
+ }
+ ; let final_iface = iface
+ & set_mi_decls (panic "No mi_decls in HomeLoaderState")
+ & set_mi_insts (panic "No mi_insts in HomeLoaderState")
+ & set_mi_defaults (panic "No mi_defaults in HomeLoaderState")
+ & set_mi_fam_insts (panic "No mi_fam_insts in HomeLoaderState")
+ & set_mi_rules (panic "No mi_rules in HomeLoaderState")
+ & set_mi_anns (panic "No mi_anns in HomeLoaderState")
+ & set_mi_simplified_core (panic "No mi_simplified_core in HomeLoaderState")
+
+ bad_boot = mi_boot iface == IsBoot
+ && isJust (lookupKnotVars (if_rec_types gbl_env) mod)
+ -- Warn against an HPT-updating import
+ -- of one's own boot file! (one-shot only)
+ -- See Note [Loading your own hi-boot file]
+
+ ; warnPprTrace bad_boot "loadInterface" (ppr mod) $ do
+ hpt <- getHpt
+ -- Create an IO action that loads and compiles bytecode from Core
+ -- bindings.
+ --
+ -- See Note [Interface Files with Core Definitions]
+ let lazy_bytecode = loadIfaceByteCode hsc_env iface loc (mkNameEnv new_eps_decls)
+ liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt
+ liftIO $ addOnDemandHomeModule hpt mod final_iface bad_boot (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) lazy_bytecode
+
+addModIfacePartsToEps :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL ()
+addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) = do
+ ; purged_hsc_env <- getTopEnv
+
+ ; let final_iface = iface
+ & set_mi_decls (panic "No mi_decls in PIT")
+ & set_mi_insts (panic "No mi_insts in PIT")
+ & set_mi_defaults (panic "No mi_defaults in PIT")
+ & set_mi_fam_insts (panic "No mi_fam_insts in PIT")
+ & set_mi_rules (panic "No mi_rules in PIT")
+ & set_mi_anns (panic "No mi_anns in PIT")
+ & set_mi_simplified_core (panic "No mi_simplified_core in PIT")
+
+ bad_boot = mi_boot iface == IsBoot
+ && isJust (lookupKnotVars (if_rec_types gbl_env) mod)
+ -- Warn against an EPS-updating import
+ -- of one's own boot file! (one-shot only)
+ -- See Note [Loading your own hi-boot file]
+
+ -- Create an IO action that loads and compiles bytecode from Core
+ -- bindings.
+ --
+ -- See Note [Interface Files with Core Definitions]
+ add_bytecode old
+ | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls)
+ = extendModuleEnv old mod action
+ -- Don't add an entry if the iface doesn't have 'extra_decls'
+ -- so 'get_link_deps' knows that it should load object code.
+ | otherwise
+ = old
+ ; let mhome_unit = ue_homeUnit (hsc_unit_env purged_hsc_env)
+ ; warnPprTrace bad_boot "loadInterface" (ppr mod) $
+ updateEps_ $ \ eps ->
+ if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface
+ then eps
+ else if bad_boot
+ -- See Note [Loading your own hi-boot file]
+ then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls }
+ else
+ eps {
+ eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
+ eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
+ eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
+ eps_rule_base = extendRuleBaseList (eps_rule_base eps)
+ new_eps_rules,
+ eps_complete_matches
+ = eps_complete_matches eps ++ new_eps_complete_matches,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps)
+ new_eps_insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
+ new_eps_fam_insts,
+ eps_ann_env = extendAnnEnvList (eps_ann_env eps)
+ new_eps_anns,
+ eps_mod_fam_inst_env
+ = let
+ fam_inst_env =
+ extendFamInstEnvList emptyFamInstEnv
+ new_eps_fam_insts
+ in
+ extendModuleEnv (eps_mod_fam_inst_env eps)
+ mod
+ fam_inst_env,
+ eps_stats = addEpsInStats (eps_stats eps)
+ (length new_eps_decls)
+ (length new_eps_insts)
+ (length new_eps_rules),
+ eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults
+ }
+
+
{- Note [Loading your own hi-boot file]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally speaking, when compiling module M, we should not
@@ -1142,10 +1209,10 @@ moduleFreeHolesPrecise doc_str mod
return (Succeeded (renameFreeHoles ifhs insts))
Failed err -> return (Failed err)
-wantHiBootFile :: Maybe HomeUnit -> ExternalPackageState -> Module -> WhereFrom
+wantHiBootFile :: Maybe HomeUnit -> HomeLoaderState -> Module -> WhereFrom
-> MaybeErr MissingInterfaceError IsBootInterface
-- Figure out whether we want Foo.hi or Foo.hi-boot
-wantHiBootFile mhome_unit eps mod from
+wantHiBootFile mhome_unit hls mod from
= case from of
ImportByUser usr_boot
| usr_boot == IsBoot && notHomeModuleMaybe mhome_unit mod
@@ -1164,8 +1231,8 @@ wantHiBootFile mhome_unit eps mod from
-- We never import boot modules from other packages!
| otherwise
- -> case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of
- Just (GWIB { gwib_isBoot = is_boot }) ->
+ -> case hlsIsBoot hls (toUnitId <$> mod) of
+ Just is_boot ->
Succeeded is_boot
Nothing ->
Succeeded NotBoot
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -93,6 +93,7 @@ import GHC.ByteCode.Serialize (ModuleByteCode, gbc_hash)
import GHC.Unit.Home.Graph (lookupHugByModule)
import GHC.Unit.Home.ModInfo (HomeModLinkable(..), HomeModInfo (..))
import GHC.Linker.Types (linkableParts)
+import GHC.Unit.Home.PackageTable
{-
-----------------------------------------------
@@ -427,7 +428,8 @@ checkVersions hsc_env mod_summary iface self_recomp
-- case we'll compile the module from scratch anyhow).
when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- ; updateEps_ $ \eps -> eps { eps_is_boot = mkModDeps $ dep_boot_mods (mi_deps iface) }
+ ; hpt <- getHpt
+ ; liftIO $ hlsSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface))
}
; recomp <- checkList [checkModUsage (hsc_FC hsc_env) u
| u <- mi_sr_usages self_recomp]
=====================================
compiler/GHC/IfaceToCore.hs
=====================================
@@ -137,6 +137,7 @@ import Language.Haskell.Syntax.BooleanFormula (BooleanFormula)
import Language.Haskell.Syntax.BooleanFormula qualified as BF(BooleanFormula(..))
import Language.Haskell.Syntax.Extension (NoExtField (NoExtField))
import GHC.Builtin.KnownKeys (ioTyConKey)
+import GHC.Unit.Home.PackageTable
{-
This module takes
@@ -631,12 +632,13 @@ tcHiBootIface hsc_src mod
-- current module, which either means a module loop (not
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
- do { eps <- getEps
- ; case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of
+ do { hpt <- getHpt
+ ; hls <- liftIO $ hptLoaderState hpt
+ ; case hlsIsBoot hls (toUnitId <$> mod) of
-- The typical case
Nothing -> return NoSelfBoot
-- error cases
- Just (GWIB { gwib_isBoot = is_boot }) -> case is_boot of
+ Just is_boot -> case is_boot of
IsBoot ->
let diag = Can'tFindInterface err
(LookingForHiBoot mod)
=====================================
compiler/GHC/Linker/Deps.hs
=====================================
@@ -157,8 +157,8 @@ get_link_deps opts pls maybe_normal_osuf span mods = do
else homeModInfoObject hmi <|> homeModInfoByteCode hmi
get_linkable osuf mod -- A home-package module
- = HUG.lookupHugByModule mod (ue_home_unit_graph unit_env) >>= \case
- Just mod_info -> adjust_linkable (expectJust (homeModLinkable mod_info))
+ = lookupHomeLinkable mod (ue_home_unit_graph unit_env) >>= \ case
+ Just home_linkable -> adjust_linkable home_linkable
Nothing -> do
-- It's not in the HPT because we are in one shot mode,
-- so use the Finder to get a ModLocation...
@@ -175,6 +175,10 @@ get_link_deps opts pls maybe_normal_osuf span mods = do
maybe (fallback_no_bytecode home_unit mod) pure from_bc
_ -> fallback_no_bytecode home_unit mod
where
+ lookupHomeLinkable mod hug =
+ HUG.lookupHugByModule mod hug >>= \case
+ Just mod_info -> pure $ homeModLinkable mod_info
+ Nothing -> pure Nothing
fallback_no_bytecode home_unit mod = do
let fc = ldFinderCache opts
=====================================
compiler/GHC/Tc/Instance/Family.hs
=====================================
@@ -57,6 +57,8 @@ import Data.Function ( on )
import qualified GHC.LanguageExtensions as LangExt
import Data.List (sortOn)
import qualified GHC.Unit.Home.Graph as HUG
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
+import Control.Applicative ((<|>))
{- Note [The type family instance consistency story]
@@ -407,8 +409,9 @@ getFamInsts hpt_fam_insts mod
| Just env <- lookupModuleEnv hpt_fam_insts mod = return env
| otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod)
; eps <- getEps
+ ; hpt_extra_mod_fam_insts <- queryHpt HomePackageTable.hptLoadedModFamInstEnv
; return (expectJust $
- lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
+ lookupModuleEnv hpt_extra_mod_fam_insts mod <|> lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
where
doc = ppr mod <+> text "is a family-instance module"
@@ -615,7 +618,8 @@ addLocalFamInst (home_fie, my_fis) fam_inst
-- by the current module, rather than every instance
-- we've ever seen. Fixing this is part of #13102.
; eps <- getEps
- ; let inst_envs = (eps_fam_inst_env eps, home_fie)
+ ; extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv
+ ; let inst_envs = (eps_fam_inst_env eps `unionFamInstEnv` extra, home_fie)
home_fie' = extendFamInstEnv home_fie fam_inst
-- Check for conflicting instance decls and injectivity violations
@@ -948,7 +952,7 @@ tcGetFamInstEnvs :: TcM FamInstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
tcGetFamInstEnvs
- = do { eps <- getEps; env <- getGblEnv
+ = do { eps <- getEps; env <- getGblEnv; !extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv
; let !pkg_env = eps_fam_inst_env eps
!home_env = tcg_fam_inst_env env
- ; return (pkg_env, home_env) }
+ ; return (pkg_env, home_env `unionFamInstEnv` extra) }
=====================================
compiler/GHC/Tc/Module.hs
=====================================
@@ -157,7 +157,6 @@ import GHC.Types.SourceFile
import qualified GHC.LanguageExtensions as LangExt
import GHC.Unit.Env as UnitEnv
-import GHC.Unit.External
import GHC.Unit.Types
import GHC.Unit.State
import GHC.Unit.Home
@@ -192,6 +191,7 @@ import qualified Data.Map as M
import Data.Foldable ( for_ )
import Data.Traversable ( for )
import Data.IORef( newIORef )
+import GHC.Unit.Home.PackageTable (hlsSetBootInfo)
{-
************************************************************************
@@ -513,7 +513,8 @@ tcRnImports hsc_env import_decls
-- visible to loadHiBootInterface in tcRnSrcDecls,
-- and any other incrementally-performed imports
; when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
- updateEps_ $ \eps -> eps { eps_is_boot = imp_boot_mods imports }
+ ; hpt <- getHpt
+ ; liftIO $ hlsSetBootInfo hpt (imp_boot_mods imports)
}
-- Update the gbl env
=====================================
compiler/GHC/Tc/Utils/Env.hs
=====================================
@@ -152,6 +152,7 @@ import Control.Monad
import Data.IORef
import Data.List ( intercalate )
import qualified Data.List.NonEmpty as NE
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{- *********************************************************************
* *
@@ -385,7 +386,8 @@ tcGetClsDefaults :: [Module] -> TcM [DefaultEnv]
tcGetClsDefaults mods = do
hug <- hsc_HUG <$> getTopEnv
module_env_defaults <- eps_defaults <$> getEps
- liftIO $ mapMaybeM (lookupClsDefault hug module_env_defaults) mods
+ more_env_defaults <- queryHpt HomePackageTable.hptLoadedDefaults
+ liftIO $ mapMaybeM (lookupClsDefault hug (module_env_defaults `plusModuleEnv` more_env_defaults)) mods
lookupClsDefault :: HomeUnitGraph -> ModuleEnv DefaultEnv -> Module -> IO (Maybe DefaultEnv)
lookupClsDefault hug module_env_defaults mod =
@@ -398,8 +400,9 @@ tcGetInstEnvs :: TcM InstEnvs
-- and the home-pkg inst env (includes module being compiled)
tcGetInstEnvs = do { eps <- getEps
; env <- getGblEnv
+ ; extra <- queryHpt HomePackageTable.hptLoadedInstEnv
; return (InstEnvs { ie_global = eps_inst_env eps
- , ie_local = tcg_inst_env env
+ , ie_local = tcg_inst_env env `unionInstEnv` extra
, ie_visible = tcVisibleOrphanMods env }) }
-- Illegal term-level use of type things
=====================================
compiler/GHC/Tc/Utils/Instantiate.hs
=====================================
@@ -88,6 +88,7 @@ import Data.List ( mapAccumL )
import qualified Data.List.NonEmpty as NE
import Control.Monad( when, unless )
import Data.Function ( on )
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{-
************************************************************************
@@ -922,6 +923,7 @@ addLocalInst (home_ie, my_insts) ispec
-- 'dups' are those 'matches' that are equal to the new one
; isGHCi <- getIsGHCi
; eps <- getEps
+ ; extra_inst_env <- queryHpt HomePackageTable.hptLoadedInstEnv
; tcg_env <- getGblEnv
-- In GHCi, we *override* any identical instances
@@ -933,7 +935,7 @@ addLocalInst (home_ie, my_insts) ispec
global_ie = eps_inst_env eps
inst_envs = InstEnvs { ie_global = global_ie
- , ie_local = home_ie'
+ , ie_local = home_ie' `unionInstEnv` extra_inst_env
, ie_visible = tcVisibleOrphanMods tcg_env }
-- Check for inconsistent functional dependencies
@@ -945,6 +947,13 @@ addLocalInst (home_ie, my_insts) ispec
; let (_tvs, cls, tys) = instanceHead ispec
(matches, _, _) = lookupInstEnv False inst_envs cls tys
dups = filter (identicalClsInstHead ispec) (map fst matches)
+ ; traceRn "addLocalInst 0" (ppr ispec)
+ ; traceRn "addLocalInst 1" (ppr home_ie)
+ ; traceRn "addLocalInst 2" (ppr my_insts)
+ ; traceRn "addLocalInst 3" (ppr matches)
+ ; traceRn "addLocalInst 4" (ppr dups)
+ ; traceRn "addLocalInst 5" (ppr global_ie)
+ ; traceRn "addLocalInst 6" (ppr extra_inst_env)
; unless (null dups) $
dupInstErr ispec (head dups)
=====================================
compiler/GHC/Tc/Utils/Monad.hs
=====================================
@@ -30,7 +30,7 @@ module GHC.Tc.Utils.Monad(
getEpsVar,
getEps,
updateEps, updateEps_,
- getHpt, getEpsAndHug,
+ getHpt, queryHpt, getEpsAndHug,
-- * Initialising TcM plugins
TcMPluginHandling(..),
@@ -261,6 +261,7 @@ import Control.Monad.Catch ( bracket_, finally, onException, mask, mask_, MonadC
import Data.Foldable (traverse_)
import Data.IORef
import qualified Data.Map as Map
+import qualified GHC.Unit.Home.PackageTable as HomePackageTable
{-
************************************************************************
@@ -740,6 +741,11 @@ updateEps_ upd_fn = updateEps (\eps -> (upd_fn eps, ()))
getHpt :: TcRnIf gbl lcl HomePackageTable
getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
+queryHpt :: (HomePackageTable -> IO a) -> TcRnIf gbl lcl a
+queryHpt f = do
+ hpt <- getHpt
+ liftIO $ f hpt
+
getEpsAndHug :: TcRnIf gbl lcl (ExternalPackageState, HomeUnitGraph)
getEpsAndHug = do { env <- getTopEnv; eps <- liftIO $ hscEPS env
; return (eps, hsc_HUG env) }
@@ -2740,8 +2746,9 @@ getCompleteMatchesTcM
= do { hsc_env <- getTopEnv
; eps <- liftIO $ hscEPS hsc_env
; tcg_env <- getGblEnv
+ ; extra_matches <- queryHpt HomePackageTable.hptLoadedCompleteMatches
; let tcg_comps = tcg_complete_match_env tcg_env
- ; liftIO $ localAndImportedCompleteMatches tcg_comps eps
+ ; liftIO $ localAndImportedCompleteMatches (tcg_comps ++ extra_matches) eps
}
localAndImportedCompleteMatches :: CompleteMatches -> ExternalPackageState -> IO CompleteMatches
=====================================
compiler/GHC/Unit/External.hs
=====================================
@@ -71,8 +71,7 @@ eucEPS = readIORef . euc_eps
initExternalPackageState :: ExternalPackageState
initExternalPackageState = EPS
- { eps_is_boot = emptyInstalledModuleEnv
- , eps_PIT = emptyPackageIfaceTable
+ { eps_PIT = emptyPackageIfaceTable
, eps_free_holes = emptyInstalledModuleEnv
, eps_PTE = emptyTypeEnv
, eps_iface_bytecode = emptyModuleEnv
@@ -101,19 +100,6 @@ initExternalPackageState = EPS
-- their interface files
data ExternalPackageState
= EPS {
- eps_is_boot :: !(InstalledModuleEnv ModuleNameWithIsBoot),
- -- ^ In OneShot mode (only), home-package modules
- -- accumulate in the external package state, and are
- -- sucked in lazily. For these home-pkg modules
- -- (only) we need to record which are boot modules.
- -- We set this field after loading all the
- -- explicitly-imported interfaces, but before doing
- -- anything else
- --
- -- The 'ModuleName' part is not necessary, but it's useful for
- -- debug prints, and it's convenient because this field comes
- -- direct from 'GHC.Tc.Utils.imp_dep_mods'
-
eps_PIT :: !PackageIfaceTable,
-- ^ The 'ModIface's for modules in external packages
-- whose interfaces we have opened.
=====================================
compiler/GHC/Unit/Home/PackageTable.hs
=====================================
@@ -23,9 +23,12 @@
-- 'hptCollectObjects'...
module GHC.Unit.Home.PackageTable
(
- HomePackageTable(..)
+ HomePackageTable
, emptyHomePackageTable
+ , HomeLoaderState -- TODO: should this be opaque? Probably
+ , emptyHomeLoaderState
+
-- * Lookups in the HPT
, lookupHpt
, lookupHptByModule
@@ -33,6 +36,7 @@ module GHC.Unit.Home.PackageTable
-- * Extending the HPT
, addHomeModInfoToHpt
, addHomeModInfosToHpt
+ , addOnDemandHomeModule
-- * Restrict the HPT
, restrictHpt
@@ -42,6 +46,18 @@ module GHC.Unit.Home.PackageTable
, hptAllInstances
, hptAllFamInstances
, hptAllAnnotations
+ , hlsIsModuleNameWithBoot
+ , hlsIsBoot
+ , hlsSetBootInfo
+ , hptLoadedIsBoot
+ , hptLoadedTypeEnv
+ , hptLoadedInstEnv
+ , hptLoadedFamInstEnv
+ , hptLoadedModFamInstEnv
+ , hptLoadedRuleBase
+ , hptLoadedAnnEnv
+ , hptLoadedCompleteMatches
+ , hptLoadedDefaults
-- ** More Traversal-based queries
, hptCollectDependencies
@@ -64,7 +80,7 @@ module GHC.Unit.Home.PackageTable
-- it is not sufficient to go through the intended insert-only API.
, hptInternalTableRef
, hptInternalTableFromRef
-
+ , hptLoaderState
-- * Legacy API
--
-- | This API is deprecated and meant to be removed.
@@ -80,8 +96,14 @@ import qualified Data.Set as Set
import GHC.Core.FamInstEnv
import GHC.Core.InstEnv
+import GHC.Core.Rules (RuleBase, extendRuleBaseList, emptyRuleBase)
+import GHC.Data.Word64Set qualified as W64
+import GHC.Linker.Types (Linkable)
import GHC.Types.Annotations
import GHC.Types.CompleteMatch
+import GHC.Types.TypeEnv
+import GHC.Types.TyThing
+import GHC.Types.Unique (getKey, getUnique)
import GHC.Types.Unique.DFM
import GHC.Unit.Home.ModInfo
import GHC.Unit.Module
@@ -89,13 +111,15 @@ import GHC.Unit.Module.Deps
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface
import GHC.Utils.Outputable
-import GHC.Types.Unique (getUnique, getKey)
-import qualified GHC.Data.Word64Set as W64
+import GHC.Types.Name
+import GHC.Types.Name.Env (extendNameEnvList)
+import GHC.Types.DefaultEnv (DefaultEnv)
+import GHC.Core
-- | Helps us find information about modules in the home package
-newtype HomePackageTable = HPT {
+data HomePackageTable = HPT {
- table :: IORef (DModuleNameEnv HomeModInfo)
+ table :: IORef (DModuleNameEnv HomeModInfo),
-- ^ Domain = modules in this home unit
--
-- This is an IORef because we want to avoid leaking HPTs (see the particularly bad #25511).
@@ -109,6 +133,7 @@ newtype HomePackageTable = HPT {
-- to temporarily violate the HPT monotonicity.
--
-- The elements of this table may be updated (e.g. on rehydration).
+ loader :: IORef HomeLoaderState
}
-- | Create a new 'HomePackageTable'.
@@ -120,7 +145,38 @@ emptyHomePackageTable :: IO HomePackageTable
-- romes:todo: use a MutableArray directly?
emptyHomePackageTable = do
table <- newIORef emptyUDFM
- return HPT{table}
+ loader <- newIORef emptyHomeLoaderState
+ return HPT{table, loader}
+
+data HomeLoaderState = HomeLoaderState
+ { hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot
+ , hls_iface_table :: ModuleEnv ModIface
+ , hls_type_env :: !TypeEnv
+ , hls_iface_bytecode :: !(ModuleEnv (IO Linkable))
+ , hls_inst_env :: !InstEnv
+ , hls_fam_inst_env :: !FamInstEnv
+ , hls_mod_fam_inst_env :: !(ModuleEnv FamInstEnv)
+ , hls_rule_base :: !RuleBase
+ , hls_ann_env :: !AnnEnv
+ , hls_complete_matches :: !CompleteMatches
+ , hls_defaults :: ModuleEnv DefaultEnv
+ }
+
+emptyHomeLoaderState :: HomeLoaderState
+emptyHomeLoaderState =
+ HomeLoaderState
+ { hls_is_boot = emptyInstalledModuleEnv
+ , hls_iface_table = emptyModuleEnv
+ , hls_type_env = emptyTypeEnv
+ , hls_iface_bytecode = emptyModuleEnv
+ , hls_inst_env = emptyInstEnv
+ , hls_fam_inst_env = emptyFamInstEnv
+ , hls_mod_fam_inst_env = emptyModuleEnv
+ , hls_rule_base = emptyRuleBase
+ , hls_ann_env = emptyAnnEnv
+ , hls_complete_matches = []
+ , hls_defaults = emptyModuleEnv
+ }
--------------------------------------------------------------------------------
-- * Lookups in the HPT
@@ -139,6 +195,36 @@ lookupHptByModule hpt mod
Just hm | mi_module (hm_iface hm) == mod -> Just hm
_otherwise -> Nothing
+hptLoaderState :: HomePackageTable -> IO HomeLoaderState
+hptLoaderState = readIORef . loader
+
+hptLoadedIsBoot :: HomePackageTable -> IO (InstalledModuleEnv ModuleNameWithIsBoot)
+hptLoadedIsBoot hpt = hls_is_boot <$> readIORef (loader hpt)
+
+hptLoadedTypeEnv :: HomePackageTable -> IO TypeEnv
+hptLoadedTypeEnv hpt = hls_type_env <$> readIORef (loader hpt)
+
+hptLoadedInstEnv :: HomePackageTable -> IO InstEnv
+hptLoadedInstEnv hpt = hls_inst_env <$> readIORef (loader hpt)
+
+hptLoadedFamInstEnv :: HomePackageTable -> IO FamInstEnv
+hptLoadedFamInstEnv hpt = hls_fam_inst_env <$> readIORef (loader hpt)
+
+hptLoadedModFamInstEnv :: HomePackageTable -> IO (ModuleEnv FamInstEnv)
+hptLoadedModFamInstEnv hpt = hls_mod_fam_inst_env <$> readIORef (loader hpt)
+
+hptLoadedRuleBase :: HomePackageTable -> IO RuleBase
+hptLoadedRuleBase hpt = hls_rule_base <$> readIORef (loader hpt)
+
+hptLoadedAnnEnv :: HomePackageTable -> IO AnnEnv
+hptLoadedAnnEnv hpt = hls_ann_env <$> readIORef (loader hpt)
+
+hptLoadedCompleteMatches :: HomePackageTable -> IO CompleteMatches
+hptLoadedCompleteMatches hpt = hls_complete_matches <$> readIORef (loader hpt)
+
+hptLoadedDefaults :: HomePackageTable -> IO (ModuleEnv DefaultEnv)
+hptLoadedDefaults hpt = hls_defaults <$> readIORef (loader hpt)
+
--------------------------------------------------------------------------------
-- * Extending the HPT
--------------------------------------------------------------------------------
@@ -186,6 +272,56 @@ restrictHpt HPT{table=hptr} hmis =
addListToHpt :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> IO ()
addListToHpt hpt = mapM_ (uncurry (addToHpt hpt))
+addOnDemandHomeModule :: HomePackageTable -> Module -> ModIface -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO ()
+addOnDemandHomeModule hpt mn iface bad_boot (new_hls_decls, new_hls_insts, new_hls_defaults, new_hls_fam_insts, new_hls_rules, new_hls_anns, new_hls_complete_matches) bytecode = do
+ atomicModifyIORef (loader hpt) $ \hls ->
+ ( if mn `elemModuleEnv` hls_iface_table hls
+ then hls -- If already loaded, don't add twice
+ else
+ if bad_boot
+ then addHomeModTypeEnv hls
+ else addHomeModData hls
+ , ()
+ )
+ where
+ addHomeModTypeEnv hls = hls
+ { hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls
+ }
+
+ addHomeModData hls = hls {
+ hls_iface_table = extendModuleEnv (hls_iface_table hls) mn iface,
+ hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls,
+ hls_iface_bytecode = case bytecode of
+ Nothing -> hls_iface_bytecode hls
+ Just bc -> extendModuleEnv (hls_iface_bytecode hls) mn bc,
+ hls_rule_base = extendRuleBaseList (hls_rule_base hls)
+ new_hls_rules,
+ hls_complete_matches
+ = hls_complete_matches hls ++ new_hls_complete_matches,
+ hls_inst_env = extendInstEnvList (hls_inst_env hls)
+ new_hls_insts,
+ hls_fam_inst_env = extendFamInstEnvList (hls_fam_inst_env hls)
+ new_hls_fam_insts,
+ hls_ann_env = extendAnnEnvList (hls_ann_env hls)
+ new_hls_anns,
+ hls_mod_fam_inst_env
+ =
+ let
+ fam_inst_env =
+ extendFamInstEnvList emptyFamInstEnv
+ new_hls_fam_insts
+ in
+ extendModuleEnv (hls_mod_fam_inst_env hls)
+ mn
+ fam_inst_env,
+ hls_defaults = extendModuleEnv (hls_defaults hls) mn new_hls_defaults
+ }
+
+hlsSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO ()
+hlsSetBootInfo hpt is_boot_env =
+ atomicModifyIORef' (loader hpt) $ \ hls ->
+ (hls { hls_is_boot = is_boot_env }, ())
+
----------------------------------------------------------------------------------
---- * Queries
----------------------------------------------------------------------------------
@@ -216,6 +352,11 @@ hptAllFamInstances = fmap mkModuleEnv . concatHpt (\hmi -> [(hmiModule hmi, hmiF
hptAllAnnotations :: HomePackageTable -> IO AnnEnv
hptAllAnnotations = fmap mkAnnEnv . concatHpt (md_anns . hm_details)
+hlsIsBoot :: HomeLoaderState -> InstalledModule -> Maybe IsBootInterface
+hlsIsBoot hls mn = gwib_isBoot <$> hlsIsModuleNameWithBoot hls mn
+
+hlsIsModuleNameWithBoot :: HomeLoaderState -> InstalledModule -> Maybe ModuleNameWithIsBoot
+hlsIsModuleNameWithBoot hls mn = lookupInstalledModuleEnv (hls_is_boot hls) mn
--------------------------------------------------------------------------------
-- * Traversal-based queries
@@ -315,7 +456,8 @@ hptInternalTableRef = table
-- Use with care, only if you can really justify going around the intended insert-only API.
hptInternalTableFromRef :: IORef (DModuleNameEnv HomeModInfo) -> IO HomePackageTable
hptInternalTableFromRef ref = do
+ loader <- newIORef emptyHomeLoaderState
return HPT {
- table = ref
+ table = ref,
+ loader
}
-
=====================================
compiler/GHC/Unit/Module/Env.hs
=====================================
@@ -13,7 +13,12 @@ module GHC.Unit.Module.Env
, extendModuleEnvWith, filterModuleEnv, mapMaybeModuleEnv
-- * ModuleName mappings
- , ModuleNameEnv, DModuleNameEnv
+ , ModuleNameEnv
+ , extendModuleNameEnv
+ , emptyModuleNameEnv
+ , lookupModuleNameEnv
+ , unionModuleNameEnv
+ , DModuleNameEnv
-- * Sets of Modules
, ModuleSet
@@ -234,6 +239,17 @@ UniqFM.
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM ModuleName elt
+extendModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> elt -> ModuleNameEnv elt
+extendModuleNameEnv = addToUFM
+
+emptyModuleNameEnv :: ModuleNameEnv elt
+emptyModuleNameEnv = emptyUFM
+
+lookupModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> Maybe elt
+lookupModuleNameEnv = lookupUFM
+
+unionModuleNameEnv :: ModuleNameEnv elt -> ModuleNameEnv elt -> ModuleNameEnv elt
+unionModuleNameEnv = unionModuleNameEnv
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
-- Has deterministic folds and can be deterministically converted to a list
=====================================
utils/haddock/haddock-api/src/Haddock/Interface.hs
=====================================
@@ -56,21 +56,25 @@ import GHC.Driver.Monad
import GHC.Driver.Make
import GHC.Driver.Main
import GHC.Core.InstEnv
+import GHC.Core.FamInstEnv
import qualified GHC.Driver.DynFlags as DynFlags
import qualified GHC.Utils.Outputable as Outputable
import GHC.Driver.Session hiding (verbosity)
import GHC.Driver.Phases
import GHC.Driver.Pipeline (compileFile)
import GHC.HsToCore.Docs (getMainDeclBinder)
-import GHC.Iface.Load (loadSysInterface)
-import GHC.IfaceToCore (tcIfaceInst, tcIfaceFamInst)
-import GHC.Tc.Utils.Monad (initIfaceLoad, initIfaceLcl)
+import GHC.Iface.Load (findAndReadIface)
+import GHC.IfaceToCore (tcIfaceDecls, tcIfaceInst, tcIfaceFamInst)
+import GHC.Tc.Utils.Monad (goptM, updateEps_, initIfaceLoad, initIfaceLcl)
import GHC.Tc.Utils.Env (lookupGlobal_maybe)
import GHC.Types.Error (mkUnknownDiagnostic)
import GHC.Types.Name.Occurrence (emptyOccEnv)
+import GHC.Types.Name.Env (extendNameEnvList)
import GHC.Unit.Finder (findImportedModule, runFinderM, ModuleLookupScope(..), FindResult(Found))
import GHC.Unit.Home.ModInfo
import GHC.Unit.Home.PackageTable
+import GHC.Unit.External (eps_PTE, eps_inst_env, eps_fam_inst_env)
+import GHC.Unit.Module (getModuleInstantiation)
import GHC.Unit.Module.Graph (ModuleGraphNode (..), ModuleNodeInfo(..))
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface (mi_semantic_module, mi_boot)
@@ -254,19 +258,29 @@ dropErr :: MaybeErr e a -> Maybe a
dropErr (Succeeded a) = Just a
dropErr (Failed _) = Nothing
-loadHiFile :: HscEnv -> Outputable.SDoc -> Module -> IO (ModIface, ([ClsInst], [FamInst]))
-loadHiFile hsc_env doc theModule = initIfaceLoad hsc_env $ do
-
- mod_iface <- loadSysInterface doc theModule
-
- insts <- initIfaceLcl (mi_semantic_module mod_iface) doc (mi_boot mod_iface) $ do
-
- new_eps_insts <- mapM tcIfaceInst (mi_insts mod_iface)
- new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts mod_iface)
-
- pure (new_eps_insts, new_eps_fam_insts)
-
- pure (mod_iface, insts)
+loadHiFile :: Verbosity -> HscEnv -> Outputable.SDoc -> Module -> IO (ModIface, ([ClsInst], [FamInst]))
+loadHiFile verbosity hsc_env doc requested = initIfaceLoad hsc_env $ do
+ let installed = fst (getModuleInstantiation requested)
+ iface_fetch_result <- liftIO $ findAndReadIface hsc_env doc installed requested NotBoot
+ case iface_fetch_result of
+ Failed _ -> do
+ out verbosity normal $ "Loading interface for " ++
+ moduleNameString (moduleName requested) ++
+ " failed"
+ liftIO exitFailure
+ Succeeded (mod_iface, _) -> do
+ all_insts <- initIfaceLcl (mi_semantic_module mod_iface) doc (mi_boot mod_iface) $ do
+ ignore_iface_pragmas <- goptM Opt_IgnoreInterfacePragmas
+ decls <- tcIfaceDecls ignore_iface_pragmas (mi_decls mod_iface)
+ insts <- mapM tcIfaceInst (mi_insts mod_iface)
+ fam_insts <- mapM tcIfaceFamInst (mi_fam_insts mod_iface)
+ updateEps_ $ \ eps -> eps {
+ eps_PTE = extendNameEnvList (eps_PTE eps) decls,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps) insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps) fam_insts
+ }
+ pure (insts, fam_insts)
+ pure (mod_iface, all_insts)
processModule :: Verbosity -> ModSummary -> [Flag] -> IfaceMap -> InstIfaceMap -> WarningMap -> Ghc (Maybe Interface)
processModule verbosity modSummary flags ifaceMap instIfaceMap warningMap = do
@@ -279,7 +293,7 @@ processModule verbosity modSummary flags ifaceMap instIfaceMap warningMap = do
unit_state = hsc_units hsc_env
(mod_iface, insts) <- if Flag_NoCompilation `elem` flags
- then liftIO $ loadHiFile hsc_env doc $ ms_mod modSummary
+ then liftIO $ loadHiFile verbosity hsc_env doc $ ms_mod modSummary
else do
hmi <- liftIO $ lookupHpt (hsc_HPT hsc_env) (moduleName $ ms_mod modSummary) >>= \case
Nothing -> error "processModule: All modules should be loaded into the HPT by this point"
@@ -376,7 +390,7 @@ createOneShotIface verbosity flags instIfaceMap moduleNameStr = do
let oneShotUnit = stringToUnit (unitIdString (homeUnitId_ dflags))
- (iface, insts) <- liftIO $ loadHiFile hsc_env doc $ mkModule oneShotUnit moduleNm
+ (iface, insts) <- liftIO $ loadHiFile verbosity hsc_env doc $ mkModule oneShotUnit moduleNm
-- Update the DynFlags with the extensions from the source file (as stored in the interface file)
-- This is instead of ms_hspp_opts from ModSummary, which is not available in one-shot mode.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0f928d0a6db34470ba941f37d58ee0ā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0f928d0a6db34470ba941f37d58ee0ā¦
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/T27981-ncg-mystery-box] 73 commits: Fix stale and false comments in the NCG
by Mikolaj Konarski (ļ¼ Mikolaj) 20 Nov '26
by Mikolaj Konarski (ļ¼ Mikolaj) 20 Nov '26
20 Nov '26
Mikolaj Konarski pushed to branch wip/T27981-ncg-mystery-box at Glasgow Haskell Compiler / GHC
Commits:
35ec50c5 by Mikolaj Konarski at 2026-11-20T00:12:51+01:00
Fix stale and false comments in the NCG
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe."
Comments and documentation only: the generated code is the same. Each
item names a comment, says what it said, and says what holds instead.
- The comment above genMachCode in GHC.CmmToAsm named stix code
and the UniqSM monad. The code is Cmm, and genMachCode switches
from the UniqDSM monad to NatM.
- NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad, placed
Note [Unwinding information in the NCG] in that module. The Note
is in GHC.CmmToAsm.
- The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm,
AsmCodeGen and MachCodeGen. It now names the modules and functions
that do what it lists. Two comments further down named MachCodeGen:
as calling cmmMakeDynamicReference for static data, which
the instruction selectors do, and as calling the initialization
of the PIC base register for every procedure that accessed it, which
cmmTopCodeGen in the x86 and PowerPC instruction selectors does,
but not on AIX. They now say so.
- The header of GHC.CmmToAsm.Reg.Target said that the module keeps
the NCG from emitting code for an architecture other than the host's.
Each of its functions dispatches on the target platform's
architecture, and the sentence is deleted.
- Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout ran
optimizeCFG right after instruction selection. cmmNativeGen runs
it after register allocation and shortcutting. The Note presented
the next two steps, loopInfo's loop analysis and mkGlobalWeights'
refinement of the edge weights, as unconditional; optimizeCFG takes
them only under -fcmm-static-pred, which -O implies, and the Note now
says so. It said that the refined weights are normalized relative
to the most often visited node; they are relative to the entry node,
to which calcFreqs gives frequency 1.
- Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight
as 20k; defaultWeights has 1000. It said that likely branches
are taken more than 80% of the time and unlikely ones less than 20%;
the default weights give 75% and 25%. It said that the false side
of a regular branch is preferred; getCfg gives both sides the same
weight, the x86-64 instruction selector adds 3 to the false side
of a floating-point comparison, and optHsPatterns' favourFewerPreds
may then prefer one side by its predecessors. It said that calls
are ignored completely; the layout leaves a call's edge out while
it builds chains and while it combines neighbouring chains,
and divides its weight by 64 when it merges the chains.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also
said that edges constituted by a call are ignored. The layout ignores
them while it builds the chains and while it combines neighbouring
chains, and counts a 64th of their weight when it merges the chains.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two
heuristics where staticBranchPrediction applies three, ohPredicts
being the third.
- In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1
is the branch in the true case; s1 is the successor with the smaller
label. The guard commented "Only backedges" is also reached by a back
edge beside a heap or stack check's edge, and its comment now says so.
- The comment above findBackEdges, in GHC.CmmToAsm.CFG, said
that it finds back edges by BFS. It finds them by a depth-first search
(classifyEdges in GHC.Data.Graph.Directed).
- The Instruction class asked regUsageOfInstr to state precisely
the registers an instruction reads and writes. x86's states them
as the register allocators are to see them, and the comment now says
so, with examples of where that departs from what the hardware does.
- The comment at the last arm of regUsageOfInstr's MOV case,
in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching
it zero any remaining upper part of the destination. Some do, such
as a 32-bit MOV into a general register and a load at FF32 or FF64;
others keep it, such as a MOV between registers at FF32 or FF64,
printed movss or movsd, and an 8-bit or 16-bit MOV into a general
register. The comment now also says that the usage of the other MOV
instructions has a register destination written, not read.
- Comments in the liveness pass, in both register allocators and
at the Ord instances of CmmTickScope, LocalReg and VirtualReg said
that deterministic code generation is not supported, which
-fobject-determinism provides. In the liveness pass
and the allocators, each now says whether the order at hand matters
and, where it does, what it decides; at the Ord instances,
that the order compares uniques and so is deterministic only
if the uniques are.
- In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there
are no loops in the code, so that the block frequencies can be 1.
Given a CFG, slurpSpillCostInfo scales the uses and definitions
it counts by the CFG's block frequencies; the comment is deleted.
- linearRegAlloc's haddock and the comment over process said
that a block of an SCC is allocated before a jump into it only
if it is the procedure's first block; any of its entry blocks is.
The comment over process also said that process loops where a block's
assignment never gets set. It stops after a round that allocates
no block, and so drops such a block.
- findPrefRealReg's comment said that the preferred register
is the first one the variable was assigned to. It is the variable's
register in the first entry assignment, in allocation order, that maps
it to a register; a block's entry assignment is recorded at the first
jump into it.
- Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint,
which is -dasm-lint.
- Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag
-ddrop-asm-stats, which is -ddump-asm-stats.
- The executable specification of FreeRegs,
in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently
released registers first. It now gives noFreeRegs as [] and has
getFreeRegs hand out the registers in each instance's fixed order.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays
associated with its register to the end of the procedure. A register
that outgrows its slot moves to new ones; what holds is that no other
register gets the old slot.
- The comment at handleComponent's case for a cycle of moves,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that it spills all
the cycle's source registers. It spills one.
- makeRegMovementGraph's comment said that cyclic components seem
to occur only very rarely. They are frequent in some code:
in the benchmark of orthotope, a Haskell array library on Hackage,
compiled by a GHC build of 2026-10 whose linear allocator
was master's, the fixup code breaks 39 register cycles through a stack
slot in $w$s$wequalT1 and 59 in $w$s$w$ccompare1. The two counts
were not taken again on master. The sentence is deleted.
- A comment at expandNode's case for a move from InBoth to InMem,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that the source's slot
is guaranteed to be the destination's. They can differ where
the virtual register has more than one slot, and the value
is then stored from its register; the comment now says that the guard
fails only there.
- GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal proc labels]
in GHC.Cmm.Label, across two lines. The Note is in GHC.Cmm.CLabel,
and the citation is now on one line.
- A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs
scans the integer registers from 28 down. It starts from x18,
and the comment now also says that it starts from v31 among the v
registers.
- The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86"
of what holds on i386 alone, and numbered the registers with 8-bit
versions 1-4, and the allocatable ones among them 1, 3 and 4. It now
says "On i386", and they are 0-3, and 0, 2 and 3.
- The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave
RISC-V as an example. registerArch gives RISC-V NoVectors
and no architecture Separate.
- The stmtToInstrs of X86, AArch64, LA64 and RV64 took the condition
of a conditional branch to be likely false, GHC.Cmm.ContFlowOpt having
arranged for the likely side to fall through. ContFlowOpt also inverts
a condition whatever its likelihood where the condition can
be inverted, the true target has one predecessor and the false target
more than one, so the condition may be likely true; none of the four
genCondBranch functions reads the likelihood.
- mkCmmIfThenElse', in GHC.StgToCmm.Monad, said that the NCG does
not know about likely annotations. The PowerPC code generator has
printed them as branch hints since 2017, and since 2018 getCfg has
weighted the CFG's edges by them, which on x86-64 the block layout
and the order of some conditional branches' jumps (invertCondBranches)
follow. Its clause on a fallthrough is replaced by what the swap does:
where the test can be inverted it becomes a likely-true test
of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where
the true target, after shortcutting, has one predecessor.
- The users' guide said that -fcmm-static-pred's prediction is used
by the register allocation and code layout passes. The prediction
is made only in the x86-64 native code generator, and is used, after
register allocation and without -finfo-table-map, for the layout
and for the order of some conditional branches' jumps
(invertCondBranches). The entry now also says that on x86-64 the graph
colouring allocators (-fregs-graph, -fregs-iterative) weight the uses
and definitions they count by the same heuristics whatever the flag
says, without -finfo-table-map (slurpSpillCostInfo, mkGlobalWeights),
but choose what to spill by live range length alone (chooseSpill,
spillCost_length), so that the flag does not change their allocation.
- The users' guide's entry of -fcmm-sink said that the sinking pass
attempts to find identical Cmm blocks and eliminate the duplicates.
Those are words of the -fcmm-elim-common-blocks entry, run
into this entry's sentence since the two entries were written;
the sentence now says only that the pass attempts to move variable
bindings closer to their usage sites.
Assisted-by: Claude Opus 5.5
- - - - -
f34bb767 by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Define the labels of the NCG's comments
Of what anyone working with the NCG needs, this commit serves "The kind
of each statement in the NCG's comments, shown at the statement: a bug,
half-done work, a likely change or code meant to stay.", "What a comment
that does not show the kind of its statements does and does not claim."
and "How the statements on bugs, half-done work and likely changes
are kept true as the code changes."
Comments only; the generated code is the same.
Note [Labels in NCG comments], added to GHC.CmmToAsm, defines the labels
that the native code generator's comments put at the head
of a statement. The commits that follow label each statement they add,
and are read under this Note:
BUG wrong behaviour, a missing check or misleading code;
the statement says in short what it leads to and where
it is reached
WIP half-done work
TODO what is likely to change, correct or buggy; a bug marked
TODO alone is accepted for now and worked around
BUG TODO both, where both are to be stressed
no label what is meant to stay; a kept trade-off says why
A BUG statement names its consequence: wrong code, wrong debugging
information, a panic or another failed compilation, assembly
the assembler rejects, only slower or larger code, only a warning
from the assembler, only more C stack space, or only a misled reader.
The Note does not reach back to older comments: their TODO, ToDo, FIXME
and XXX predate its meanings, and an older comment that carries no label
makes no claim that the code is meant to stay.
The Note also says how the labels are kept true. A change to what
a labelled statement describes removes or rewrites the statement
in the same change; BUG and TODO gain the issue's number when the issue
is filed; and a git grep given in the Note lists the labelled lines.
Assisted-by: Claude Opus 5.5
- - - - -
4afe468d by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Document bugs and TODOs in the NCG's CFG and block layout
Of what anyone working with the NCG needs, this commit serves "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- postRegCFG in GHC.CmmToAsm (BUG: X86's allocMoreStack retargets every
jump into an entry block to the block it adds after it,
but addImmediateSuccessor moves only the entry block's own edges).
The CFG keeps an edge into the entry block from each block that jumps
there, though the code now jumps to the added block, and lacks
those blocks' edges to the added block. This costs only speed.
It is reached on x86-64, the only target with a CFG after register
allocation, where ncgAllocMoreStack adds blocks, that is, where
allocation needs more spill slots than maxSpillSlots. This rests
on master's code read. The linear allocator's fixup blocks were added
to the CFG before postRegCFG, and the added block is reachable,
through the entry block's edge to it. No reader of the CFG after
postRegCFG panics on these edges: shortcutWeightMap has no lookup
that panics; optimizeCFG's lookups take their blocks and edges
from the CFG itself; sanityCheckCfg compares blocks only; sequenceTop
looks up only the blocks the CFG's edges name, all of them blocks
of the code; and invertCondBranches takes an edge's information
as a Maybe and leaves a jump without it alone.
- build_mapping in shortcutBranches, GHC.CmmToAsm (BUG: under -g a block
that holds only its jump also holds the location and unwinding
information that -g adds, so it is kept where without -g
it is shorted). The code under -g jumps through the kept block,
and on x86-64 static prediction and block layout get another CFG
than without -g. This costs only speed and code size, under -g
and -fasm-shortcutting, on x86 and x86-64, not on Darwin. This rests
on master's code read: split matches a block of exactly one
instruction, and under -g on ELF targets other than AArch64
the instruction selectors put a LOCATION at the head of a block
with a source note, and under -g x86's gives a CmmUnwind an UNWIND,
neither of which emits code. On a development branch whose block
layout differed from master's, this changed the code of a probe
under -g.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG (BUG:
with tables next to code too, a block that is only a tail call's jump
to a label is shortcut away, and with it the edge A -> B). A's branch
has one target fewer in the CFG than in the code, and a loop whose
only exit was the lost edge has no exit in the CFG, so calcFreqs caps
its cycle probability. This costs only speed. It is reached on x86-64,
the only target with a CFG after register allocation,
under -fasm-shortcutting, not on Darwin. This rests on master's code
read: the removed block ends in a tail call and has no edges out
in the CFG; it leaves the code and the CFG together, and no block
becomes unreachable; and the readers of the CFG after
shortcutWeightMap, listed above for postRegCFG, do not panic
on a missing edge.
- getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28088: the CFG gets only
the blocks reachable from the entry, while instruction selection still
covers the blocks that cmmToCmm makes unreachable when, after the Cmm
pipeline has removed the unreachable blocks, it turns a branch
on a constant into a jump). Where such a block updates the CFG
at its current block, as X86's cmpxchg loop for an atomic and, or, xor
or nand does, the compiler panics with "getSuccessorEdges: Block does
not exist". This is reached on x86 and x86-64, at any optimisation
level: cmmToCmm turns a branch on a literal into a jump under every
flag, and the literal comes at -O0 from cmmToCmm's own constant
folding and at -O from sinking's. For x86-64 this rests on master's
code read and on runs of master's compiler under -dcmm-lint.
A procedure whose if (1 != 0) leaves a block with a fetch-and-and
unreachable panics with that message at -O0 and at -O, and also
at both with -finfo-table-map added, under which no CFG is kept after
instruction selection, as on i386. Where the branch tests a local set
to 1 instead, the procedure panics at -O and compiles at -O0. For i386
it rests on master's code read alone, no i386 compiler having
been run: getCfgProc builds the CFG for every target, i386 runs
the same selector (ncgX86 = ncgX86_64), and updateCfgNat forces each
update, so addImmediateSuccessor's call of getSuccessorEdges panics
during instruction selection whether or not a CFG is kept after it.
It rests also on ISSUE 28088's record.
A TODO citing ISSUE 20428, at livenessCfg
and at ncgEnableDeadCodeElimination, says that -finfo-table-map turns
dead code elimination off, and with it every use of the CFG
from the liveness pass on. No CFG is then kept after register
allocation, so the layout has neither static prediction nor the chains
of -fblock-layout-cfg, and lays the blocks out without weights.
Note [CFG Edge Weights] now says what -fcmm-static-pred changes:
that under it the weights become estimated frequencies before the layout
uses them.
A TODO in Note [Layout relevant edge weights],
in GHC.CmmToAsm.BlockLayout, citing ISSUE 27799, says that the modifier
on the edges of a conditional branch under-prices such an edge where
buildChains skips the branch's other edge because it would close
a cycle, as it can skip a loop latch's back edge.
At getCfg's case for a switch, master's comment says that the weight -1
given to every target of a switch with more than ten targets, a compiler
performance hack, keeps the layout from considering them. A TODO there
now says that the layout considers them nonetheless, and that what
the hack saves has not been measured.
Other TODOs say:
- at the Ord instance of CfgEdge, that edges of equal weight are ordered
by their labels, which carry no meaning for the layout;
- in Note [Updating the CFG during shortcutting], that where
shortcutting redirects an edge onto one already there, only one
EdgeInfo is kept and the weights are not summed;
- at allEdges' relevantWeight in sequenceChain, that it differs
from directEdges';
- at dropJumps, that a block that only jumps to the next one is left
as an empty label and a jump over it is kept.
In X86's genCondBranch', a comment says that the 3 added to the weight
of a floating-point comparison's false edge breaks layout ties toward
the side GHC.Cmm.ContFlowOpt arranges to fall through.
Assisted-by: Claude Opus 5.5
- - - - -
87d38d0a by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Document bugs and TODOs in static branch prediction and loop analysis
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, BUG TODO for a bug that is also likely to change,
WIP for half-done work, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- getCfg in GHC.CmmToAsm.CFG (BUG: after fixStgRegisters, a test
of CurrentTSO or CurrentNursery reads BaseReg and is tagged
HeapStackCheck). The exemptions of Note [Static Branch Prediction]
for heap and stack checks then apply to such a test, so its weights
are left unpredicted. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read. The tag
decides the code only through isHeapOrStackCheck, all of whose callers
are in staticBranchPrediction, which runs inside mkGlobalWeights.
mkGlobalWeights reaches the code through staticPredCfg, only
under -fcmm-static-pred, and otherwise only through the graph
allocator's spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28083 (an edge into the entry block is never a back edge,
as mkDomMap leaves the root out of every dominator set). A loop whose
head is the entry block is not found. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read
and ISSUE 28083's record. loopInfo's result reaches the code only
through static prediction and block layout: of its two callers,
loopLevels is never called, and mkGlobalWeights serves staticPredCfg,
under -fcmm-static-pred, and otherwise only the graph allocator's
spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28093 (a self loop is a back edge only where its block dominates
no other block). A block that jumps to itself and to an exit
it dominates, as cmpxchg_code's retry loop in GHC.CmmToAsm.X86.CodeGen
does, is not a loop. calcFreqs then takes the block for irreducible
and gives frequency 0 to it and to every block it dominates.
This costs only speed, on x86-64 under -fcmm-static-pred, by the same
path as the BUG of ISSUE 28083. This rests on master's code read,
on the record of ISSUE 28093, and on -ddump-cfg-weights of a loop
calling fetchOrIntArray#, compiled by a GHC built from 3d326d7d28
with changes outside the native code generator: the retry block's
edges and the loop's back edge weigh 0. Between 3d326d7d28
and the master commit this branch starts from, GHC.CmmToAsm.CFG
and cmpxchg_code are unchanged, and the dominator code loses only
a `return = pure`.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG (BUG: the back
edge rule supersedes a likely annotation in the Cmm as well). A branch
with both a back edge and another edge is predicted to take the back
edge, whatever its annotation says. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read:
staticBranchPrediction's case for a mix of back edges and other edges
reads no annotation.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG (BUG TODO:
a constructor-tag test is predicted like any other comparison,
its equal side unlikely). The prediction is wrong for the trees
of Data.Map and Data.Set, which declare Bin first: in a lookup,
the side that stays in the loop is predicted unlikely. This costs only
speed, on x86-64 under -fcmm-static-pred. It is accepted until
the knowledge of the likely side reaches the CFG, hence TODO as well.
This rests on master's code read.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG, its BUG (s1
is taken for the true side only where it is ltrue, the label
the branch was made with, which an edge no longer ends at once
the linear allocator's fixup block, by addNodesBetween,
or shortcutting, by shortcutWeightMap, has redirected it). Where
the redirected true edge's new target has the smaller label
of the two, each side gets the other's prediction, and the layout's
estimate takes the likely side for the unlikely one. This costs only
speed, on x86-64 under -fcmm-static-pred. This rests on master's code
read, and on a count over nofib's modules on a development branch
whose static prediction also predicts an inequality with a literal,
which found such branches inverted at -O2 and none at -O1.
- calcFreqs in GHC.CmmToAsm.CFG (BUG: mkGlobalWeights passes the loops
in the order of loopInfo's back edges, by label, and not by nesting).
An enclosing loop's pass can come before an inner loop's and read
the branch probability of an inner back edge where its cycle
probability belongs, which gives nested loops wrong cycle
probabilities. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read.
A WIP in Note [Static Branch Prediction] says that the paper's other
heuristics are stubs.
calcFreqs' comment on an irreducible block, "Rare we don't care", now
says what frequency such a block keeps and, as a TODO, that such blocks
are not rare, that the layout then ranks edges by frequencies that do
not add up, with a loop calling fetchOrIntArray#, compiled by the GHC
named under ISSUE 28093 above, for a case, and what summing their inflow
measured on a development branch.
Other TODOs say:
- in Note [Back edges in loopInfo], that findBackEdges, which
optHsPatterns uses for the back edge bonus, disagrees with loopInfo
on edges into the entry block, on back edges of irreducible cycles
and on self loops;
- at ohPredicts, that only MO_Eq is read, so the spelling
GHC.Cmm.ContFlowOpt leaves decides whether a test is predicted,
and that predicting a pointer-tag test spelt with MO_Ne as its MO_Eq
spelling is predicted was tried on a development branch and gained
nothing;
- at lehPredicts, that where a heap or stack check's call to the garbage
collector returns into the procedure, loopInfo takes the cycle through
that call for a loop: the heuristic then says nothing about a branch
into the checking block where that block is the loop's head, and takes
a branch towards a case alternative without such a check for a loop
exit where the head is the block choosing the alternative;
- at calcFreqs, that nothing checks its result, and that a check could
compare each block's frequency with the sum of the frequencies
on its in-edges, which the propagation departs from at some blocks,
among them an irreducible block, a loop head whose cycle probability
is capped, and the entry block;
- at loopMembers, that neither it nor loopLevels has a caller in GHC:
loopMembers since the graph allocator's spill costs, for which
it was added early in 2019, began that year to weight by block
frequencies instead, and loopLevels since it came with the loop
analysis that year.
A comment at optimizeCFG says that static prediction starts
from the weights optHsPatterns leaves, so that their adjustments carry
into the predicted probabilities, except where the back edge rule
replaces them.
Assisted-by: Claude Opus 5.5
- - - - -
90ee3014 by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Document bugs and TODOs in liveness and the register allocators
Of what anyone working with the NCG needs, this commit serves
"The invariants the code depends on.", "Where the code does something
other than what reading it suggests.", "Where the code is known
to behave wrongly or is half done.", "What each known bug leads to, such
as wrong code, a compiler panic or only slower code, and under which
flags and on which targets it is reached." and "Where the code is likely
to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- regAlloc in GHC.CmmToAsm.Reg.Graph (BUG: it hands ncgAllocMoreStack
slotsCount', the highest slot number, which counts the preallocated
slots, where the linear allocator gives only the slots beyond
maxSpillSlots): the preallocated slots are reserved a second time.
This costs C stack space, under -fregs-graph or -fregs-iterative,
on every target, and where a target's mkStackAllocInstr needs more
instructions for a larger amount, code at entry and exit: on AArch64
one instruction more for each 4095 bytes, on RISC-V, LoongArch
and PowerPC more past the range of an immediate, and on Windows x86-64
a call of ___chkstk_ms past 4 KB. This rests on master's code read.
Every target's allocMoreStack moves the stack pointer by the slots
it is given times spillSlotSize. The graph allocator can be chosen
for any target, and trivColorable covers x86, x86-64, PowerPC,
AArch64, RISC-V and LoongArch.
- pprSpillCostRecord in GHC.CmmToAsm.Reg.Graph.SpillCost (BUG: it binds
a SpillCostRecord as (reg, uses, defs, life), where the type's
comments give its fields as the writes, the reads and the lifetime).
Only the names are wrong: it prints the two counts in the record's
order, under no names, and their sum divided by the register's node
degree, and nothing in GHC calls it. This rests on master's code read:
slurpSpillCostInfo's incDefs fills the second field and incUses
the third.
- joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG: on x86
a floating-point == or /= test's block ends in two jumps that name one
target, genCondBranch's parity jump and a conditional or unconditional
one, and each is joined on its own). Where that target needs a fixup
block, each of the two jumps gets one, with the same moves, and both
are reachable. This costs only code size, on x86 and x86-64
under the linear allocator. This rests on master's code read
and on constructed Cmm compiled by master's compiler; no module
of nofib or of the compile benchmarks was found to show it. A fix
that shares the block where the two jumps' stack deltas agree,
the target's vregs have the same locations at both and no value moves
between two slots was written on a development branch and is left out.
- joinToTargets_again in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG:
once it has made a fixup block for a target and patched the jump to go
there, the destinations still to consider keep the target's later
occurrences, as a jump table lists a target once for each entry naming
it). Each later occurrence makes the same moves again, into a block
nothing jumps to, which is given an edge in the CFG, laid out
and emitted: dead code. This costs only code size, under the linear
allocator. This rests on master's code read: x86's jumpDestsOfInstr
lists a jump table's targets with their repetitions, and the other
targets with jump tables do likewise. Such a block was found in GHC's
own GHC.CmmToAsm.Dwarf.Constants and in none of nofib's
or the testsuite's modules.
- makeRegMovementGraph, handleComponent and makeMove
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, and the header
of GHC.CmmToAsm.Reg.Linear.StackMap (BUG, ISSUE 27638: since
ISSUE 26668 a virtual register whose format has outgrown its slot gets
new slots, so a jump can need a move between two slots of one
register): such a move ends in makeMove's panic, "makeMove: we don't
handle mem->mem moves". And where handleComponent's cyclic case moves
to an InBoth destination (BUG, a statement of its own, ISSUE 27638
reporting only the panic), the destination's slot is written only
if it is the slot spillR picks; otherwise it keeps a stale value,
which is wrong code where the slot is reloaded. Both are reached
under the linear allocator, where a virtual register's format grows
past 8 bytes, which only a vector format does, and so only on i386,
x86-64 and AArch64, the targets whose code generators take vectors
(checkVecCompatibility in GHC.StgToCmm.Prim; PowerPC's, RV64's
and LA64's stop with sorry on vectors). The first is reached on x86-64
at -O1 and -O2: master's compiler panics so on a function in which
a Double, also broadcast to a DoubleX2#, is live at a join of two arms
of a case that both load eleven Int#s and seventeen Doubles.
No program reaching the second is known. The first can be reached two
ways, by expandNode, both from a jump at which the virtual register
is in one of its slots only: into a block that holds it in another
of its slots only, and into a block that holds it in a register
and another slot, where makeMove loads the register first. A fix
cannot count on a spare register: nothing keeps one free at a jump,
and the block's entry assignment can hold every allocatable register,
on x86-64 the eleven integer registers (rax, rbx, rcx, rdx, rsi, rdi,
r8 to r11 and r14) and the sixteen vector registers, the others being
the stack pointer and those of STG's Base, Sp, Hp and SpLim (freeReg
in compiler/CodeGen.Platform.h). This rests on master's code read,
ISSUE 27638's record and a run of master's compiler. The cyclic case
drops the InMem half of an InBoth destination (expandNode lists InReg
first) and writes only spillR's slot, which is getStackSlotFor's
newest slot of the virtual register and differs from the destination's
only after the register grew. And allocateRegsAndSpill frees
the register of an InBoth virtual register without a store,
so that its next use reloads the slot.
- livenessSCCs in GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 27619: Regs' Eq
compares the registers and not their formats, so the fixpoint can stop
before the formats recorded for a cycle's blocks converge): a vector
register can be recorded live at a format narrower than the value
it holds, and a write at that format then kills
it in minusCoveredRegs, which is wrong code. No program giving a wrong
result is known. This rests on master's code read and ISSUE 27619's
record, whose program shows a register recorded so.
- getSlotMap in slurpReloadCoalesce, GHC.CmmToAsm.Reg.Liveness (BUG:
it folds the slot maps of a block's predecessors from the empty map
with mergeSlotMaps, which keeps only the slots both maps hold).
The slot map on entry to a block is always empty, so a reload
is coalesced with a spill only inside one block. This costs only speed
and code size, under -fregs-graph or -fregs-iterative, on every
target. This rests on master's code read; buildGraph
in GHC.CmmToAsm.Reg.Graph is the only caller of slurpReloadCoalesce.
- maxRegWithFormat in GHC.CmmToAsm.Reg.Regs (BUG, ISSUE 27619: Format's
derived Ord compares a VecFormat's number of elements before their
format, ranking VecFormat 16 FmtInt8, 128 bits, above VecFormat 4
FmtDouble, 256 bits): it can keep the narrower of two formats.
Were one register read at both, a write at the narrower would kill
it in minusCoveredRegs, which is wrong code; whether any register
is read so is not known. This rests on master's code read
and ISSUE 27619's record.
The other statements, by part.
The linear allocator:
- Note [The first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, says that the first jump
into a block that the allocator processes records the block's entry
assignment, spilled values included, and that every later jump
conforms to it by fixup code. Its three TODOs are what follows
from that: a loop head recorded from a preheader that spilled
a loop-carried value has the value reloaded on every iteration,
and stored again by every back edge once the body has written it;
a return continuation and the procedure's entry that enter one loop
at two blocks record incompatible assignments (ISSUE 27800);
and the block that a failed heap or stack check returns to
from the garbage collector can be allocated before the hot path's jump
into the checking block and record that block's entry assignment,
as the order of allocation depends on no frequency. process' comment
cites the Note.
- Note [Unique order in the linear allocator],
in GHC.CmmToAsm.Reg.Linear, says, as a TODO, which decisions take
the order of the vregs' uniques as a ranking: the spill victim,
and the order in which saveClobberedTemps moves values out
of clobbered registers. It also says that the order decides
joinToTargets' fixup moves. The comments at those three folds cite it.
- Issues get labels where the code behaves as they report: TODO
for ISSUE 27980, closed as a duplicate of ISSUE 27800,
at findPrefRealReg, for ISSUE 27981 at joinToTargets_first's release
of registers, and for ISSUE 26631 at saveClobberedTemps' choice
of a register; BUG for ISSUE 27638 at handleComponent, makeMove,
makeRegMovementGraph and StackMap's header, whose comments ruled out
a move between two stack slots, which ISSUE 26668 made possible.
- TODOs without an issue: raInsn's elimination of a move gives
the destination the source's register, whatever register an entry
assignment recorded for a block it is live into expects;
findPrefRealReg's preference is keyed by virtual register, while a Cmm
local is one virtual register over all its live ranges; and expandNode
stores a value InBoth at both ends of a jump into the slot
that already holds it.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap says that a stack slot
belongs to one virtual register for the whole procedure,
as getStackSlotFor takes new slots only at the next free one, which
only grows, and a register that outgrows its slot gets another,
keeping the first; that the fixups at a jump rely on this; and
that it costs stack, the slots of a procedure adding up over every
register spilled in it.
- Step (j) of the outline at the top of GHC.CmmToAsm.Reg.Linear,
re-adding a dead spilled register's stack slot to the free list,
is marked WIP: it is not done, as a StackMap never frees a slot.
- A comment at clobberRegs' filter says that frAllocateReg panics
on a register already allocated on AArch64, RISC-V and LoongArch.
- Three designs that a trial on a development branch found no gain
in are recorded beside the code they would change: handing out
the floating-point registers in descending order (at the TODO
for ISSUE 26631 in saveClobberedTemps), taking the entry block first
and then, after each SCC, an SCC holding a block whose entry
assignment is recorded (at the TODO for ISSUE 27800), and putting
fixup moves before an unconditional jump rather than in a block
of their own (in joinToTargets_again).
Liveness, in GHC.CmmToAsm.Reg.Liveness and GHC.CmmToAsm.Reg.Regs:
- The fixpoint of livenessSCCs says that it compares the whole map
at every round (TODO, ISSUE 27437), and that its steps are monotone,
so that a test comparing the formats too would reach a result
independent of the order in which the blocks are walked. Regs' Eq says
that it ignores formats (TODO, ISSUE 27619).
- The comment on the SCCs' order says that no block may fall through
before allocation, and liveDieRead's haddock that at a branch it also
holds the registers live into its targets only.
- A comment at computeLiveness' panic on SCCs out of reverse dependent
order says that, where sccBlocks has a CFG, a jump to a block missing
from the CFG reaches it too.
The graph allocator: in GHC.CmmToAsm.Reg.Graph.SpillCost, a WIP comment
says that the block frequencies scale only the counts of uses
and definitions, on which no spill choice depends, as spillCost_chaitin,
which would read them, is commented out.
Both allocators: a TODO at patchRegsOfInstr says that, as it maps
a register to a register, both allocators reload a spilled value
into a register for an instruction that reads it, even at its last read,
where an x86 instruction could read the stack slot.
Assisted-by: Claude Opus 5.5
- - - - -
dc7ab797 by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
Document bugs and TODOs in code generators, DWARF and an unused module
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- getRegister' in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28126:
isNbitEncodeable 12 admits label offsets from -2048 to 2047, while
check_off in GHC.CmmToAsm.AArch64.Ppr accepts only 0 to 4095):
on AArch64, compiling a label at an offset from -2048 to -1 stops
with check_off's error, a pgmError,
"GHC.CmmToAsm.AArch64.Ppr.check_off : -8 is out of 12 bit"
for an offset of -8. Below -2048 the guard fails, and the next clause
adds the offset through a register. This rests on master's code read
(litToImm', ImmIndex, check_off), ISSUE 28126's record and a run
of master's x86-64 compiler given an AArch64 target description,
in which a Cmm load from a label less 8, at -O0 and at -O,
and plusAddr# of a string literal and -1#, at -O, stop
with check_off's error; nothing was run on AArch64.
- lower_CmmRegOff in GHC.CmmToAsm.Wasm.FromCmm and the cases
for CmmRegOff of getRegister' in GHC.CmmToAsm.RV64.CodeGen
and GHC.CmmToAsm.LA64.CodeGen, one BUG at each (the sum
is not truncated to a sub-word register's width, as each target's
general lowering of a sub-word MO_Add truncates its result,
and cmmMachOpFoldM in GHC.Cmm.Opt folds a sub-word register plus
a literal into a CmmRegOff at any width validOffsetRep allows). Where
an operation reads the bits above the width, this is wrong code:
on wasm32 a widening MO_UU_Conv of a sub-word value masks nothing,
and on RV64 and LA64 Note [Signed arithmetic on RISCV64] and LA64's
comment "Signed arithmetic on LoongArch64" keep a sub-word value
zero-extended between operations. This rests on master's code read
alone; nothing was run on these targets. On RV64 and LA64 an offset
that fits in 12 bits goes to the case of MO_Add for such a literal,
or on RV64 for an offset from -2047 to -1 to that of MO_Sub, which
does not truncate either (on RV64 ISSUE 28133); on RV64 an offset
of -2048 goes to MO_Sub's general case, which truncates.
- getRegister''s case for CmmRegOff in GHC.CmmToAsm.X86.CodeGen (BUG:
neither mangleIndexTree nor add_int narrows the offset
to the register's width, and cmmMachOpFoldM's folds of literals
into a CmmRegOff sum them unnarrowed). For a 16-bit register whose
offset lies outside 16 bits, add_int's LEA, printed as an ADD
of an immediate where the result takes the operand's register, makes
the assembler warn that it shortened the immediate (addw $90000,%ax
for a 16-bit register plus three times 30000); the shortened immediate
gives the value meant, so this costs only the warning, on x86
and x86-64. An 8-bit register's sum takes an ADD whose immediate
litToImm narrows, an LEA printed as an LEA takes the offset
as a 32-bit displacement without a warning, and a wider register holds
any offset add_int is given. This rests on master's code read
(mangleIndexTree, add_code, add_int and the printing of an LEA
as an ADD in GHC.CmmToAsm.X86.Ppr), on master's compiler, whose
assembly for such a sum in Cmm made the assembler warn so, and on GNU
as given addw and leaw with such an immediate and displacement,
with and without --32: it warned of the addw alone and assembled both.
- getHiVirtualRegFromLo in GHC.Platform.Reg, pointed to from localReg64
and getNewReg64 in GHC.CmmToAsm.Monad and from genByteSwap
in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28125: the high half keeps
the number of the low half's unique): a 64-bit Cmm local and a 64-bit
NCG temporary with the same number share their high half, and where
both are live, writing one overwrites the other's high 32 bits.
This is wrong code on i386; 32-bit PowerPC, which uses the same
functions, was not tried. Equal numbers occur, as the NCG's uniques
count from 0 in each Haskell module (initDUniqSupply 'n' 0
in GHC.Driver.Main.Compile). In genByteSwap, equal high halves
with different low halves can arise so, and the branch for that case
swaps correctly. This rests on master's code read and ISSUE 28125's
record.
- verifyBasicBlock in GHC.CmmToAsm.X86.CodeGen (BUG: nothing checks
that a block of native code ends in a transfer of control;
this checks, in a DEBUG compiler, only that nothing but jumps follows
a jump). A block that did not end in one would run on into whichever
block the layout puts after it, which is wrong code; no instruction
selector is known to make such a block. This rests on master's code
read.
- getAmode in GHC.CmmToAsm.X86.CodeGen, three clauses (BUG, ISSUE 28105:
each can emit a displacement outside the signed 32-bit range: -i where
i = -2^31; an offset left unchecked; and an offset checked only
at shift 3, as && binds tighter than ||): where the displacement does
not fit, the x86-64 assembler rejects the module. This rests
on master's code read and ISSUE 28105's record.
- getAmode in GHC.CmmToAsm.X86.CodeGen, its clause for a register offset
plus a shift (BUG: nor is the offset narrowed to the register's
width). On i386 an offset outside 32 bits reaches the assembler, which
warns and shortens it modulo 2^32, to the address meant, so this costs
only the warning; on x86-64 such an offset is the BUG of ISSUE 28105
at the same clause. This rests on master's code read, nothing having
been compiled for i386, and on GNU as given such displacements
with --32, which it shortened with a warning and assembled.
- genPrim in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 27694: MO_UF_Conv's
genWordToFloat does not return the last block it adds, so a later
statement of the same Cmm block that splits its current block in turn,
as a second conversion does, moves the wrong block's edges): the CFG
lacks the edges of the jumps ending the Cmm block, and where
the linear allocator puts a fixup block on one of them,
addNodesBetween panics with "Can't find weight for edge that should
have one", the panic of ISSUE 27915. Where the second conversion's
last block is a lone jump, shortcutting (-fasm-shortcutting,
on at -O2, never on Darwin) cuts it, and shortcutWeightMap drops
its out-edges, which in the CFG are the only edges into the first
conversion's blocks; the blocks stay in the CFG, unreachable
from the entry and with edges, and classifyEdges
in GHC.Data.Graph.Directed, which findBackEdges calls
for optHsPatterns, panics with "Failed to classify edge of CFG -
not not timed" on an edge out of them. Both are reached on x86-64,
the only target for which backendMaintainsCfg holds, and
not under -finfo-table-map, under which no pass after instruction
selection gets a CFG. -dasm-lint does not catch the missing edges
first, as sanityCheckCfg compares the CFG's blocks with the code's
and not its edges. This rests on master's code read, the records
of ISSUE 27694 and ISSUE 27915, a run of master's compiler on a loop
with two word2Double# in one Cmm block: it panics in addNodesBetween
at -O, at -O2 and at -O -dasm-lint, and compiles at -O0
and at -O -fregs-graph, as the graph allocator makes no fixup blocks;
and a run of master's compiler on two word2Double# in one Cmm block
ahead of a loop: it panics in classifyEdges at -O2, at -O2 -dasm-lint,
at -O2 -fregs-graph, at -O1 -fasm-shortcutting
and at -O0 -fasm-shortcutting, and compiles at -O0, at -O1
and at -O2 -fno-asm-shortcutting.
- addDefaultUnwindings in GHC.CmmToAsm.Dwarf (BUG: it gives every
unwinding table that does not name Sp the rule Sp has
at the procedure's entry, and the table that X86's addSpUnwindings
adds where the C stack pointer moves, as around a C call, names MachSp
alone). Up to the next table that names Sp, DWARF gives the canonical
frame address by Sp's rule at entry: after a C call, rbp+0 on x86-64,
where before the call it can be another offset, such as rbp+16.
A debugger unwinding from there finds the wrong frame. This is reached
under -g on ELF targets, on x86 and x86-64, as ncgDwarfUnwindings
holds on ELF targets under -g and addSpUnwindings is X86's. This rests
on master's code read and on readelf's reading of the frame table
of an object that master's compiler made under -g.
The other statements:
- backendMaintainsCfg in GHC.CmmToAsm.BlockLayout said that i386 should
work but is untested. It now says, as WIP, that i386 is left out
because it is untested and its iselExpr64 splits blocks for 64-bit
shifts without adding them to the CFG.
- genPrim's comment says that its remaining cases add no blocks, while
MO_UF_Conv's genWordToFloat adds blocks: the BUG above stands there.
- mkRegRegMoveInstr in GHC.CmmToAsm.X86.Instr says that its move clears
the upper part of the register. A TODO says that for a float
or a double it is MOV FF64, printed movsd, which keeps
the destination's upper half.
- invertCondBranches inverts a jump only after an integer comparison.
A TODO says that maybeInvertCond's complement on the flags is as sound
after a floating-point one.
- pprBasicBlock in GHC.CmmToAsm.X86.Ppr aligns, past a procedure's
start, only a block with an info table (TODO, ISSUE 27668).
- condIntCode' tests a value against zero even on a path where
the instruction computing it has set ZF and SF from it, as on the back
edge of a loop that counts down: it sees only the comparison,
and another path into the test, such as the loop's entry, may set
no flags. Only a condition that reads ZF and SF alone could use
the flags of a dec, which writes OF and leaves CF where TEST clears
both (TODO, ISSUE 27738).
- GHC.CmmToAsm.Reg.Graph.Coalesce says, as a TODO, that no module
imports it, and that its pass, which ran before allocation, has had
no caller since 2007, when it was taken out of the pipeline in favour
of the coalescing that GHC.Data.Graph.Color.colorGraph does.
Assisted-by: Claude Opus 5.5
- - - - -
fe8e80d0 by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
State the NCG's norms and where a branch's likely side is known
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Norms of the NCG], in GHC.CmmToAsm, states two norms that GHC's
own documents and testsuite hold the native code generator to, and what
each means for a change. Under -fobject-determinism the output
is bit-for-bit the same for the same inputs, so an order taken
from uniques is a question for review. The testsuite passes -dcmm-lint
by default, so a test written in Cmm must be one that Cmm lint accepts.
Note [Where a branch's likely side is known], in GHC.CmmToAsm.CFG, says
where the code generator learns which side of a conditional branch
is likely: where the branch is made, as for heap and stack checks;
upstream, and not carried down, for constructor-tag tests; and nowhere,
for the rest, to which static prediction applies its heuristics. It also
states the trade-offs kept with that knowledge, each with its reason:
conditions inverted so that the true side falls through even where
the false side is likely, and edges across calls left out when chains
are built and when neighbouring chains are combined.
Note [Norms of the NCG] points to it.
Assisted-by: Claude Opus 5.5
- - - - -
c4dfbac9 by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
Rewrite the NCG's overview Note
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe.", "Which targets go
through the NCG, which of its parts each target uses, and what the NCG
takes from the Cmm pipeline, StgToCmm and the RTS.", "The NCG's passes
in the order they run, and what each requires of the one before.",
"The invariants the code depends on." and "What the tests cover and what
they do not: which targets CI runs natively, which paths have few
or no tests, and which performance test exercises which pass."
Comments only; the generated code is the same.
Note [Native code generator], the module header of GHC.CmmToAsm, named
CmmStmts, cmmCodeGen, targetDoubleSize and smStablePtrTable, which
no longer exist, and machine-independent optimisations "defined below",
which are in GHC.Cmm.GenericOpt. This commit rewrites it. The Note now
says:
- which targets go through cmmNativeGen, that wasm32 has a generator
of its own, and which back end the other targets get by default;
- what the Cmm pipeline hands over, and what the NCG takes from StgToCmm
and the RTS;
- the interfaces through which the machine-independent parts access
a target, and what only some targets have;
- the passes, in the order cmmNativeGen runs them, with the flags
that turn them on and the dump flags that show their output, and,
at step 4, what instruction selection must ensure;
- where the NCG's uniques come from;
- what the assembler and the linker do after it;
- the flags, testsuite directories and benchmarks for working
on the NCG.
For detail it cites the Notes and labelled statements of the preceding
commits.
Assisted-by: Claude Opus 5.5
- - - - -
7626094c by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
Propose two principles for the NCG
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Proposed principles of the NCG], in GHC.CmmToAsm, puts two
principles to GHC's developers and says that the native code generator
does not keep them yet:
- correctness first: semantic correctness is not traded for a measured
gain that an incorrect form gives by accident, until a form with both
has been looked for and the trade agreed in review;
- one TODO set: a departure from correctness that is left in place
is marked TODO, as a member of one set that is accepted for now
and re-investigated together.
No other commit cites the Note, so this commit can be dropped
on its own.
Assisted-by: Claude Opus 5.5
- - - - -
8c411224 by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
Add a README to the NCG's directory
Of what anyone working with the NCG needs, this commit serves "An order
in which to read the NCG's Notes.", "One place where the terms the NCG's
comments use are defined.", "One small function followed through
the NCG's dumps, in the order of its passes.", "Which parts of the NCG
were examined for bugs, half-done work and likely changes, and which
were not.", "The invariants the code depends on." and "How to find
the pass at fault for a miscompilation or a compiler panic, and how
to reduce the case to a Cmm test."
Documentation only; the generated code is the same.
compiler/GHC/CmmToAsm/README.md is a way in for anyone working
with the native code generator, whether reading its output and dumps,
tracking a fault to its pass, reviewing or making a change,
or maintaining it. It says what to read and what to do, and for each
fact about the code it cites a Note or a comment by name. Its sections:
- Where to start reading: three Notes of GHC.CmmToAsm, then Notes
on the passes, each with its module, in the overview's order.
- Vocabulary: the terms the NCG's comments use without defining them,
each with where it is defined or used.
- Finding the pass at fault for a wrong result or a panic: the oracles
to compare with, the flags that switch a pass off or swap it,
the lints, and how to cut a case down to a Cmm test.
- One function through the dumps: a small loop compiled at -O on x86-64,
with an excerpt for each dump flag in the overview's list of passes
but -ddump-asm-regalloc-stages, which prints nothing under the linear
allocator.
- Reviewing a change: the invariants the code depends on, as questions
by kind of change, each citing the Note or comment that states it.
- What the labelled statements cover: which parts of the NCG they
were first written from, and which were left out.
The excerpts are cut from the dumps of one compilation by a compiler
built from master: each of their lines but "..." is a line of a dump,
in the dump's order, with tabs replaced by spaces. Every Note, function,
module, flag and path the README names exists at this commit.
The overview, Note [Native code generator], now ends by pointing
to the README.
Assisted-by: Claude Opus 5.5
- - - - -
ba007117 by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
rts: run finalizers soon after the GC that finds them
scheduleFinalizers puts the finalizer thread at the end of the run
queue, and the thread whose heap overflow caused the GC goes back
to its front unless a context switch is pending. So under the RTS timer
the finalizers wait for the next context switch, 20 ms by default,
and whatever they would free stays live until then: a program that opens
and closes handles fast keeps every closed handle's buffers. nofib's
maillist, which appends to its output a line at a time, peaks at 16.6 MB
of residency where -V0 and -C0, whose scheduler switches whenever
another thread is runnable, keep 1.65 MB.
Request a context switch when scheduling the finalizers, so that they
run at the next block boundary. maillist then keeps 1.65 MB
under the default timer and runs 13.4% fewer instructions at -O2, 12.7%
at -O1 and 12.6% built at -O0. Across nofib, cacheprof runs 0.80% more
at -O2 and 0.96% at -O1, as it does under -V0: run promptly,
the finalizers lower the residency (cacheprof's peak 0.82 MB against
0.89 MB), so the major GCs, triggered by the old generation's size
against the live data, come more often (cacheprof's 148 against 143
at -O2). Built at -O0, gg runs 0.26% more and treejoin 0.46% fewer;
no other program moves by 0.2% beyond its run-to-run noise.
Figures of variants not taken were measured on earlier forms
of the series.
Fixes ISSUE 28060.
Assisted-by: Claude Opus 5.5
- - - - -
77cb8da1 by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
Address a register offset directly in x86's getAmode
getAmode made the mode of CmmRegOff r n by mangleIndexTree r n, building
the sum r + n for the alternative of x + lit to take apart. It now gives
that alternative's mode, r's register with the offset n, directly,
under the same guard, is32BitLit of n at r's width, and where r
is not PicBaseReg; the other cases go to the mangled sum as before.
For the PicBaseReg condition isPicReg moves from GHC.Cmm.Opt, which did
not export it, to GHC.Cmm.Utils, which exports it and which x86's code
generator imports already. The code generated is the same.
Measured against its parent: nofib's objects are the same size,
as are containers', megaparsec's, vector's and A2T's, and the stage-1
compiler, built by GHC 9.12.4, runs 1.6% fewer instructions compiling
T3294 at -O0, 0.65% at -O and 0.64% at -O2; 0.56%, 0.19% and 0.17% fewer
compiling T12707; and 0.29% and 0.31% fewer compiling T9961 and T783
at -O0. The stage-2 compiler runs 0.090%, 0.065% and 0.11% fewer
compiling nofib's puzzle at -O0, -O1 and -O2, and 0.099% fewer compiling
nofib's programs at -O0 and 0.035% and 0.047% fewer at -O1 and -O2,
geometric means.
The test cmm_regoff loads and stores at q + k for offsets k on both
sides of the 32-bit displacement bounds, q passed as p - k so that
each access is at a known address.
Assisted-by: Claude Opus 5.5
- - - - -
756d0c3d by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
Gather a Cmm sum's literals into one constant, and narrow != as ==
To move into a merge request of its own, together with "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant", "Assign literals after computed values
at the end of a block" and "Drop the assignments that only a discarded
assignment read".
GHC.Cmm.Opt's special case (a - b) + c ==> a + (c - b) fired whatever b
and c were, and where c - b could not fold it put a literal on the left
of a subtraction, which x86 cannot encode as an immediate: containers'
Set.elemAt, at -O2, computed i + ((-1) - s) for its right step, a mov,
a sub and an add where a sub and a dec do. The reassociation (a + b) - c
==> a + (b - c) had the same flaw where b is a literal and c is not,
turning (x * y + 1) - w into x * y + (1 - w). This commit gathers such
sums into one normal form, which x86's code generator now computes
by one LEA or addressing mode (add_int, getAmode); and it narrows !=
against a literal, as ==, and a comparison of two operands widened
alike.
cmmMachOpFold now puts an addition or subtraction at one width
into the form of Note [Additive normal form] in GHC.Cmm.Opt,
its literals summed into one constant: e + k, k - e or e, a difference
e - k being left as it is where e has no constant. This takes the place
of the reassociations of (a + b) - c and (a - b) + c, and that of (a +
b) + c no longer moves a literal c from the top.
That reassociation, (a + b) + c ==> a + (b + c) where c is no literal,
is master's, and reassocAdd now does it: where a is neither a literal,
a register offset nor a MachOp and the folded b + c is a sum at the same
width whose right operand is no literal, it builds a + (b + c)
as it stands, since cmmMachOpFold would return that sum unchanged,
and it folds every other step by cmmMachOpFold, as master's code does.
A left-nested sum of n terms still takes n(n-1)/2 steps to become
right-nested, as in master's reassociation; each step is now cheaper.
The x86 code generator takes the sums left this way into one LEA:
add_int computes (a + b) + k as the address of that form and (a - b) + k
as (a + k) - b, and getAmode makes a complex addressing mode of (a +
b) + k and of (a + (b << s)) + k, and of the same forms less k. One
function, x86_offset_amode, makes these modes and add_int's address
of (a + b) + k: master's clauses of getAmode for x + lit and x - lit
and add_int's default alternative, master's LEA of x's register and k,
now share it. Master's clauses below them that take a shift stay, each
still reached: x + (y << s) by a sum with no literal, the swap
of a shift and a literal by a literal that is no 32-bit displacement,
and, where nothing folds, as at -O with -fno-cmm-sink, (x + k) + (y <<
s) for a register x by array indexing and x + ((y << s) + k)
by hand-written Cmm. Master's getRegister' now makes the LEA
of a register offset r + n directly, as add_int makes it of the sum
mangleIndexTree builds, without building the sum, where r is wider
than 16 bits. It leaves W8, which LEA does not take, and W16
to mangleIndexTree and add_int, which narrows n to r's width: at W16 n,
which cmmMachOpFoldM's folds of literals into a register offset leave
unnarrowed, can be wider than r, and the LEA, printed as an ADD
of an immediate where its result takes r's register, makes the assembler
warn that it shortened the immediate (addw $90000,%ax for a 16-bit x
plus three times 30000), as compiling the same with master's compiler
does. The BUG statement at getRegister''s case for CmmRegOff, which said
that a 16-bit register offset reached the assembler unnarrowed,
is deleted. Measured at the series' end against the clause taking W16,
nofib's assembly at -O1 and -O2 and that of the compile cells T3294,
T12707, T783, T9961 and ManyBasicBlocks is the same, and no cell rises
by 0.001% in instructions or allocation; narrowing n in the clause
itself instead, through Integer, made the cells rise by up to 0.088%
in instructions and 0.115% in allocation (ManyBasicBlocks at -O0).
The narrowing that compares a widened operand with a literal
at the operand's width listed MO_Eq but not MO_Ne, so a byte widened
to a word was tested with != after a zero extension; MO_Ne is added
beside MO_Eq. A comparison of two operands widened alike, from the same
width and both by zero extension or both by sign extension, is now done
at that width as well, under the literal case's rule for signedness
(ISSUE 2080), its tables moved to the top level to serve both. Vector's
awshcc and nofib's reverse-complement, lambda and parser gain where !=
is narrowed like ==, and the boot libraries' comparisons of two operands
widened alike, in text, bytestring and ghc-internal's eqWord32,
are narrowed too, containers running fewer instructions by them.
Gathering a sum's literals can fold a negative constant into a label's
offset, as master's own fold of a label less a literal does. AArch64's
code generator loaded a label at an offset fitting 12 signed bits
by an add whose immediate is unsigned, so an offset such as -8 made
its printer's check_off stop the compilation with an error; a negative
offset now takes the general path, which adds the offset
from a register. That is the fault ISSUE 28126 reports, so this commit
should fix it; the issue's test, which MR 16994 adds as expected broken
on AArch64, has not been run with it.
The tests cmm_fold_lit (Cmm, the reassociations and the narrowing)
and cmm_fold_elemAt (Haskell at -O2, Set.elemAt's step) fail without
these changes, and cmm_addnf compares each shape over boundary values
with the same formula computed in Haskell. cmm_fold_lit is skipped where
the word is 32 bits, where -dcmm-lint, which the testsuite passes
by default, rejects its assignments of a byte widened by %zx64 to a W_;
nothing was run on a 32-bit target. CmmRegOffW16, on x86-64 only,
compiles a 16-bit register plus three constants whose sum does not fit
16 bits, returned and assigned; the assembler's warning on its stderr
is its failure, and through the testsuite's driver, at the series' end,
it fails so with the clause taking W16 and passes without.
Measured against its parent: nofib's programs run 0.22% and 0.21% fewer
instructions at -O2 and -O1 and 0.079% fewer at -O0 (geometric means),
spectral-norm 11.8% fewer at -O2 and -O1, allocating the same;
containers' benchmarks run 0.26% and 0.24% fewer instructions at -O2
and -O1, megaparsec's 0.89% and 0.83% and vector's 0.61% and 0.60%.
The stage-1 compiler runs 2.3%, 1.8% and 1.8% fewer instructions
compiling MR 16269's CmmDiamondChain at -O0, -O1 and -O2, and at most
0.001% more on any compilation of T3294, T12707, T783 and T9961.
Compiling a Cmm procedure that rotates N locals in a loop and returns
their sum at -O1, it runs 0.991, 0.974, 0.940 and 0.898 times
the instructions at N = 50, 100, 200 and 400.
Compiled by the boot compiler, GHC 9.12.4, GHC.Cmm.Opt allocates 49%
more (2.040 against 1.369 GB), the cost of addNormalise's own code;
at the series' top it allocates 1.96 GB, 43% more than master's.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
42c5ef4a by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Address (i << s) + lit on x86 by a scaled index with no base
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Take
the constant out of a shifted or scaled sum in Cmm's sums", "Fold
cmmOffset's offset into any sum with a constant", "Assign literals after
computed values at the end of a block" and "Drop the assignments
that only a discarded assignment read".
x86's getAmode took (i << s) + lit, the address of an entry of a closure
table, which tagToEnum# and a derived Enum's toEnum, succ and pred load,
by its default branch: the shift computed into a register, which became
the base, and lit the displacement, as shlq $3,%rax then movq
tbl(%rax),%rbx. Its clause for x + lit, which takes every literal
a displacement holds (is32BitLit), now takes such an x, s at most 3,
as an index scaled by 2^s with no base register and lit
the displacement, movq tbl(,%rax,8),%rbx, with the default branch's
relocation. The clause takes it by x86_offset_amode, the function
it shares with master's clause for x - lit and add_int's default
alternative, so add_int takes the value (x << s) + k into the same LEA,
and an address (j << s) - k, s at most 3, is made the same way, one
instruction shorter. The clause for (a << n) + lit stays,
for the literals x + lit does not take: a label on Windows (Note
[%rip-relative addressing on x86-64]) and an integer or a label's offset
wider than 32 bits, but gives the sum to x86_complex_amode itself, lit
the base, rather than turning it around; its comment says so. Master's
x86_complex_amode now takes the index term and finds the scale itself, i
<< s for s at most 3 scaled by 2^s and any other index unscaled,
so master's clause for x + (y << s) is deleted, the clause for x + y
making the same mode of such a sum. Under -fPIC and -dynamic a table's
label reaches getAmode as PicBaseReg plus the label or as a load
from the GOT, except on Windows, where it is a literal that x + lit does
not take, so those loads are unchanged.
Measured against its parent: nofib's programs run 0.033%, 0.029%
and 0.19% fewer instructions at -O2, -O1 and -O0 (geometric means),
at -O2 CSD 0.52% fewer, cryptarithm2 0.49%, ansi 0.42%, puzzle 0.35%
and cichelli 0.32%, none more by 0.2%, the geometric means of their
allocation unchanged; containers' benchmarks run 0.010% and 0.012% fewer
at -O2 and -O1, IntSet's eq 1.1% and spanAntitone of IntSet and IntMap
1.0% fewer, and vector's 0.086% and 0.082% fewer, findIndexR 1.7%
and 1.6%; megaparsec's geometric means fall by 0.039% and 0.038%
and A2T's sample runs 0.004% fewer, none of their benchmarks rising.
The stage-1 compiler runs at most 0.002% more instructions compiling
T3294, T12707, T783, T9961 and ManyBasicBlocks, and its allocation moves
by 0.003% or less.
The test cmm_scaledlit loads and stores at (i << s) + lbl for s from 0
to 3 and lbl plus or minus 8, and computes (x << s) + k at 64, 32, 16
and 8 bits for s from 0 to 4, with k small or at a bound of 32 bits
or of a narrower width, and at 64 bits past the 32-bit bounds, comparing
each with the same formula computed in Haskell; ClosureTblAmode checks
that tagToEnum#'s closure table is addressed with no base register,
and is skipped on Windows and where code is position-independent
by default.
Assisted-by: Claude Opus 5.5
- - - - -
496e20c0 by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Take the constant out of a shifted or scaled sum in Cmm's sums
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Fold cmmOffset's
offset into any sum with a constant", "Assign literals after computed
values at the end of a block" and "Drop the assignments that only
a discarded assignment read".
The additive normal form (Note [Additive normal form] in GHC.Cmm.Opt)
gathered the constants of an addition's operands only where an operand
was a sum, a difference, a register offset or a literal, so p + ((i + 1)
<< 3), the element after i of an array, kept its constant inside
the shift, and x86 computed i + 1 and the shift before loading. addView
now views an operand (e + k) << s or (e + k) * c at width w, k
an integer and s < w, as the term e << s or e * c with the constant k <<
s or k * c, the product distributing over the sum modulo 2^w, where
that constant narrowed to w fits in 32 bits; the old view is sumView.
p + ((i + 1) << 3) becomes (p + (i << 3)) + 8, one address of x86's
getAmode, and the closure table entry ((t - 1) << 3) + lbl becomes (t
<< 3) + (lbl - 8), with one label literal. Left as they are: (k - e) <<
s, whose term e << s would be subtracted, which no x86 address does,
while p + ((1 - j) << 3) + 24, an element of an array in nofib's fem,
gamteb and puzzle, is one address; and a constant wider than 32 bits,
which x86 would move into a register where k cost nothing, as in (x + 1)
<< 40.
Measured against its parent: nofib's CSD runs 0.78% and scs 0.21% fewer
instructions at -O2 and -O1, and built at -O0 dom-lt, n-body, kahan
and fannkuch-redux run 0.60% to 0.69% fewer and others by less,
no program more by 0.2%, the geometric means 0.012%, 0.013% and 0.066%
lower at -O2, -O1 and -O0; vector's benchmarks run 0.12% fewer at -O2
and -O1, nextPermutation and prevPermutation of a small vector 1.8%,
and A2T's sample 0.016% fewer, none of its cells more by 0.2%;
containers' and megaparsec's geometric means move by 0.007% or less;
allocation is unchanged in the packages' benchmarks and moves by 0.037%
or less in nofib's programs and A2T's cells. The stage-1 compiler's
instructions and allocation compiling T3294, T12707, T783, T9961
and ManyBasicBlocks change by 0.003% or less, and the stage-2 compiler's
allocation compiling nofib's programs moves by 0.001% or less at -O2,
-O1 and -O0 (geometric means).
The test cmm_fold_scaled checks in the Cmm dump p + ((i + 1) << 3), q +
(i + 2) * 24 and the two shapes left as they are, and cmm_addnf now also
computes such shifts and products as operands of additions
and subtractions, and loads at them, comparing each with the same
formula computed in Haskell. cmm_fold_scaled is skipped where the word
is 32 bits, where cmmMachOpFoldM folds (i + 1) << 40 to 0, i being 32
bits wide, and i386 passes no argument in the R2 it names; nothing
was run on a 32-bit target.
Assisted-by: Claude Opus 5.5
- - - - -
d13b40e4 by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Fold cmmOffset's offset into any sum with a constant
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Assign literals after
computed values at the end of a block" and "Drop the assignments
that only a discarded assignment read".
cmmOffset summed its offset into a MachOp only of the form e + k
and wrapped any other MachOp in a new addition, folding nothing. Sink's
inl_exp inlines a local's value into a register offset l + n
by cmmOffset, so that (e - 1) + 1 was left as it is: with Sink on,
the NCG never folds, ncgDoConstantFolding being not (gopt
Opt_CoreConstantFolding dflags || gopt Opt_CmmSink dflags). cmmOffset
now reads a MachOp through the additive normal form's own view, addView,
moved with sumView and their types from GHC.Cmm.Opt to GHC.Cmm.Utils,
and adds the offset to the constant of e + k, e - k and k - e alike:
a sum whose constant cancels becomes its term, a register plus
a constant a register offset. Every caller gets it, the NCG's jump-table
index among them. cmmOffset reads the view only of an addition
or a subtraction, never of the shift or product that addView takes
apart, so a local (e + k) << s inlined into an offset stays ((e + k) <<
s) + n, as before. Master's mkRODataLits tests its literals
by isLabelLit in place of its local needsRelocation.
At -O1 and -O2 a derived Enum's succ and pred each lose one instruction,
in nofib's puzzle and ben-raytrace and in ansi-terminal-types,
and dataToTag# x plus or minus a literal loses one; every other object
of nofib's programs at -O0, -O1 and -O2, of containers', megaparsec's
and vector's benchmarks at -O1 and -O2 and of their dependencies stays
the same size, and the instruction counts of puzzle and ben-raytrace
move by 0.0006% or less. The stage-1 compiler's instructions
and allocation compiling T3294, T12707, T783, T9961 and ManyBasicBlocks
change by 0.002% or less, and the stage-2 compiler's allocation
compiling nofib's programs moves by 0.001% or less (geometric means)
and by 0.025% or less in any program. Compiled by the boot compiler, GHC
9.12.4, GHC.Cmm.Utils allocates 40% more (1.066 against 0.760 GB),
sumView inlined into addView, and GHC.Cmm.Opt 11% less (1.955 against
2.208 GB); at the series' top Utils allocates 1.07 GB, about two fifths
again master's.
The test cmm_sinkoff sinks such values into an offset at 64, 32 and 8
bits, its constants at the wrap boundaries, and compares each
with the same formula computed in Haskell; cmm_swoff switches on e - k
and k - e at 64 and 32 bits over jump tables whose range starts at 100.
EnumTagOffset greps the assembly of a constructor's index plus 3 and
minus 1, and of the next and the previous constructor loaded from its
closure table: the - 1 that takes the index from the pointer's tag folds
into the literal and into the table's displacement, where the parent
commit's compiler subtracts it by an instruction of its own in each of
the four.
Assisted-by: Claude Opus 5.5
- - - - -
20f0c0ec by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Predict an inequality with a literal in static branch prediction
ohPredicts, static branch prediction's opcode heuristic, predicts
that a comparison with a literal is unlikely to come out equal,
but it matched only MO_Eq. The control-flow optimisation turns
an equality into an inequality where that lets the test's true side fall
through (Note [Invert Cmm conditionals] in GHC.Cmm.ContFlowOpt),
and so spelt the same test went unpredicted, its two sides weighted
alike. ohPredicts now predicts the true side of an inequality
with a literal (0.7), as it predicts the false side of an equality,
except where an operand is masked by MO_And, as in a pointer tag test,
(x & 7) != 0, or a test of a bitmap's bits, or is a constructor tag: one
read from an info table, an unboxed sum's, a local register every
assignment to which is a tag, which a pass over the procedure's Cmm
finds, or one less than such a register. Whether those bits are set,
or which constructor a tag names, depends on the type or the data, which
the CFG does not record, so a test of a constructor tag is predicted
as before (Note [Static prediction of tag tests]). That pass
and ohPredicts take one less than a tag register in both its spellings,
CmmRegOff r (-1), as the sink leaves dataToTagLarge#'s r - 1 at -O1
and -O2, and the subtraction of 1, which stays under -fno-cmm-sink.
Predicting every inequality made containers' benchmarks take up to 3.1%
more instructions, through the tag tests of tree lookups; leaving out
only pointer tag tests, intmap fromSet took 1.3% to 1.8% more, through
buildTree's bitmap test.
The pass, tagRegisters, counts an unsafe foreign call's results among
a register's assignments, in a second pass over the blocks made only
where there is a candidate; no other node assigns a local register
in the code generator's input, a safe call being lowered to unsafe ones
before. It drops each candidate assigned a copy of a register that holds
no tag, or one less than such a register, once, and with
it the candidates assigned from it in turn, through a map
from a register to those (tagSource) built only where a candidate
is dropped: filtering all the candidates again until a pass dropped none
took time quadratic in the length of a chain of copies. Measured
at the series' end, each against the code without it: in a Cmm procedure
assigning r = n & 7 in one arm and (r) = ccall labs(n) in the other,
then testing r != 3, the test's edges were weighted 0.5 each without
the count of the call's result and are 0.7 and 0.3 with it;
in a procedure of N if-else diamonds in sequence, the k-th assigning xk
a copy of x(k-1) in one arm and x(k-1) & 7 in the other, then testing xN
!= 3, the compiler ran 30015211 and 2009023957 more instructions at -O1
than with the test xN > 3, for which the tag registers are not computed,
at N = 400 and 3200 (where the whole compile took 3346781123), and runs
3224188 and 33084927 more. With either change nofib's modules compile
to the same assembly at -O1 and -O2, and each compile cell stays within
0.01% of the allocation and 0.005% of the instructions it took before.
What this removes is a tie. In megaparsec's sepEndBy loop, a cold
continuation's edge into the loop's second head weighs as much
as the hot edge into it once "Hand calcFreqs a procedure's loops inner
first" estimates them, because the test before them, written as != 0,
is estimated 50/50; the tie gives the cold block the fall-through,
and every element a jump. With this commit the hot edge is the heavier
one.
The trade is k-nucleotide's hash table lookup: the exits of its bucket
loop, written as tests for zero, come out as != 0 and are now predicted
to stay in the loop, so that with the loop-exit heuristic the loop's
back edge outweighs its entry; block layout gives the back edge
the head's fall-through, and every first probe, which finds its key
about 95% of the time, pays a jump. The commit that lets a loop's back
edge outrank its entry makes this layout anyway. The gains include
containers' intmap compareSize:n (3.4% fewer instructions) and nubOrd
issue1202_repeat (0.89% fewer at -O1), and megaparsec's endBy (0.60%
to 0.64% fewer at -O2).
As a TODO at ohPredicts records, the exception goes by an operand's
form, not by what decides the test: a parity test, its mask inside
arithmetic, is predicted, and an evaluation test, (x & 7) != 0, is left
out with the constructor-tag tests; predicting evaluation tests
as evaluated, in either spelling, cost nofib 0.36% more instructions.
Leaving out as well parity tests, x `rem` 2^p, also as GHC.Cmm.Opt
rewrites it, x - ((x + c) & -2^p), and masks under a conversion, a shift
or the addition of a literal, leaves unpredicted 8 of the 1685
inequalities with a literal predicted in nofib at -O1 and 8 of 2282
at -O2, 220 of 21354 in the boot libraries and the ghc library
and at most 7 in each build of containers', megaparsec's and vector's
benchmarks. It moves nofib's programs by less than 0.06%
in instructions, the benchmarks of containers, megaparsec and vector
within the spread of their runs or by at most 0.016%, the cells
of orthotope's A2T benchmark by less than 0.1%, and the compiler's
instructions by at most 0.001% compiling perf/compiler's T3294, T12707,
T783 and T9961, its allocation not at all.
Measured against the parent commit, in instructions: nofib's programs
move by 0.003% or less at every level, in geometric mean, k-nucleotide
taking 0.46% more at -O2 and 0.26% at -O1; containers' benchmarks move
by 0.004% or less at both levels, the compareSize:2 rows of intmap
and intset and intset's deleteMax taking one instruction a call more;
megaparsec's take 0.028% fewer at -O2 and 0.023% at -O1; vector's move
by 0.005% or less; in orthotope's A2T benchmark maximumA.one over small
strided arrays takes two instructions a call more (0.4% to 0.6%),
and many of its cells take 0.2% to 0.4% fewer, both by a jump
in absAxesAndStartT: of the two return blocks that run back into the tag
test at its head, the layout now places before the test the one most
cells take, and maximumA.one's strided cells take the other.
No benchmark's allocation moves by 0.05% but k-nucleotide's, 0.16% more
at -O2 and 0.060% less at -O1; the compiler allocates at most 0.022%
more compiling perf/compiler's T3294, T12707, T783 and T9961.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
f7ed0249 by Mikolaj Konarski at 2026-11-20T00:12:56+01:00
Find a CFG's back edges by one depth-first search
findBackEdges classified every edge of the CFG (classifyEdges, which
timestamps the visits of a depth-first search from the entry) to find
the few that lead back to a block on the search's path. optHsPatterns
calls it on every procedure, at every optimisation level, to give back
edges their bonus. findBackEdges is now that depth-first search itself:
it visits the successors in the same order and collects, as it goes,
the edges into a block still on its stack, leaving out an edge
from a block to itself, which classifyEdges calls a self loop rather
than a back edge. classifyEdges and its EdgeType,
in GHC.Data.Graph.Directed, had no other user and are gone.
The generated code is the same: the assembly of perf/compiler's T3294,
T12707, T783 and T9961 at -O0 and -O, and the object code of nofib's
programs at -O2, are the parent's. The stage-1 compiler allocates 0.19%
less compiling T3294 at -O0, 0.74% less compiling T12707, 0.97% less
compiling T783 and 0.97% less compiling T9961; at -O, 0.32% less
compiling T12707 and 0.25% less compiling T783; and the stage-2
compiler, compiling nofib's programs at -O2, 0.23% less in geometric
mean and up to 0.39% less (real/compress2). Compiling MR 16269's
CmmDiamondChain at -O1 and -O2, the stage-1 compiler allocates 0.19%
less.
Assisted-by: Claude Opus 5.5
- - - - -
079c10cc by Mikolaj Konarski at 2026-11-20T00:12:56+01:00
Drop jumps over blocks dropJumps empties
dropJumps removes a block's last jump where it can fall through
to the next block, and a jump-only block it so empties stays as a label,
so that a jump over it to the block after is left as a jump to the next
instruction (x86-64's eb 00, which master's intmap benchmarks at -O1
carry). It now looks past the blocks that hold no code or that it leaves
holding none, by a fold from the end over the blocks it has already
processed, among which a block it leaves without code holds none
already. Looking ahead over the blocks still to process instead,
as first written, took time exponential in a run of blocks holding one
jump each; the fold builds the whole list before returning its first
block, and the compiler allocates 0.081% more compiling perf/compiler's
T783 at -O0 than with that look-ahead.
A block holding no code is one with no info table that holds only meta
instructions or none: under -g a block whose jump the layout dropped
keeps its unwinding information, and without -g the only meta
instruction a block can hold is the comment that GHC.Cmm.GenericOpt
makes of an assignment of a register to itself. The test is a function
of its own beside dropJumps, fallsTo: it succeeds at a block whose label
satisfies a predicate, passes over a block holding no code, and fails
elsewhere. Its first argument is the meta test, for a code generator
where the Instruction instance is not in scope; dropJumps passes
the class's isMetaInstr, and as the predicate canFallthroughTo where
the label has no info table.
dropJumps, master's function, is generic over the backends,
so this changes it on every backend. On x86-64 isMetaInstr holds only
of instructions that emit no code, and a jump over a block whose own
jump dropJumps dropped is dropped under -g as without it. On AArch64,
RV64 and LA64 isMetaInstr holds of PUSH_STACK_FRAME and POP_STACK_FRAME
too, which emit code, so there dropJumps rests on no block holding only
those: their code generators emit the two only around a C call, in one
sequence with the call, which nothing checks, and none of the three
backends was built for this change.
Measured against its parent: built at -O1, containers' intset folds
over sparse sets run 1.6% (foldr_elem) and 0.90% (foldl_elem) fewer
instructions and intmap's fromSetA 0.49% to 1.4% fewer, the geometric
mean 0.006% lower, and no benchmark rises; at -O2 containers' benchmarks
neither rise nor fall. nofib's programs move by less than 0.2% at every
level, and their geometric means, megaparsec's and vector's by 0.003%
or less; no cell of A2T's sample moves by 0.1%. The assembly of T3294,
T12707, T783, T9961 and ManyBasicBlocks is the parent's, and the stage-1
compiler runs at most 0.032% more instructions compiling them (T783
at -O0) and allocates up to 0.050% less (T9961 at -O0) and up to 0.035%
more (T783 at -O0).
fallsTo tests a block's instructions before it looks the block up
in the map of info tables, dropJumps' predicate looks the label up only
where the jump can fall to it, and dropJumps binds isMetaInstr strictly;
the comments there say what each other choice cost. Measured
at the series' end, against it with dropJumps passing only over blocks
with no instructions and with the x86-64 code generator's later tests
of the same question as functions of their own: at -O1 with -g nofib's
code changes in some procedures of ben-raytrace, cacheprof, fem, fluid,
hidden, scs, smallpt, minimax and simple, some losing a jump, the others
placing their blocks otherwise; several now equal their code without -g,
and none that equalled it differs. At -O2 with -g nothing changes,
nor does nofib's assembly without -g at -O1 and -O2; the code
of a constructed procedure at -O0 with a block holding only that comment
changes. The compiler runs 0.008% fewer instructions compiling T9961
at -O0, 0.052% fewer compiling T783 there and 0.010% fewer compiling
ManyBasicBlocks at -O1 and -O2, and allocates at most 0.002% more,
compiling T9961 at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
a58e1b1c by Mikolaj Konarski at 2026-11-20T00:12:57+01:00
Let a loop's back edge outrank its entry in block layout
sequenceChain lays the blocks out by fusing chains along the heaviest
edges first, by the final edge weights. Under -fcmm-static-pred,
on at -O1 and -O2, those are the frequencies static prediction
estimates, which can rate a loop's back edge below its entry: where
the branch that decides whether the loop goes on has no back edge among
its targets, the other heuristics predict it, and they can predict
staying in the loop to be unlikely, as in a lookup down a tree (Note
[Static prediction of tag tests]). The entry then falls through
into the loop's head, and every iteration pays a jump back.
optHsPatterns gives back edges a bonus (increaseBackEdgeWeight),
but static prediction replaces the weights of the branches
its heuristics cover with its predictions, so that the bonus counts only
at those it leaves alone, a heap or stack check's and those whose
targets are all back edges, and at a two-way branch back
into the procedure's entry, whose weights static prediction starts from.
sequenceChain now raises (preferBackEdges) each back edge by a little
more than the weight of the heaviest edge into its head that is
not a call, a back edge or a self loop, which keeps the order of several
back edges into one head; Note [Layout relevant edge weights]. A back
edge out of a jump table is not raised: it cannot fall through,
so raising it would only take the head's fall-through from an edge
that can. Nor is a back edge out of a block with another successor:
that block executes its branch whichever successor falls through,
so falling through saves nothing an iteration, while every entry pays
a jump; leaving such edges out takes 1.55% off intset folds:sparse
foldr_elem and 0.78% off foldl_elem, and 6.4% off folds:dense
foldl'_maximum, at -O2. preferBackEdges takes the back edges
from findBackEdges, now exported.
The garbage collector's return to the block that made a heap or stack
check is no such loop: a back edge leaving a block that follows a failed
check stays as it is. checkFailures, in GHC.CmmToAsm.CFG, finds
those blocks: the targets of the less likely edges of a branch
that getCfg tags HeapStackCheck, one whose condition reads SpLim, HpLim
or BaseReg, and their successors, such as the block the garbage
collector returns to, which can be a continuation that a call returns
to as well. A block that follows such a block and whose one out-edge has
the code generator as its source, such as a block the register allocator
puts there, counts as following a failed check too (coldBlocks). Raising
those back edges too makes containers' benchmarks take 0.28% more
instructions (set fromAscList:fusion 3.2%, intset fromList:worstCase
3.0%); leaving out the blocks that follow a failed check but
not the block the register allocator puts after such a block, 0.09% more
(map alter insert 0.9%). A new Note, [Frequencies before register
allocation] in GHC.CmmToAsm.CFG, names two shapes coldBlocks misses:
the block allocMoreStack splits off a block the garbage collector
returns to, and a fixup block on a failure edge, which takes the edge's
tag. A TODO at coldBlocks points there. Building the set in GHC.CmmToAsm
instead, from checkFailures' blocks, the blocks allocMoreStack splits
off a cold entry block and the fixup blocks on an edge out of or
into a cold block, changed a few procedures' layout in nofib and moved
no figure measured, while costing up to 0.03% more compile allocation
at -O0.
Nor is a back edge into the one successor of the procedure's entry block
raised: the entry would then jump to that block at every call, which
a loop that seldom iterates does not win back. The RTS's entry code has
such loops, which retry on an indirection: raising their back edges made
stg_BLACKHOLE_info, stg_enter_info and stg_forceIO_info begin
with a jump into the loop, so that stg_BLACKHOLE_info ran an instruction
more for every blackhole entered. Where the code generator split
the entry block, as allocMoreStack does, and the block holding the rest
of its code has one successor, that successor stands in for the entry's.
Measured against the parent commit, in instructions; sequenceChain runs
only under -fblock-layout-cfg, on at -O1 and -O2. At -O2 nofib's
programs take 0.051% fewer (queens 1.2%, wheel-sieve1 1.0%, banner
0.47%), vector's benchmarks 0.41% fewer (leaffix 3.4%, rootfix 2.7%,
listRank 2.2%), containers' 0.099% fewer and megaparsec's 0.062% fewer
(reachOffsetNoLine 0.78%, reachOffset 0.46% to 0.60%); at -O1 nofib's
take 0.048% fewer (knights 1.3%, wheel-sieve1 0.99%, banner 0.44%);
fannkuch-redux moves by no more than its noise.
Some of containers' and megaparsec's benchmarks rise; the rises
are trades. The rule's own is the jump a loop's entry now pays, which
its iterations seldom win back: intmap lookup_mixed 2.0%, whose lookups
gain nothing from the descent that now falls through, and intset's
intersection and difference benchmarks, about 0.7%: the continuation
that evaluates the second set now jumps into differenceTip's descent,
a loop whose head has two back edges and which runs no iteration where
that set is a Tip, as in these benchmarks, while IntMap's lookups,
of the same shape, iterate about sixteen times an entry and gain 2.5%
to 3.0%; no static rule tells the two apart. megaparsec's hexadecimal,
decimal and octal at -O1 pay the same jump, and so does megaparsec's
scientific.4000, which calls decimal's decimal_: 20 instructions more,
as decimal.4000.
The fused rows, containers' map fromDistinctDescList:fusion, map and set
fromList-distinctAsc:fusion, and map fromListWith-asc:fusion
and fromListWithKey-asc:fusion, take 0.4% to 0.8% more at -O2, and set
fromDistinctDescList:fusion 0.90% more. Raising back edges only
into heads outside every enclosing loop reverts them, and with them
nubInt's noFusion_repeat, which pays the same jump into IntSet's member,
1000 instructions a run, and issue1202_repeat, intmap lookup_mixed
and intset alterF:delete:present; but it gives back the gains of intmap
lookup_hits, lookup_most and index (2.9% to 3.0%), lookup_misses (2.5%),
intset member and alterF:member (1.0% to 1.1%), and vector's listRank
(2.2%) and awshcc (1.8%), at -O2.
Where two back edges raised alike into one head tie, the static order
breaks the tie: at -O1 megaparsec's reachOffset pays 78000 instructions
a call, isWideChar's loop head having two back edges, tied, and the tie
going by label order to the one that ASCII input never takes. Flipping
the order takes 4.0% off intmap lookup_half, 2.0% off lookup_mixed
and 1.2% off intset alterF:delete:present, and at -O1 1.1% off
megaparsec's reachOffsetNoLine and 0.8% off errorBundlePretty, but adds
2.5% to nofib's fasta at -O2 and 1.2% at -O1, gives back 96% of banner's
gain, and adds 5.9% to intset fromAscList:fusion, 2.3% to fromAscList,
1.3% to mapMonotonic and, at -O1, 0.9% to vector's next
and prevPermutationBijective; the static order is kept.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The stage-1 compiler allocates 0.11% and 0.14% more compiling
perf/compiler's T12707 and T783 at -O and 0.097% and 0.13% more at -O2,
and 0.22% more compiling MR 16269's CmmDiamondChain at -O1 and -O2;
elsewhere its allocation moves by less than 0.03%. The stage-2 compiler
allocates 0.25% and 0.23% more compiling nofib's reptile and puzzle
at -O2. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.BlockLayout allocates 14% more (1.143 against 1.001 GB).
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
914c7f1e by Mikolaj Konarski at 2026-11-20T00:12:57+01:00
Hand calcFreqs a procedure's loops inner first
calcFreqs estimates block frequencies by Wu and Larus's algorithm, which
takes the loops from inner to outer, as its comment says: an enclosing
loop's frequencies use the cycle probability of each loop inside it,
computed when that loop is processed. mkGlobalWeights handed
it the loops in loopInfo's order, by back edge in the order of the CFG's
labels, so an enclosing loop could come first. calcFreqs then took
the probability of an inner loop's back edge itself, often 1.0,
for that loop's cycle probability, which calcFreqs caps at 1 - 1/512,
so the inner loop's head counted up to 512 times as often as
it was entered. The cycle a heap check makes through the garbage
collector is such an inner loop in any loop that allocates:
in containers' map benchmarks, the head of the loop that looks keys up
was estimated to run several times as often as the edges into it.
mkGlobalWeights now sorts the loops by the size of their bodies,
an inner loop's body being a proper subset of an enclosing one's.
This makes block layout lean on the estimate more. Taking a procedure's
loops in label order could make a head's frequency up to 512 times
its inflow, so that the loop's back edge won by accident; where static
prediction calls staying in a loop over a tree unlikely (Note [Static
prediction of tag tests]), it is now the rule that a back edge outranks
the loop's entry ("Let a loop's back edge outrank its entry in block
layout") that keeps layout from following the estimate.
Measured against the parent commit, in instructions; calcFreqs changes
the generated code only under -fcmm-static-pred, on at -O1 and -O2.
No nofib program moves by 0.2%, no benchmark of containers or megaparsec
rises at -O2, and vector's benchmarks take 0.034% fewer at -O2
(findIndexR_manual 1.07% fewer) and fannkuch-redux 0.19% fewer.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The compiler's allocation compiling perf/compiler's T3294, T12707, T783
and T9961 moves by 0.004% or less.
Assisted-by: Claude Opus 5.5
- - - - -
234ccd4d by Mikolaj Konarski at 2026-11-20T00:12:57+01:00
Count self loops as loops in static branch prediction
loopInfo took an edge for a back edge where its target dominates
its source, by mkDomMap's sets, which hold a block's own label only
where the block is a leaf of the dominator tree. So a self loop counted
as a back edge only from a leaf, and the retry of an atomic operation
that x86 emulates with a compare-and-swap loop (cmpxchg_code), whose
block dominates the block after it, counted as none: calcFreqs then took
that block for irreducible and gave frequency 0 to it, to every block
it dominates and to their edges, a surrounding loop's back edge among
them. mkDomMap's sets now hold each block's own label but the root's,
so that a self loop counts as a back edge but at the root, which no edge
enters as a back edge. mkDomMap also builds the map in one fold
over the dominator tree, inserting each block but the root as it walks
the tree, where it built a list of pairs, each block
with its dominators, and made a map of the list. The fold is taken
from Simon Jakobi's MR 16269, for ISSUE 27448, which also changes what
the sets hold. This fixes ISSUE 28093, self loops missed as back edges,
as MR 16269 does.
The retry edge cmpxchg_code adds now has a TransitionSource of its own,
AsmCodeGenRetry, which staticBranchPrediction leaves out of its rule
that a back edge is more likely than any other edge, so that the retry
is predicted to be rare rather than to repeat seven times in eight. Note
[Static Branch Prediction] says so. Andreas Klebinger's MR 16535
overlaps with this commit at that edge: it builds that loop's edges
by continueInNewBlock and addColdSelfLoop, and the two changes conflict
there.
The back edges staticBranchPrediction tests were a Set of pairs,
master's, looked up for each successor of each block; they are now
a LabelMap from each block to the LabelSet of the blocks its back edges
enter, looked up once a block.
Measured against the parent commit, on x86-64: the assembly
of perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O
is the same, and so are the objects of nofib's programs at -O2;
of containers' objects only graph-benchmarks' Main changes,
and no benchmark of containers, vector or megaparsec moves beyond
its noise. The stage-1 compiler allocates at -O 5.5% less compiling
perf/compiler's T783, 0.35% less compiling T12707, 0.25% less compiling
T3294 and 0.008% less compiling T9961, and 27.6% and 27.5% less
compiling MR 16269's CmmDiamondChain at -O1 and -O2. Most of the saving
is the fold's, at T783 and CmmDiamondChain. At -O0, where static
prediction is off, the allocation moves by 0.002% or less.
Assisted-by: Claude Opus 5.5
- - - - -
87329858 by Mikolaj Konarski at 2026-11-20T00:12:58+01:00
Specialise the linear allocator and liveness pass to x86-64
The linear allocator is overloaded in the instructions and in the free
registers, and the liveness pass in the instructions, so on x86-64 too
they called every instruction method through a dictionary: the code
generator is specialised for each target, but its calls of regAlloc
and cmmTopLiveness went to the overloaded functions. Both now have
a SPECIALISE pragma for x86's instructions, and NOINLINE [0], without
which neither rule fires, when the boot compiler builds stage 1 or when
the stage-1 compiler builds stage 2: cast worker/wrapper makes each
function an alias of its body, cast to UniqDSM, and the alias inlines
from the function's own phase whatever its rules' phase, so it inlines
into the code generator before the call there becomes one at x86's
instructions, which is what the rule rewrites. A phase on the SPECIALISE
pragmas alone, [0] or [2], makes neither rule fire. linearRegAlloc
passes the other targets' free registers through a NOINLINE function,
which the specialiser does not specialise, so that only x86-64's get
a copy of the allocator; Note [Specialising the linear allocator].
The allocator's constraint synonym no longer requires Outputable free
registers, which nothing prints, and is renamed
from OutputableRegConstraint to RegAllocConstraint. Liveness.hs now
imports GHC.CmmToAsm.X86 for its Instruction instance, which Linear.hs,
importing Liveness.hs, has as well, so the allocator's modules
that import either compile after the x86 code generator; this makes
no import cycle, as of the allocator's modules the x86 code generator
imports only GHC.CmmToAsm.Reg.Target.
Specialising joinToTargets as well, with NOINLINE [0], saved
the compiler less allocation than this commit does.
The idea of specialising the allocator comes from the draft MR 4764
by Ben Gamari and Andreas Klebinger, which overlaps with this commit:
MR 4764 specialises the linear allocator to x86-64 and i386,
by INLINEABLE pragmas on the allocator's functions and SPECIALIZE
pragmas in GHC.CmmToAsm.X86, and this commit specialises it
and the liveness pass to x86-64, by the SPECIALISE pragmas above.
The generated code is the same: nofib's object files are the parent's
size. The stage-1 compiler allocates 1.8% less compiling perf/compiler's
T3294 at -O0 and 0.66% less at -O, 1.2% less compiling T12707 at -O0
and 0.40% less at -O, 1.0% less compiling T783 at -O0 and 0.20% less
at -O, and 1.7% less compiling T9961 at -O0, though only 0.014% less
at -O, where CI compiles it. Compiling MR 16269's CmmDiamondChain at -O1
and -O2, it allocates 0.55% less. Compiled by the boot compiler, GHC
9.12.4, GHC.CmmToAsm.Reg.Linear allocates 59% more (2.590 against
1.625 GB) and GHC.CmmToAsm.Reg.Liveness 28% more (2.095 against
1.640 GB). The compiler's code grows by about 100 KB. The series'
figures for its pragmas, these among them, come from stage-1 compilers
built by GHC 9.12.4; at the series' top a stage-2 compiler
with the series' pragmas, against one without them, keeps every sign:
compiling T3294, T783, T12707 and T9961 at -O0, -O and -O2 and MR
16269's CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, it runs
0.032% to 4.7% fewer instructions and allocates 0.038% to 4.1% less.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
2028ebe5 by Mikolaj Konarski at 2026-11-20T00:12:58+01:00
Record the linear allocator's spills only for -ddump-asm-stats
recordSpill kept every spill and reload the linear allocator inserts,
with its reason, in ra_spills, for the statistics -ddump-asm-stats
prints, their only reader. It now keeps them only when that flag is on.
The statistics printed are the same, and so is the generated code.
The stage-1 compiler allocates 0.20% less compiling perf/compiler's
T3294 at -O0.
Assisted-by: Claude Opus 5.5
- - - - -
03af9ec6 by Mikolaj Konarski at 2026-11-20T00:12:59+01:00
Check the order of liveness SCCs where jump targets are looked up
computeLiveness checked that a procedure's SCCs come in reverse
dependency order (checkIsReverseDependent) in a walk of its own,
gathering every instruction's jump destinations, and panicked otherwise.
The liveness pass looks every jump target's live-in registers up anyway,
taking none for a target missing from its map; that lookup now panics
instead, naming the target. For this, livenessSCCs enters the blocks
of a cyclic SCC in the map before the SCC's first walk, with no register
live, which is what the lookup took them to have, so that a target can
be missing only where the SCCs are out of order, or where the CFG
that gave the reachable blocks (sccBlocks) lacks it. The separate walk
goes, and with it computeLiveness, which then only called livenessSCCs:
regLiveness calls that itself. The generated code is the same.
The stage-1 compiler allocates 0.62% less compiling perf/compiler's
T3294 at -O0 and 0.24% less at -O, 0.55% less compiling T12707 at -O0
and 0.22% less at -O, 0.68% less compiling T783 at -O0 and 0.16% less
at -O, and 0.67% less compiling T9961 at -O0. Compiling MR 16269's
CmmDiamondChain at -O1 and -O2, it allocates 0.13% less.
Assisted-by: Claude Opus 5.5
- - - - -
d3c2afe1 by Mikolaj Konarski at 2026-11-20T00:12:59+01:00
Keep a procedure's imports only where they are emitted
cmmNativeGens forced the imported symbols of each procedure, rendered
as text, to avoid a space leak, and kept them for makeImportsDoc, which
emits them only where needImportedSymbols holds; on x86-64 Linux
that takes -dynamic -fno-PIC. Where needImportedSymbols does not hold,
cmmNativeGens now neither forces nor keeps them. The generated code
is the same, also under -dynamic, -fPIC and -dynamic -fno-PIC.
The stage-1 compiler allocates 0.15% less compiling perf/compiler's
T9961 at -O0.
Assisted-by: Claude Opus 5.5
- - - - -
953e142b by Mikolaj Konarski at 2026-11-20T00:12:59+01:00
Copy no register list in x86's mkRU where every register counts
regUsageOfInstr on x86 and x86-64 filtered both of an instruction's
register lists, keeping the virtual registers and the real ones
an allocator may hand out (interesting), and so copied both lists
for every instruction. mkRU now returns a list unchanged where every
register in it is kept. Sylvain Henry's MR 16843 (ISSUE 28008) overlaps
with this commit: MR 16843's register usage DSL tests each register
as it adds it, but copies a list of registers it is given as it tests
them, where this commit returns such a list unchanged when every
register in it is kept. The generated code is the same. The stage-1
compiler allocates 1.2% less compiling perf/compiler's T3294 at -O0
and 0.46% less at -O, 0.76% less compiling T12707 at -O0 and 0.24% less
at -O, 0.53% less compiling T783 at -O0, and 1.5% less compiling T9961
at -O0. Compiling MR 16269's CmmDiamondChain at -O1 and -O2,
it allocates 3.3% less.
Assisted-by: Claude Opus 5.5
- - - - -
3762a8fb by Mikolaj Konarski at 2026-11-20T00:13:00+01:00
Mark the registers an instruction clobbers allocated, free or not
clobberRegs marked allocated those of the registers an instruction
clobbers that were free, listing the free registers of every class
for each instruction that writes a real register, with its own copy
of allFreeRegs from GHC.CmmToAsm.Reg.Linear.FreeRegs, and looking each
clobbered register up in the list. The FR class now has frClobberRegs,
which marks the clobbered registers allocated: by default those of them
that are free, by allFreeRegs, as clobberRegs did, since on AArch64,
RISC-V and LoongArch allocateReg panics on a register already allocated;
on x86-64, whose allocateReg marks a register that is not free
as it marks a free one, it marks every one of them, listing nothing.
clobberRegs calls it, and GHC.CmmToAsm.Reg.Linear no longer imports
the register class modules that only the copy used. The free registers
after a clobber are the same on every target, and so is the generated
code on x86-64.
The stage-1 compiler allocates 0.093% less compiling perf/compiler's
T3294 at -O0, 0.42% less compiling T12707, 0.47% less compiling T783,
and 1.2% less compiling T9961; at -O, 0.13% less compiling T12707.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.49%
less. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear.FreeRegs allocates 73% more (0.489 against
0.283 GB).
Assisted-by: Claude Opus 5.5
- - - - -
3850efc8 by Mikolaj Konarski at 2026-11-20T00:13:00+01:00
Keep an instruction's register usage in its liveness
The liveness pass's backward walk computes the register usage of every
instruction it annotates (regUsageOfInstr), and its forward walk
(livenessForward), the linear allocator's genRaInsn and the graph
allocator's spill cost (slurpSpillCostInfo) and spiller (regSpill_instr)
computed it again. Liveness now keeps it (liveUsage), and those use
the kept usage instead. patchRegsLiveInstr, which only the graph
allocator reaches, computes the patched instruction's usage again,
as an instruction's usage can depend on whether its registers are equal:
x86's VXOR of a register with itself into itself reads nothing. A new
Note in GHC.CmmToAsm.X86.Instr, [What x86's regUsageOfInstr reports],
lists that case with the others where the usage is not what
the processor does. This commit overlaps with Sylvain Henry's MR 16843
(ISSUE 28008), which keeps the usage in the liveness annotation too
and also builds it more cheaply in every backend, but has neither
that Note nor the two changes to genRaInsn below; MR 16843 was read
before this commit was written. genRaInsn also takes the list
of the virtual registers an instruction reads as it is built, where
master passed it through nubOrdOn to remove repeats: a register read
twice is found at its second lookup in the register its first gave it,
so that the instruction is patched alike, and Data.Containers.ListUtils
is no longer imported. It also patches an instruction's registers
without master's patch_map, a UniqFM that listToUFM built for every
instruction from the virtual registers the instruction reads and writes,
paired with the real registers allocated to them: patchLookup takes,
by unique, the register of the last written pair whose vreg is the one
it is given, or else of the last read one, the entry listToUFM kept.
The generated code is the same, with the linear allocator
and with -fregs-graph. The stage-1 compiler allocates 3.8% less
compiling perf/compiler's T3294 at -O0 and 1.4% less at -O, 1.8% less
compiling T12707 at -O0 and 0.54% less at -O, 1.3% less compiling T783
at -O0, and 2.3% less compiling T9961 at -O0. Compiling MR 16269's
CmmDiamondChain at -O1 and -O2, it allocates 0.34% less.
Assisted-by: Claude Opus 5.5
- - - - -
33aad82b by Mikolaj Konarski at 2026-11-20T00:13:01+01:00
Walk a block of a cyclic SCC again only when its successors change
livenessSCCs annotated the blocks of a cyclic SCC by walking all of them
again until the registers live on entry to every block stopped changing,
comparing two whole block maps as lists after each round. livenessCyclic
now walks a block again only when the registers live on entry to one
of its successors in the SCC, or their formats, have changed since
its last walk. A block walked again takes each instruction's usage
from its last walk (livenessBlockAgain), and master's liveness1 hands
the usage it computes to liveness1U, which the two share. The old loop
compared only which registers are live (the Eq of Regs ignored formats),
so it could stop before a wider format had reached every block
of the SCC, the case Note [Register formats in liveness analysis]
describes; the new one carries formats through as well, and Regs' Eq now
compares them too. This fixes ISSUE 27619 and does what ISSUE 27437
asks: the walk itself finds the changes, and no whole block map
is compared. Two vector formats of a register are now compared by width
where the liveness join keeps the wider (compareFormats) and where
a write kills a vector value no wider than the format written.
This commit overlaps with MR 16537, Simon Jakobi's, which fixes both
issues by iterating the fixpoint over the SCC's blocks until the formats
of the registers live on entry converge. An earlier version of MR 16537
also removed the derived Ord of formats, comparing them by width,
and this commit follows that version in comparing vector formats
by width and takes its regression test T27619 unchanged; it follows MR
16537 in carrying the formats through, and walks again only the blocks
whose successors changed where MR 16537 walks every block of the SCC
each round.
The liveness join keeps the wider of two vector formats of a register:
compareFormats, in GHC.CmmToAsm.Reg.Regs, compares two vector formats
by width, and two vectors of one width, as every other pair, by Format's
derived Ord, so that the order stays total. minusCoveredRegs lets
a write kill a vector value no wider than the format written,
and master's shrinkingRegs, which nothing calls, is deleted.
In liveness1U, delCoveredRegs, new in GHC.CmmToAsm.Reg.Regs and sharing
minusCoveredRegs' test of whether a write kills a value, takes
the registers an instruction writes out of the live set without building
their set, where master's liveness1 built it by mkRegsMaxFmt
for minusCoveredRegs. The derived Ord, which ISSUE 27619 also notes,
ranks a vector by its number of elements before their format: by it,
the join could keep a register read at two vector formats
at the narrower, and a write at the narrower kill a value live
at the wider, cases no x86 input was found to reach, and a write killed
no value live at a format of its width ranked above its own. The new
unit test testFormatWidths, in regalloc_unit_tests, checks the join both
ways and the kill between formats of different widths and of one;
it fails without the width comparison.
The generated code is the same on every program measured outside SIMD
code. Of perf/compiler's T3294, T12707, T783 and T9961, only T9961 at -O
has a cyclic SCC, and the stage-1 compiler's allocation compiling
it moves by 0.006%; compiling nofib's programs at -O2, the stage-2
compiler allocates 0.30% less in geometric mean and up to 4.2% less
(spectral/puzzle). Compiling MR 16269's CmmDiamondChain at -O1 and -O2,
the stage-1 compiler allocates 31.9% and 31.8% less. Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Liveness allocates
23% more (2.312 against 1.886 GB) and GHC.CmmToAsm.Reg.Regs 12% more
(0.208 against 0.186 GB).
In SIMD code, of the testsuite's simd tests compiled at -O1 and -O2,
with and without -mavx2, int32x4_basic and word32x4_basic,
with and without _baseline, lose a register move without -mavx2
to the width comparison: SSE2's Int32X4 insertion writes at VecFormat 4
FmtInt32 registers it reads at VecFormat 4 FmtFloat, so that
by the derived Ord the write killed nothing and those registers
were live into the procedure. int8x16_arith and word8x16_arith change
a symbol's name only, and every other test that compiles gives the same
code, as nofib's multiplier, primes, puzzle and para do. Compiling
perf/compiler's T3294, T783, T12707 and T9961, MR 16269's
CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, the width
comparison changes the compiler's instructions and allocation hardly
at all.
livenessCyclic takes the blocks to walk highest position in the SCC
first. With them taken in the order queued, the compiler ran 4.3% more
instructions and allocated 5.5% more compiling CmmDiamondChain at -O0,
and 3.6% and 4.5% more at -O1 and -O2; with the lowest taken first, 5.7%
more instructions at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
d0c85638 by Mikolaj Konarski at 2026-11-20T00:13:01+01:00
Fill in liveBorn only for the graph allocator and -ddump-asm-liveness
The liveness pass recorded, for every instruction, the registers born
there (liveBorn), which costs a forward walk over every instruction
of every block. Only the graph allocator and -ddump-asm-liveness use it.
regLivenessBorn is now a pass of its own, which the graph allocator,
its iterative variant included, runs on its input and again after
recomputing liveness, and which CmmToAsm runs only for the dump.
The generated code is the same, with the linear allocator
and with -fregs-graph. The stage-1 compiler allocates 2.5% less
compiling perf/compiler's T3294 at -O0 and 0.91% less at -O, 1.8% less
compiling T12707 at -O0 and 0.63% less at -O, 1.7% less compiling T783
at -O0 and 0.29% less at -O, and 2.2% less compiling T9961 at -O0;
with -fregs-graph it allocates up to 0.3% more (T9961 at -O0). Compiling
MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.85% less.
Figures that the per-commit measurements do not cover were measured
on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
973fc6e4 by Mikolaj Konarski at 2026-11-20T00:13:01+01:00
Prefer the register a vreg is moved into where it dies
The linear allocator preferred, for a vreg, the first register
it was recorded in on entry to any block (findPrefRealReg); Note [The
first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, gains a paragraph saying
that the first jump into a block decides that register too.
The allocator now has preferences, tried best first. firstFreeInOrder
takes the free registers of the vreg's class and returns the first
preference among them, else the first of them. allocRegsAndSpill_spill
takes its choice, and so does saveClobberedTemps, which took the first
free register where it moves a value out of a clobbered one. This commit
adds one preference, ahead of the first-used register: the real register
the current block moves the vreg into where the vreg dies. A value
computed into a vreg that the block then moves into R1, before
an evaluation or a return, is computed in R1, and the move, now
from a register to itself, is dropped by genRaInsn. The first-used
register, which keeps a loop variable in one register at both ends
of a loop, gains nothing for a value that dies in the block. Ranked
after it, the new preference cost nofib's scs 0.2% more instructions
once later commits changed the order of the free registers: a spilled
value was reloaded into its first-used register and then moved into R1's
register. processBlock builds, for each block, the map from a vreg
to the register the block moves it into where it dies (dyingMoves,
rc_moveDests). The preference is taken from Andreas Klebinger's MR
16693, whose choice of a free register prefers the real register a vreg
is moved into where it dies, in any block (ISSUE 27742); this commit
takes the moves of the current block, a subset of those.
The map lives in a record of its own, RA_Context, which RA_State holds
in one strict field (ra_context), rather than in RA_State itself, where
an unused field alone makes the compiler allocate 0.3% more compiling
T3294 at -O0. The NCG configuration, which the allocator uses but does
not update either, moves there too (rc_config, was ra_config), and runR
takes the context in its place.
The expected assembly of codeGen/should_gen_asm's T24813 loses the movq
before each function's jmp: each popcount is now computed in R1.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs, linked with the same libraries for both, take 0.26%
fewer (0.26% at -O1, 0.72% at -O0), none as much as 0.2% more beyond
their run-to-run noise; vector's benchmarks 0.27% fewer, none more;
containers' 0.41% fewer, none as much as 0.1% more beyond their noise;
megaparsec's 0.51% fewer (skipSomeTill 1.3%, endBy1 1.2%), none more;
fannkuch-redux moves by no more than its noise at -O2 and -O1.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The stage-1 compiler allocates 0.10% more compiling perf/compiler's
T12707 at -O0, 0.19% more compiling T783, and 0.085% more compiling
T9961; compiling T3294 its allocation moves by 0.029% or less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
9a74616a by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Prefer a vreg's register at a recorded jump target (ISSUE 27980)
firstFreeInOrder now puts first the register the vreg has on entry
to a jump target of the current block whose assignment is already
recorded (jumpLocRegs), such as a loop header jumped to from the loop's
end: in that register the vreg needs no fixup move at the jump.
For a target not yet reached, it takes the recorded assignments
of the blocks that target jumps to, up to three jumps on. The first-used
register, which a loop variable took until now, is the one the vreg
was recorded in by whichever block recorded it first, which need
not be the target. processBlock looks up the recorded assignments
of the block's jump targets once, when the block starts (rc_jumpLocs,
in RA_Context), taking the targets from a map of each block's jump
targets that linearRegAlloc' builds once for the procedure (jumpSuccs):
a target's assignment is recorded only at the block's jumps, after which
no preference is looked up. Built lazily, that map makes the compiler
allocate 0.3% more compiling perf/compiler's T3294 at -O0.
In ISSUE 27980's reproducer the loop's continuation then reloads
a variable straight into the register the loop header has it in,
and the fixup block goes away. vector's quickhull and nofib's sphere
and fibheaps show the same pattern, a rotation through a spill slot
gone. It is a preference, applying where the block that gives the vreg
a register jumps to a target whose assignment is recorded and the vreg's
register there is free; the fixups of ISSUE 27800, of which ISSUE 27980
was closed as a duplicate, stay.
The test, T27980, is the Cmm of ISSUE 27980's reproducer, its allocator
statistics (-ddump-asm-stats) searched for fixup moves: with the parent
commit's compiler the loop's back edge pays one.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's sphere takes 0.28% fewer at -O2 and fibheaps 0.24% fewer at -O1,
vector's quickhull 0.68% fewer at -O1, and no other program of nofib's,
benchmark of vector's or fannkuch-redux moves by more than its noise;
containers' benchmarks take 0.010% fewer (intset mapMonotonic 1.4%)
and megaparsec's 0.004% fewer (hexadecimal.4000 0.12%), none as much
as 0.1% more beyond their noise. No benchmark's allocation changes
beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.34%,
0.56% and 0.50% more compiling perf/compiler's T12707, T783 and T9961
at -O0, 0.16% and 0.19% more compiling T12707 and T783 at -O, and 0.32%
more compiling MR 16269's CmmDiamondChain at -O1 and -O2, and 0.046%
less compiling T3294 at -O0; the stage-2 compiler allocates 0.079%,
0.079% and 0.20% more compiling nofib's programs at -O2, -O1 and -O0
(geometric means). Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 24% more (3.171 against 2.562 GB).
The look-ahead past a target not yet reached, to the recorded
assignments of the blocks it jumps to, is a trade in the sample
of orthotope's A2T benchmark. Shaped's maximumA.one over small strided
Unboxed and boxed arrays takes three instructions a call more (up
to 0.88%), and Shaped's minimumA and maximumA over small dense Unboxed
and boxed arrays two more: the look-ahead leaves a swap of two registers
through a spill slot on the hot edge into a join of Shaped's operations,
where the parent commit paid the same swap on another edge. Without
that look-ahead the six cells are back at the parent commit's counts
or below, but its gains go: Ranked's convertE over small dense boxed
arrays takes 3.1% more and Shaped's ==.rank1 over small dense Unboxed
arrays 1.4% more, and the 384 cells this commit improves give back 190.8
of the 5218.3 instructions a call they gain. That toggle was measured
on the A2T sample alone. A fix would need block frequencies before
register allocation.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
03790c0d by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Prefer the register a later block moves a vreg into where it dies
firstFreeInOrder now has a last preference: the real register a block
the vreg is live into moves it into where it dies, for a vreg computed
blocks earlier, such as R1 for a value evaluated some blocks after
it is computed (wideMoveDests, once a procedure; rc_wideDests).
The blocks that follow a failed heap or stack check, such
as those calling the garbage collector, do not count: the move there
seldom runs, and the register it names can cost a move in the hot code.
The preference is left out where that register is live together
with the vreg somewhere, which a walk of the blocks finds: at a block's
entry, after an instruction's writes, and where a vreg born while
the vreg is live is moved into that register where it dies, in the block
it is born in. The walk follows a vreg on into the vreg it is moved
into where it dies, to which the allocator gives the same register,
dropping the move; and it takes an instruction's writes
from its register usage, liveBorn being filled in only for the graph
allocator and the liveness dump. It visits only the blocks a destination
is live into or written in, a move into one where a vreg dies included,
as elsewhere no destination is live during the walk; and the candidates
and the moves of a vreg into another where it dies, which the walk
follows, are found in one pass over the procedure's blocks. Nor
is it taken where another vreg the block reads or writes,
with no location yet, has the register as its first-used one
(rc_claims): without this, in vector's leaffix and listRank at -O1
a bound or an array reloaded after a call took its wide destination,
displacing the values whose first-used register it is, and the loop's
latch fixups grew from three instructions to five and six. A vreg
already given a location claims nothing, so that a literal in intset
instanceOrd:dense keeps its wide destination where an already coalesced
vreg has it as its first-used register. processBlock's claims take
an instruction's register usage from its liveness, where it has one,
rather than computing it again. dyingMoves now gives moves into vregs
as well, and is INLINE: out of line it makes the compiler allocate 1.0%
more compiling perf/compiler's T3294 at -O0. This preference
and the earlier one for the current block's moves ("Prefer the register
a vreg is moved into where it dies") together overlap with
that of Andreas Klebinger's MR 16693, the real register a vreg is moved
into where it dies, in any block.
Counting those blocks, in containers' map foldMap_traverseSum a node
and its field both had %rbx as their destination, the field from the hot
block that evaluates it, the node only from the heap check's failure
block, which calls the garbage collector; the node, allocated first,
took %rbx, and the field, given %rax, moved into %rbx at every
evaluation: 1.5% more instructions. CmmToAsm takes those blocks
from checkFailures (allocCold) and passes them to the linear allocator,
wherever the backend maintains the CFG, -finfo-table-map or not;
that is on x86-64 only, and elsewhere the set is empty. Leaving out only
the failure targets that no other edge enters, as an earlier form
of this change did, changes no code in perf/compiler's T3294, T12707,
T783 and T9961 or in containers' benchmarks, and makes the compiler
allocate slightly more.
The rule for a vreg born while the vreg is live keeps the register
for the later vreg, which its own block moves into it. Without it,
in containers' graph buildG the loop's index and lower bound took R2's
and R3's registers, which the block making the loop's call needed
for its arguments, and that block ended with three moves an edge, 3.3%
more instructions. Counting every vreg born while the vreg is live
and moved into the register in any block made containers' map insertWith
take 3% more instructions: its value argument arrives in R3
and is passed in R3 to both recursive calls, and the node's key, born
later in the loop and moved into R3 in another block, made it lose R3
as a preference, so every iteration moved it out of R3 and back. Note
[Frequencies before register allocation] gains a bullet saying
that where blocks give a vreg different destinations the last block's
wins, with a TODO at wideMoveDests: taking the hottest block's instead,
by mkGlobalWeights, moved containers' benchmarks both ways by up to 1.4%
and cost 0.24% more compile allocation, its estimate made
for this alone. A comment there notes that a destination no allocator
hands out, Sp, Hp or BaseReg, stays a candidate; leaving those out
changed no code measured and costs compile allocation.
Where no preference is free, firstFreeInOrder now leaves out, while
others remain, the free registers the current block moves another vreg
into where it dies: a vreg given one would keep the other from being
computed in it, or have to move out of its way. Those registers are kept
as a mask by register number, the first free register taken without
filtering the list where the block moves no other vreg into a register
where it dies, and the claims are walked only where no earlier
preference is free and the wide destination is, so that the compiler's
allocation compiling a procedure of many C calls grows
with the procedure as at the parent. That mask is made from two masks
of the block's moves, made once a block: the registers they enter,
and those that two or more vregs enter, the vreg's own register left out
where it alone enters that one. The two are held with the block's map
in one value, and the blocks that move no vreg share one. Folding
the block's moves at every choice instead made the stage-1 compiler run
2.3% more instructions compiling the battery's scaling program ccalls,
400 C calls in one block, at -O1; the masks add to no compilation
of perf/compiler's tests or of CmmDiamondChain more than 0.006%
of that fold's allocation or 0.001% of its instructions. Held as a pair
in a field of their own, they cost up to 0.076% more allocation (T9961
at -O0); held in the one value, made from the list of the block's moves,
up to 0.27% (T3294 at -O0), and made from the block's map, 0.016% (T9961
at -O0), the rest going when the function making it was marked OPAQUE:
its worker and wrapper had allocated a value for each block, the empty
one too. The figures below were measured with the fold. Without this,
containers' graphFromEdges and stronglyConnCompR took up to 1.1% more
instructions at -O1: the index-error block of their key lookup passes lo
and hi in R3 and R4, so the new preference gives them those registers
in the lookup's loop, and the array element, which has no preference,
took the first free register, R1's, into which the loop moves the key
before storing the element: every probe moved the element out
of it first.
mkMoveDests, which builds the masks of the block's moves,
and wideMoveDests, for its mask of the wide destinations, assert
that each register number they set is below 64: setBit sets nothing past
it, so that a register numbered past it would drop out
of the preferences in silence, and the backends number their real
registers below 64. Only a compiler built with assertions on checks
them, and none was built; in the perf flavour they cost nothing,
measured at the series' end: nofib's assembly at -O1 and -O2 and
that of the compile cells is the same, and no cell moves by 0.001%
in instructions or allocation.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs take 0.27% fewer (0.28% at -O1, 0.25% at -O0), none
as much as 0.2% more beyond their run-to-run noise; vector's benchmarks
0.26% fewer (generateIO 3.8%), none more; megaparsec's 0.20% fewer
(skipCount 0.86%, choice 0.58%), none more at -O2; fannkuch-redux moves
by no more than its noise. The benchmarks of containers take 0.72% fewer
(intset fromAscList:sparse:fusion 6.3%, intmap symmetricDifference up
to 5.4%). No benchmark's allocation changes beyond nofib's run-to-run
noise. Counting the failure blocks' moves, the stage-1 compiler
allocates 0.19% more compiling perf/compiler's T3294 at -O0, 0.26% more
compiling T12707, 0.19% more compiling T783, and 0.20% more compiling
T9961; leaving them out takes back half or more of each. Compiling MR
16269's CmmDiamondChain at -O1 and -O2, it allocates 0.12% more. It runs
0.50% more instructions than the parent's compiling CmmDiamondChain
at -O0 and 0.41% and 0.40% more at -O1 and -O2, 0.84% more compiling
T12707 at -O0 and 0.61% to 0.65% more compiling T3294, T783 and T9961
at -O0. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 72% more (5.461 against 3.171 GB).
Some rows rise, and a later commit takes back each one this paragraph
names by undoing its cause. At -O1 megaparsec's endBy takes up to 0.51%
more: its loop's join fixup, a cycle through the C stack that exists
because the block the garbage collector returns to records the join's
registers, gains a move an element; the commit after the next, "Allocate
the blocks the garbage collector returns to last", removes the whole
fixup, and with it the same loop's rotation in containers' map alter
insert, 1.3% more here, and alterF alter insert. endBy's rise is also
a trade: leaving out the wide destination's preference puts endBy back
at the parent's count, 0.47% to 0.50% fewer instructions, and gives back
megaparsec's gains, reachOffsetNoLine taking 3.9% more, reachOffset 3.4%
and errorBundlePretty 3.0%. containers' graph buildG takes up to 2.2%
more, its loop index, given no preference, now taking R1's register,
which the call at the loop's end needs, so that moves on every edge
remain, and intmap index 0.53% more, and in orthotope's A2T benchmark
sumA and productA over large broadcast boxed arrays 3.4% to 3.6% more,
the element passing through R1's register one move more an element;
"Order x86-64 free registers around R1 and clobbers (ISSUE 27981)" takes
all three back, returning buildG's block to the shape it has at "Prefer
a vreg's register at a recorded jump target (ISSUE 27980)" and loading
A2T's element straight into R1. vector's listRank takes 2.0M more
instructions at -O1, and A2T's convert.g and convertE.g over large
strided boxed arrays 18.75% more and its max.g and min.g 8.0% more,
their rnf loop swapping its index through R1's register, three moves
an element; "Allocate a loop before a continuation that enters it" takes
both back: in listRank the block before the join loads straight
into the join's registers, and the cycle through 0x40(%rsp) that holds
this commit's move is gone, and the rnf loop's swap is gone.
The rows of containers' intmap symmetricDifference-block, intmap
and intset union-block, map fromDescListWithKey:fusion and map
insertWith', and IntMap's and IntSet's union-disj_sn_swap
and union-disj_tn_swap at -O2, two instructions more each
by union-block's moves run once, are a trade: each pays moves in one
procedure, following from the register choices the preference makes,
with no local fix known; leaving the preference out reverts them
and gives back its gains. So are, in orthotope's A2T benchmark, fromList
and fromList.map over small strided Storable arrays, 0.87% to 1.09%
more, Shaped's by a register move more an element in OpsShaped's loop,
and Dynamic's and Ranked's foldrA over small Storable arrays, two
instructions more a call: taking out both of this commit's changes
to firstFreeInOrder's choice, the last preference and the free registers
it leaves out, reverts the 14 cells of the benchmark's sample that rise,
these and convert.g and convertE.g over small strided boxed arrays,
and gives back 509 of the 569 that fall. At "Allocate the blocks
the garbage collector returns to last" the fromList cells take 4.0%
to 4.4% fewer instructions than at the parent.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
e73e2de4 by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Put a block's reloads after its leading unwind in stack layout
To move into a merge request of its own, together with "Keep Sp put
across loops and tag tests in stack layout".
Under -g, maybeAddSpAdj starts each block's middle with an unwind giving
the block's Sp rule, and insertReloadsAsNeeded puts a proc point's
reloads before it, so that they run under the rule of the block laid out
before this one. At a return point that rule also covers the return
address (Note [Info Offset] in GHC.CmmToAsm.Dwarf.Types), and at -O0,
where no sinking moves the reloads, the unwind tables are wrong there,
on master at return points of nofib's multiplier, puzzle and para,
though not of primes, compiled at -O0 -g. The next two commits make
it frequent at -O0: the allocator moves the blocks the garbage collector
returns to, and then the continuations that enter a loop making no call,
with the SCCs only they lead to, to the end of its output, so that such
a continuation no longer follows its call block.
withReloads puts the reloads after a leading unwind. Without -g a middle
starts with none and the code is the same: compiled by this commit,
the four programs at -O0, -O1 and -O2 and the 15 compile-cost cells give
the same objects and assembly; with -g only their -O0 output differs,
and at -O0 none of their return points is under a wrong rule.
Cost: withReloads is one foldr, which fuses with insertReloads's
comprehension as the fold it replaces did. Compiling T3294 at -O0, -O
and -O2 takes the stage-1 compiler 0.012%, 0.007% and 0.005% fewer
instructions; the other compile-cost cells, and nofib's puzzle at -O2
compiled by the stage-2 compiler, change by at most 0.003%
in instructions, and allocation moves by at most 0.001% in every cell.
Assisted-by: Claude Opus 5.5
- - - - -
0c780f4c by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Allocate the blocks the garbage collector returns to last
The linear allocator records, at the first jump it allocates
into a block, the registers the block starts with, and later jumps
into the block move their values to match. linearRA_SCCs allocated
the SCCs in order, so the block the garbage collector returns to after
a heap or stack check fails, which jumps back into the block that made
the check, could be allocated before the hot path reached that block,
and so fix the registers it starts with. In containers' map alter
the block that builds the new node makes such a check; its return block,
allocated first, reloaded the new subtree into %rdi, R4, where
the rebalancing call takes it, while the hot path still held the other
subtree there, so the hot path reached the block through a fixup block
rotating registers at every level the insertion returns through.
linearRA_SCCs now allocates those return blocks (the procedure's entry
blocks in the set checkFailures gives, which it now takes, those
in a cycle excepted), and any SCC only they lead to, after the others,
so that another predecessor, in map alter the hot path, records
the registers and the return block pays the fixup. As it now tests every
block for whether a jump has reached it, it looks the entry blocks up
in a set built once rather than in their list. This commit overlaps
with Sylvain Henry's MR 16673 (ISSUE 27800), read before this commit
was written: both defer, in linearRA_SCCs, return blocks outside cycles;
MR 16673 those that jump into a loop, calls' continuations included,
with the acyclic blocks only they lead to, and this commit
those the garbage collector returns to, whether or not they jump
into a loop, with any SCC only they lead to.
Taking no wide move destination while allocating such a block, instead,
fixes map alter but makes map insertWith take 3% more instructions,
the mirror case: its return block, allocated first, reloads the value
argument into R3's %rsi, its wide destination, where the hot path has
it; without that destination it reloads it into %rax, and the hot path
moves it out of %rsi and back at every level. Note [Frequencies before
register allocation] gains a bullet saying that checkFailures also
counts as cold blocks the hot path may run, a continuation that a call
returns to as well and a failure target that another edge enters,
and that an estimate computed in a Cmm pass could replace
the classification; linearRA_SCCs and checkFailures gain TODOs pointing
there. Where such a continuation is on the path into a loop, deferring
it measured better than leaving it out of the set: the loop
is then allocated first, starting from the block the garbage collector
returns to from the loop's own check, so that the path into the loop
pays the moves once and the loop's latches none (containers'
set-benchmarks); leaving such continuations out costs nofib's scs 1.1%
more instructions and vector's maximumOn 2.9%, and leaving out such
failure targets changes no code measured and costs compile allocation.
Allocating a loop before the path into it on purpose, by deferring
the blocks that jump into an SCC holding an entry block, costs
fannkuch-redux 13% at -O1, whose inner loop lies in its outer loop's
SCC. MR 16673's deferral, of every return continuation outside a cycle
that jumps into a loop, is not used either, because it was found
incorrect: it defers as cold a continuation that is itself inside a loop
through the Haskell stack, and fannkuch-redux then runs 16 to 19% more
instructions.
From "Use block frequencies to order the linear allocator's SCCs" on,
the deferral orders the SCCs only where no block frequencies
are estimated, on x86-64 without -fcmm-static-pred, as at -O0, or where
the estimate lacks one of the procedure's blocks, as it can
under -finfo-table-map (ISSUE 28088); elsewhere at -O1 and -O2
that commit's order replaces it.
With the return blocks allocated last, a block that reloads a value can
find the vreg's first-used register, the one whichever block recorded
the vreg first gave it, to be another value's: in containers' map
fromList-distinctAsc at -O2 such a reload took it over its own wide
destination. firstFreeInOrder now passes over the first-used register
for the wide destination where a walk from the current block's jump
targets, through the blocks the vreg is live into and stopping
at those whose assignment is recorded, reaches no recorded block
but reaches one that moves the vreg into the wide destination where
it dies, and the value live into a block recorded with the vreg
in the first-used register reaches none of the blocks the walk passed
(staleWalk, staleMeets). The vreg is then marked (markStaleFirst),
and for a marked vreg whose walk reaches a recorded block holding
it in another free register, that register is taken: in sequence's
update.100 and adjust.100 at -O1, the continuations reloading
into the same vregs then agree, where the later ones kept the stale
register and paid a swap through the C stack. Both tests end by listing
the recorded blocks that hold the vreg in its first-used register
(blocksHolding), a visit to every recorded assignment, and both fail,
leaving the vreg its first-used register as a preference, where more
than 256 assignments are recorded: unbounded, compiling at -O0
a procedure of N two-way branches in sequence, each after a call's
return, whose arms pass a call a variable written afresh before
the branch, the listings visited a number of assignments quadratic in N.
The walks behind both give up after 64 blocks (liveWalk), a cap tested
after whether the next block is seen already or one the vreg is not live
into, and in a trace at the series' end reached by no walk compiling
nofib's modules at -O1 and -O2 or the compile cells' sources. TODO:
the bound of 256 recorded assignments, like the cap of 64 blocks,
is arbitrary and should be generalised; compiling nofib's modules
at -O2, no listing visited more than 132, and an index of the holders
in place of the bound, each recorded assignment adding a thunk to it,
made the compiler allocate 0.068% more compiling T9961 at -O0 and 0.048%
more compiling T783 at -O0. Measured at the series' end, against
it without the bound: compiling the N branches at -O0, the compiler ran
0.37, 0.85, 2.23 and 6.69 thousand million instructions for N = 400,
800, 1600 and 3200 without it and 0.32, 0.59, 1.13 and 2.22 with it,
the variable then keeping its first-used register and each arm moving
it into the argument's; nofib's modules compile to the same assembly
at -O1 and -O2, and no compile cell's instructions rose by 0.005%
or its allocation by 0.01%, the assembly the same. And genRaInsn reloads
a vreg that an instruction only moves, where it dies, into a register
free by then straight into that register, and drops the move
(reload_into), as in map union at -O2.
Master's process and genRaInsn, in GHC.CmmToAsm.Reg.Linear, build less.
process, which allocates a cyclic SCC's blocks, takes linearRA_SCCs'
accumulator and conses each block's code onto it, where it returned
a list of lists that linearRA_SCCs concatenated. genRaInsn joins
an instruction's spills, reloads and clobber saves onto the code after
it strictly, where master's concat left a thunk for each instruction.
Measured against the parent commit, in instructions: nofib's programs
take 0.11% fewer (wheel-sieve2 2.2%; 0.18% at -O1, fasta 10.7%), none
but knights at -O1, below, as much as 0.2% more beyond their run-to-run
noise; vector's benchmarks 1.2% fewer (maximumOn 17%, minimumOn 15%);
megaparsec's 3.6% fewer (endBy 22%, skipMany 16%); fannkuch-redux moves
by no more than its noise. containers' benchmarks take 0.22% fewer
(intset fromList:worstCase 8.2%, and map alter insert, the case above,
1.3%). No benchmark's allocation changes beyond nofib's run-to-run
noise. The stage-1 compiler allocates 0.54%, 0.44% and 0.59% less
compiling perf/compiler's T12707, T783 and T9961 at -O0, and at most
0.006% more in any other cell, MR 16269's CmmDiamondChain's included;
the stage-2 compiler allocates 0.081%, 0.074% and 0.24% less compiling
nofib's programs at -O2, -O1 and -O0 (geometric means). Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 23%
more (6.725 against 5.461 GB) and GHC.CmmToAsm.Reg.Linear.Base 16% more
(0.591 against 0.511 GB).
At -O1, vector's permutation benchmarks take 4.65% to 5.26% more,
quickhull 2.6% more and nofib's knights 0.52% more, and in orthotope's
A2T benchmark Summed's sumView over boxed arrays up to 1% more
and summed reduce over small dense boxed arrays 4.4% more: in their
loops another predecessor now records a join's registers, one where
a loop value with no preference has taken R1's %rbx,
and the predecessors that receive an evaluated value in %rbx reach
the join through a fixup that swaps or rotates registers at every
iteration. "Order x86-64 free registers around R1 and clobbers (ISSUE
27981)", which puts %rbx last in x86-64's fallback order, removes
these moves in the same blocks; the rotation left in quickhull's split
loop is there before this commit. A2T's generate.scalar over strided
Storable arrays takes 1.6% more, a swap through the C stack and two
moves into R1's %rbx at a join once a call, which that commit removes
too.
The other rises are the deferral's price, and leaving the deferral out
reverts them. The blocks the garbage collector returns to now pay
the moves into the registers the hot path recorded, by design:
containers' main426, $wascLinkTop and $sgo2 pay more instructions a call
at -O1; and megaparsec's many pays swaps through the C stack at every
collection, the hot path having had no fixup to lose.
With the allocation order changed, other blocks move values between
registers, with no local fix known: containers' intset
fromAscList:sparse:fusion, map fromDescListWithKey,
fromDistinctDescList, fromAscListWithKey and fromList-distinctAsc:fusion
(-O1), IntSet's symmetricDifference-block_sn_swap,
symmetricDifference-disj_tn_swap and difference-disj_nt and sequence
update.10, and megaparsec's endBy1. "Use block frequencies to order
the linear allocator's SCCs" takes back endBy1's rise by undoing
its cause: from it on, at -O1 and -O2, the hot path again records
the registers of the join in $weta4's loop, which here the continuation
of Data.Text's empty records, and $weta4 runs 133.18 instructions
a call, against 143.18 at that commit's parent. In orthotope's A2T
benchmark 19 cells of the sample take more, each back at the parent's
count with the deferral left out: Shaped's unravel.one and unravel
over small arrays three instructions a call more (unravel.one over small
dense arrays 0.72%), unravel.one storing a value to the C stack
and reloading it and moving a register once more a call, and ==.rank3
over small dense Storable and Unboxed arrays and zipWithA over small
scalar Storable ones two more; against the deferral left out, 19 cells
of the sample take more and 156 fewer. A2T's rotate.inner over large
dense Storable arrays takes 1.7% more, its loop reassigned; "Allocate
a loop before a continuation that enters it" removes about half of that,
a store and a reload through the C stack. In vector's findIndexR, which
takes 3.2% more at -O1, the procedure's entry now records the loop's
registers, with the predicate in R2's %r14, where it arrives,
and another loop value in R1's %rbx; as the loop calls the predicate
through %rbx, every iteration moves that value out of %rbx
and the predicate in, by way of %rdx: more moves than before. "Order
x86-64 free registers around R1 and clobbers (ISSUE 27981)" puts
the other value elsewhere, removing the move out of %rbx; not deferring
a return block that a warm block enters takes back the rest, but costs
nofib's fasta 13 instructions an iteration at -O1, and telling a loop's
only latch from a colder second latch needs block frequencies. At -O1
megaparsec's skipMany takes 0.95% to 0.96% more, a move an element
that lasts until "Keep Sp put across loops and tag tests in stack
layout" removes it: the hot path, now allocated before the block
the garbage collector returns to, takes the first free register where
the join's recorded one is expected. Leaving the deferral out reverts
it, with most of the procedures of megaparsec's bench-speed
that this commit changes; extending the claims of "Prefer the register
a later block moves a vreg into where it dies" to the vregs a jump
target writes removes the move but makes many of containers' benchmarks
take more instructions, intmap fromAscList 3.3% and intersection-mix_nn
1.0% among them.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
708ad583 by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Allocate a loop before a continuation that enters it
The linear register allocator gives a block the assignment of the first
jump into it that it allocates, and the SCC order puts a return
continuation before a loop it jumps into. Where the continuation's jump
was the first into a block of the loop, it decided that block's
registers, and the loop's own edges into the block paid fixup moves
at every iteration: in the reproducer of ISSUE 27800, two swaps
an iteration.
Defer such a continuation, as the blocks the garbage collector returns
to are deferred, so that the loop's own edges decide and the fixup goes
on the continuation's edge into the loop. This takes from MR 16673,
by Sylvain Henry, its deferral of a return continuation that jumps
into a loop, which is what fixes the issue there, as an extension
of the series' own deferral, not as MR 16673's code, and adds two
conditions it lacks:
* the loop calls nothing: a loop that calls C keeps its values
in spill slots, which a deferred continuation that is hot through
the Haskell stack then pays for (nofib's fannkuch-redux ran 16%
more instructions with the deferral unconditional);
* no assignment is recorded yet for the block the continuation jumps
into: once another jump has recorded one, deferring changes only
the order of allocation, by which block layout breaks its ties
(containers' intset fromAscList, one jump more an element).
The deferral remains a bet that a continuation runs less often
than the loop it jumps into, and it loses where the continuation
is the return point of a call made at every iteration of that loop,
which then pays the fixup at every iteration instead: megaparsec's
reachOffsetNoLine takes 0.96% more instructions at -O2 and reachOffset
0.28% to 0.36% more, nofib's mandel2 0.33% more, and containers' fused
fromDistinctDescList rows 8.1% to 8.8% more at -O1; it loses as well
where the loop runs no trip or few, the continuation paying the fixup
once a call: in orthotope's A2T benchmark convert.g over empty strided
boxed arrays takes 1.1% more, summed force.narrow over empty dense
Storable arrays 0.5% more and rev over small scalar Storable ones 0.4%
more. This is the trade the deferral makes, its toggle the deferral
itself, which reverts both these and the fromAscList family's gains:
the cases differ only in how often a call path runs, on which
no structural order depends. In the sample of orthotope's A2T benchmark,
34 cells take more against the parent, each back at the parent's count
with the toggle: concatOuter over small dense Storable arrays six
instructions a call more (0.62%), rev over small strided and dense
arrays three to five (0.42% to 0.49%), and ==.rank5, mapA
and zipWithA.singleR over small arrays among the rest, two to six;
against the toggle, 34 cells take more and 295 fewer. A third condition,
deferring only a continuation whose call the loop it jumps into does
not reach, breaks T27800, leaving a swap through a spill slot on both
hot edges, loses every gain of containers' fromAscList family
and vector's listRank and awshcc, makes nofib's fasta take 10.3% more
at -O2, and leaves megaparsec's reachOffsetNoLine where this commit puts
it. A2T's generate.scalar over strided Unboxed arrays takes 2.0% more,
a swap through the C stack and moves into R1's %rbx at a join once
a call, which "Order x86-64 free registers around R1 and clobbers (ISSUE
27981)" removes.
From "Use block frequencies to order the linear allocator's SCCs" on,
this deferral acts only where no block frequencies are estimated,
on x86-64 without -fcmm-static-pred, as at -O0, and on the other
targets, or where the estimate lacks one of the procedure's blocks,
as it can under -finfo-table-map (ISSUE 28088); elsewhere at -O1 and -O2
on x86-64 that commit's order replaces it, and T27800, compiled at -O,
exercises that order.
The test, T27800, is the Cmm of MR 16673's T27800.cmm, its assembly
searched for swaps and spill slots: the loop's edges carry neither,
and T27800.stderr expects the lines of the fixup on the cold edge out
of the continuation, a swap through a spill slot.
Measured against the parent commit, in instructions: vector's benchmarks
take 0.96% fewer at -O1 (hybcc 5.9%, listRank 5.8%, awshcc 3.2%, leaffix
3.8%) and move by no more than their noise at -O2; nofib's programs move
by less than 0.01% at -O2 and at -O1 in geometric mean, simple taking
0.28% and 0.21% more; containers' benchmarks move by less than 0.01%
at both levels in geometric mean, the fromAscList family taking 2.9%
to 7.8% fewer at -O2, its swap through a spill slot on each back edge
gone, though intmap fromAscList:fusion takes 1.3% more there
and the fused fromDistinctAscList rows 2.2% to 2.3% more at -O1,
and graphFromEdges up to 1.7% fewer at -O1; fannkuch-redux moves
by no more than its noise. No benchmark's allocation changes beyond
nofib's run-to-run noise. The stage-1 compiler allocates at most 0.025%
more compiling perf/compiler's T3294, T12707, T783 and T9961.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
c191c361 by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Skip registers written before a saved value's next read (ISSUE 26631)
saveClobberedTemps, saving a value out of a register an instruction
clobbers, such as an argument register of a C call, moved it
into the first free register in order, even one a later instruction
of the block writes before it reads the value again; then the value
moved again or was spilled there. It now leaves out the registers
the rest of the block writes before it next reads the value
(unwrittenBeforeRead), and where every free register is one, spills
the value at once. On System V every float and vector register
is caller-saved, so such a value live across a C call ends in memory
anyway: in simd013 the moves and a spill before the call become a spill
(ISSUE 26631). Writes in later blocks are not looked at. containers'
intmap and map mapMaybe and nofib's x2n1 and reverse-complement show
the pattern: values crossing a C call stored at once rather than first
moved into a caller-saved register, and mapMaybe's divisor kept out
of %rdx, which cqto writes.
Spilling at once wherever the first free register is written somewhere
in the value's live range instead, by the clobber map that "Order x86-64
free registers around R1 and clobbers (ISSUE 27981)" builds
(rc_clobbers), makes fannkuch-redux take 1.1% more instructions: a loop
bound kept in %rbx across a memcpy call is spilled and reloaded at every
iteration, %rbx being written elsewhere in the bound's live range,
though not before the loop reads it.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs take 0.035% fewer (k-nucleotide 2.0%), none as much
as 0.2% more; fannkuch-redux 0.32% fewer (0.35% at -O1); containers'
benchmarks 0.003% fewer at -O2 and at -O1, none more beyond their noise;
megaparsec's 0.014% fewer (string 0.17%), none more; vector's benchmarks
move by no more than their noise. No benchmark's allocation changes
beyond nofib's run-to-run noise. The stage-1 compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.010%
or less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
69cc21e7 by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Assign literals after computed values at the end of a block
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant" and "Drop the assignments that only
a discarded assignment read".
GHC.Cmm.Sink emits the assignments it sinks no further at the end
of a block, in their order. An assignment of a literal to a local
register now goes after the later ones where each of those assigns,
to another local register, a literal or the result of a machine
operation that reads neither that register nor the literal's. A literal
reads neither memory nor a register, and none of the assignments
it passes reads or writes its register, so every value stays the same.
Set first, a constant can take the register that a later value is
to be in at the block's end, while the value's operands still hold
the register the constant is to be in. In Data.Text's UTF-8 decoding,
as inlined into megaparsec's benchmarks, the ASCII path sets the width,
1, and then the character, the zero-extended byte, and jumps
to the join, whose recorded assignment has the width in %r14
and the character in %rbx. Once a later commit makes %rbx x86-64's last
choice, the byte is loaded into %r14; set first, the width would
then take %rbx and the character %r14, and the join's fixup would swap
them at every character. Set last, the width takes %r14, and the byte
is zero-extended into %rbx.
A copy or an update in place keeps a literal before it: in a trial
that let it pass them as well, the literal changed the registers
of a join's recorded assignment in megaparsec's manyTill benchmark
and of a loop head's in Text.Megaparsec.Stream's reachOffset, whose
other predecessors then paid a move a character.
At the series' end the commit still gains, by less than below
in someTill (0.07% against 0.72%). With its code switched off
at the tip, megaparsec's benchmarks run more instructions, by up
to 0.16% (sepEndBy1) at -O2 and 0.13% at -O1, and none fewer past their
noise; in the benchmark some, the difference is in the ASCII path, which
then sets the width first, as above, and the join's fixup swaps %rbx
and %r14. Without the commit, the same decoding's paths for 2- to 4-byte
characters each set the width before the character while %rax still
holds the array, and end with one more move: a loop of takeWhile
isNumber and foldl' over digits 2, 3 or 4 bytes wide then runs 0.99 more
instructions a character, and no more at 1 byte; none of megaparsec's
benchmarks has non-ASCII input.
Measured on x86-64 against its parent: megaparsec's benchmarks at -O2
run 0.029% fewer instructions over those stable across runs (someTill
0.72%), none more. Of nofib's programs only cacheprof's, k-nucleotide's
and veritas's objects change size, cacheprof's in the order
of its instructions alone and k-nucleotide's in its registers, and none
moves by as much as 0.2%; containers' and vector's benchmarks move
by no more than their noise. The assembly of perf/compiler's T3294,
T12707, T783 and T9961 at -O0 and -O is the same; at -O the stage-1
compiler allocates up to 0.010% more compiling them (T9961) and 0.0063%
and 0.0065% more compiling MR 16269's CmmDiamondChain at -O1 and -O2,
and at -O0 up to 0.0066% more (T9961).
Figures of variants not taken were measured on earlier forms
of the series.
The lines below name the perf tests that the series as a whole moves
below their windows against master; this commit by itself moves none
of them out of its window.
Metric Decrease:
CoOpt_Read
ManyAlternatives
ManyConstructors
T10421
T11545
T12227
T12234
T12425
T12707
T13035
T13056
T13253
T13253-spj
T13379
T13960
T14683
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T1969
T19695
T20049
T20261
T21839c
T24471
T26425
T26989
T3064
T3294
T4801
T5030
T5321FD
T5321Fun
T5631
T5642
T6048
T783
T9198
T9233
T9630
T9675
WWRec
Assisted-by: Claude Opus 5.5
- - - - -
6d29c475 by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Prefer a loop variable's register for the value moved into it
A vreg that the current block moves, where it dies, into another vreg,
such as a loop's next index moved into the index variable before
the jump back to the loop's header, now prefers the first register
that the assignments the block's jumps lead to, a recorded jump target's
or that of a block up to three jumps past a target not yet recorded,
give that other vreg, as it prefers a real register the block moves
it into: processBlock adds such moves to rc_moveDests, from rc_jumpLocs.
In that register the move goes away, and the other vreg is where
the first of those assignments to hold it in a register has it.
A move counts only where the block does not write its source again
(dyingMovesLast): a preference is looked up by the vreg, so it would
otherwise reach the vreg's later value. Where such a move counted,
in nofib's gcd, whose loop ends by shifting loop variables (t2C8 :=
t2Cb, then t2Cb := a new value), the new value took the register
the loop's header gives t2C8, and the jump to the header then had
to exchange two registers through a stack slot: 0.4% more instructions.
dyingMovesLast shares dyingMoves' test of a move where the vreg dies
(dyingMove). The moves into real registers include those of a vreg
the block writes again after the move, its later value then preferring
that register too; leaving them out changed no code measured and costs
compile time.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
containers' benchmarks take 0.10% fewer: map lookup absent and alterF
lookup absent 5.2% fewer, and lookupge-map's GE Twan 2.8% to 3.4%;
fannkuch-redux 0.014% fewer; nofib's programs and vector's benchmarks
move by no more than their noise. No benchmark's allocation changes
beyond nofib's run-to-run noise. The stage-1 compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.011%
or less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
0c50d530 by Mikolaj Konarski at 2026-11-20T00:13:04+01:00
Add a union sharing the first map's subtrees to GHC.Data.Word64Map
GHC.Data.Word64Map gains unionShared, exported as union is,
and GHC.Types.Unique.Set gains unionUniqSetsShared, its form
at UniqSet's type and with unionUniqSets' bias. For all maps,
unionShared m1 m2 equals union m1 m2, the same trie with m1's value
where both maps have the key; but it walks the two tries together,
handing a part of m2 with a key outside the range of the subtree of m1
it has reached to union with that subtree, and returns a subtree
it reaches unchanged where m2's part of it is the same object,
by reallyUnsafePtrEquality#, a key the subtree has or empty, or where
the walk returns both halves of the subtree unchanged. So where m2 has
no key that m1 lacks, the result is m1 itself. The pointer test only
saves work and sharing: where it answers False for the same object,
the result is still equal. Where the two maps were made from one map
by k insertions and deletions and m2 has no key that m1 lacks, it takes
O(k * min(n, W)) where union takes O(n + m). The next commit's
regClobbers unites with it the sets of registers live across
instructions, which the liveness pass builds from one another, where
unionUniqSets copies the whole set at every union.
Tested against union over pairs of maps made from one another
by insertions, deletions and changes of values, or independently,
with keys dense, sparse and over the whole 64-bit range and each value
naming the map and the edit or key that gave it: each result equals
union's, with m1's values, and is m1 itself wherever m2 has no key
that m1 lacks; a variant keeping m2's value at a common key fails
the first, and one handing an empty m2 to union, whose result there
was not m1 itself, the second. GHC's testsuite has no test
of GHC.Data.Word64Map or of GHC.Types.Unique.Set, and none is added.
Assisted-by: Claude Opus 5.5
- - - - -
af3e2cc9 by Mikolaj Konarski at 2026-11-20T00:13:04+01:00
Order x86-64 free registers around R1 and clobbers (ISSUE 27981)
On x86-64, where none of its preferences is free, a vreg now takes R1's
register, %rbx, last in each of the two parts below: an evaluation
and a return write it, so a value given it may have to move out of their
way, and a loop variable given it at the loop's entry moves at every
iteration (ISSUE 27981). Before the others it takes the registers
no instruction writes while the vreg is live past the write: for a vreg
live across a C call, these are the registers the call preserves,
on System V R2's %r14 and %rbx, and for one still live where an argument
is moved into R2's %r14 for a jump, they exclude %r14. Given a register
such an instruction writes, the vreg would have to move out of the way.
Where no preference is free, firstFreeInOrder leaves out the free
registers the block moves other vregs into where they die, and takes
the first of the rest; on x86-64, where the allocator's context holds
regClobbers' map (rc_clobbers, Nothing elsewhere), it takes the one
fallbackReg picks, the first free register in this order, R1's register
taken from a constant rather than from globalRegMaybe at every call.
Where the block moves no other vreg into a register where it dies,
firstFreeInOrder hands fallbackReg the free registers themselves, rather
than a filtered copy. In the reproducer of ISSUE 27981 this commit
already removes the back edge's fixups; the next commit removes
the cause the issue names. In T27800, the test of ISSUE 27800,
the continuation's edge into the loop no longer swaps through a spill
slot, and T27800.stderr, which expected those lines, is deleted.
regClobbers finds, for each vreg, the registers written while
it is live, once a procedure on x86-64: the liveness pass now records,
at each instruction that writes a real register, the registers live
after it (liveAcross), and regClobbers adds the written registers
to every vreg among those that is live past the instruction, as bits
by register number, finding the vregs an instruction writes once
for the instruction rather than once for each vreg live past it;
and firstFreeInOrder binds strictly the vreg's first-used preference,
which noPrefs reads a second time. Only x86-64's fallback uses them,
and on the other targets RA_Context's field is empty, so that no unread
thunk keeps the procedure's code alive. patchRegsLiveInstr, which
rewrites an instruction's registers after liveness for the graph
allocator, leaves liveAcross as liveness made it, the linear allocator
alone reading it, before any register is rewritten; the review question
of the README in compiler/GHC/CmmToAsm on rewriting registers after
liveness names liveAcross beside liveUsage. A move of the vreg itself
into a register is no such write. Where the vregs live past a write
number more than 24, as at most divisions of MR 16269's CmmDiamondChain,
regClobbers unites them with those live past the earlier writes
of the same registers and marks each union's vregs once at the end,
rather than looking each up at every write; a smaller set is marked
a vreg at a time, and the masks are the same either way. The union,
unionUniqSetsShared over the previous commit's unionShared, returns
the newer set itself where the accumulated set adds nothing to it:
the liveness pass builds the sets live across consecutive instructions
from one another, so the accumulated set stays the newest set itself
and a union walks only the few paths that differ. With unionUniqSets,
which copies the whole set, the stage-1 compiler ran 3.5% more
instructions compiling the battery's scaling program ccalls, 400 C calls
in one block, at -O1, and 0.13% to 0.15% more instructions and 0.86%
to 1.0% more allocation compiling CmmDiamondChain, against figures below
measured with it. It tests an instruction for registers live past it,
a set the liveness pass leaves empty where the instruction writes
no real register, before it computes the mask of the registers written,
which is then not 0, as a debug compiler asserts, and counts a set's
members only up to the threshold. Leaving out the writes in the blocks
that follow a failed check costs containers' lookupge-intmap Milan
lookups 0.5 to 1% more instructions, a failure block's write having kept
a vreg, by accident, out of a register that a later vreg is moved into;
Note [Frequencies before register allocation] gains a bullet
on the case, with a TODO at regClobbers. Andreas Klebinger's MR 16693,
read before this commit was written, charges a vreg for each register
that an instruction in a loop starts writing while the vreg is live
across it, and this order overlaps with that clobber cost: both steer
a vreg away from the registers written while it is live, MR 16693
by a cost counted within loops, this commit by the order of the free
registers, from the writes met anywhere the vreg is live.
On x86-64, for a vreg that has preferences, all of them taken,
fallbackReg also leaves out, where a free register would remain,
the registers that one of the assignments the block's jumps lead to,
a recorded jump target's or that of a block up to three jumps past
a target not yet recorded (rc_jumpLocs), gives another vreg, so
that the vreg does not take a register that a jump on the way there will
need for that one: a part of what ISSUE 26666 asks.
fallbackReg also leaves out, where others remain, the free registers
that the blocks up to three jumps ahead that the vreg is live into move
another vreg into where it dies, the vreg's own such destinations
excepted: given one, the vreg would keep the other from being computed
in it, or have to move out of its way there. Not for a vreg live across
a C call, which leaves its register at the call anyway: a block after
the call, such as k-nucleotide's copy of a new key, would put it
on an argument register that the call's own setup needs,
and the arguments were swapped through %r9. Nor where a jump target
not yet recorded that the vreg is live into has two or more
predecessors, those after a failed heap or stack check not counted:
its register there binds them all, and a walk from one of them reaching
a rare exit put megaparsec's manyTill counter on a register its hot
predecessor holds, a move in the join's fixup. With this look-ahead
IntMap's union-mix_sn_swap, union-mix_nn and union-mix_nn_swap take
fewer instructions at -O2, and at -O1 intmap fromAscList,
fromAscList:fusion and intset fromAscList:sparse. The look-ahead costs
the compiler instructions and allocation compiling perf/compiler's T3294
and MR 16269's CmmDiamondChain at -O0; in this commit's own figures
the saving of R1's constant and of choosing the fallback by rc_clobbers
cancels most of it. The look-ahead's walk keeps, for each block it walks
on from with two jumps or more left, the most jumps it had left there,
and walks on from the block again only with more, so that raising
its limit of three would not make it exponential in the jumps; at three
this costs hardly any more instructions compiling nofib's puzzle at -O2,
and the code is the same. The masks by register number this commit adds,
regClobbers', that of the registers in the assignments in rc_jumpLocs
that fallbackReg leaves out and the look-ahead's (dyingIn's for each
block, and lastDestBit's for the vreg's own destination, in the upper
half), assert where they are built that each number they set is below
64, and below 32 in lastDestBit, and aheadWalks that a block's mask has
no bit from 32 up: setBit and bit set nothing past the range, so
that a register numbered past it would drop out of the preferences
in silence, and x86-64 numbers its registers 0 to 31. Only a compiler
built with assertions on checks them, and none was built; in the perf
flavour they cost nothing, measured at the series' end: nofib's assembly
at -O1 and -O2 and that of the compile cells is the same, and no cell
moves by 0.001% in instructions or allocation.
raInsn no longer drops a move from one vreg into another, giving
the destination the source's register, where one of the assignments
the block's jumps lead to, a recorded jump target's or that of a block
up to three jumps past a target not yet recorded (rc_jumpLocs), has
the destination in a free register other than the source's and another
vreg in the source's: the move then puts the destination where
that assignment has it, and a jump on the way there does not have
to swap it with that other vreg, as in containers' IntSet compare
(intset instanceOrd:dense). Where none has a vreg in the source's
register, the move is dropped as before, the jump moving the destination
on its own edge rather than the move running on every path out
of the block.
The expected assembly of codeGen/should_gen_asm's
bytearray-memcpy-unroll and bytearray-memset-unroll names other
registers now; the instructions and their order are the same.
Simpler forms cost more. %rbx last for every vreg costs up to 3% more
instructions in procedures that make C calls. %r14 first as well,
wherever no vreg is live across a C call, gains in some loops but costs
up to 3% more elsewhere, where %r14 is used later, for R2 or in a jump
target's recorded assignment. Taking the registers a C call preserves
first for every vreg live across one, ignoring every other write, makes
fannkuch-redux take 1.3% more instructions: a loop variable live across
a call elsewhere in the procedure is given %r14 and moves out of R2's
way at every iteration.
Measured against the parent commit, in instructions: nofib's programs
take 0.40% fewer (fasta 5.3%, k-nucleotide 4.3%, bspt 2.4%; 0.48%
at -O1, 0.099% at -O0), none as much as 0.2% more beyond their
run-to-run noise; fannkuch-redux 0.22% fewer; vector's benchmarks 1.3%
fewer (nextPermutationBijective 4.4%, findIndexR 3.4%), none more
than 0.001%; containers' benchmarks 0.38% fewer (intset partition 6.1%,
intset filter 5.2%, graph buildG 0.54% to 3.9%); megaparsec's benchmarks
1.5% fewer (reachOffsetNoLine 7.6%, many 6.6% to 6.8%). No benchmark's
allocation changes beyond nofib's run-to-run noise. The stage-1 compiler
allocates 0.13% more compiling perf/compiler's T3294, 0.28% more
compiling T12707, 0.18% more compiling T783 and 0.32% more compiling
T9961, each at -O0, and 0.069% or less at -O and -O2. Compiling MR
16269's CmmDiamondChain, it allocates 1.6% more at -O0 and 1.3% more
at -O1 and -O2. A stage-1 compiler runs 3.2% more instructions
than the parent's compiling CmmDiamondChain at -O0 and 2.7% more at -O1
and -O2, and 1.2% more compiling T9961 at -O0, every other cell
under 1%. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 20% more (9.14 against 7.61 GB)
and GHC.CmmToAsm.Reg.Liveness 14% more (2.67 against 2.34 GB).
That compile cost is a trade, its toggle regClobbers' map: left empty,
so that the fallback orders the free registers without the clobbering
writes, it takes the commit's compile cost against its parent to 0.9%
for CmmDiamondChain at -O0 and 0.75% at -O1 and -O2, and to 0.18%
for T9961 at -O0; but the assembly of CmmDiamondChain, of T12707
and T3294 at -O0 and of T9961 at -O and -O2 changes, and so does
that of nofib programs at each level, of which, compiled by stage-1
compilers over the same libraries and run as nofib runs them, shootout's
fasta takes 5.5% more instructions at -O2, k-nucleotide 3.1%
and fannkuch-redux 2.3% more, wheel-sieve2 1.2% and wheel-sieve1 1.1%
more, and all of them together 0.25% more at -O2 and 0.15% at -O1
and the same to 0.01% at -O0, none 0.2% fewer. The map is kept,
and its cost with it.
The rises in containers are trades, each with a toggle. At -O1 IntSet's
union-common and union-mix take 0.44% to 0.84% more, union-block 0.26%
to 0.40% and IntMap's union-common 0.15% to 0.51%, and no later commit
takes them back: union_info loads the subtree field into %rdi rather
than %rsi, and each of its recursion-call blocks adds a move,
the partition of the free registers by clobbering writes being tied,
the field moved into %rsi on two paths while %rsi is written
on the third; which side wins depends on how the input sets overlap.
Not counting as clobbered a vreg's own dying-move destinations up
to three jumps ahead, except for vregs live across a C call, takes them
back, but makes intset fromAscList:sparse take 2.64% more, map
fromListWith-desc and its siblings 0.87% to 1.08% more, IntSet's
and IntMap's symmetricDifference common, mix and block rows 0.30%
to 0.59% more and Map's union-common_nn 0.49% more (-O2), and costs
0.27% more compile allocation for T3294 at -O0. map
fromListWith-desc:fusion takes 0.98% more at -O2: of four
specialisations of one insertion loop, which share R4 between two
subtree fields, the order wins three, and the variant that wins
the fourth makes the other three take 1.0% to 1.1% more. At -O1
the fused fromAscList family, intmap lookup_misses and map
fromList-distinctAsc:fusion take more by R1's place last in the order;
R1 in its natural place reverts them, but brings back graph buildG's
rise of "Prefer the register a later block moves a vreg into where
it dies" (up to 2.2%) and makes intset folds:dense foldr'_maximum take
5.8% more. intset mapMonotonic takes 1.27% more at -O2, the order
putting %rsi after %rax so that the hot path's reload cannot take %rax;
leaving out the registers the assignments in rc_jumpLocs give other
vregs for vregs without preferences too fixes it, but makes set
alterF:insert:present take 2.4% more, alterF:delete:absent 2.7% and map
fromAscList:fusion 1.9%. intset fromList:randomDups:fusion takes 0.55%
more at -O1; R1 in its natural place for vregs that die in their block
fixes it, but gives back folds:dense foldr'_maximum's gain (5.5%)
and folds:sparse foldr'_maximum's (0.9%). At -O2 intset
difference-block_sn_swap takes 54 instructions more (0.32%)
and difference-block_ns 54 fewer: in IntSet's difference the partition
of the free registers by clobbering writes moves a reload off %rsi,
and a move goes from the two blocks that tail-call one specialisation
to the two that tail-call the other; which of them is hot decides
between the rows. Not partitioning the free registers by clobbering
writes takes difference-block_sn_swap back, where the union rows' toggle
makes it take more still, but then containers' benchmarks take 0.040%
more at -O2 by the geometric mean, 137 rising and 58 falling (graph dfs,
dff and topSort on maxDAG n=1500 1.8%).
In the sample of orthotope's A2T benchmark twelve cells over small
arrays take one instruction a call more (0.21% to 0.29%), eleven of them
trades of two parts of this commit, each shown by its toggle
and not traced in the code. Three, generate.scalar over strided Storable
arrays in Shaped, Ranked and Dynamic, take more by R1's place last
in the order: R1 in its natural place takes them back and moves 181
cells of the sample, 80 up and 101 down, but makes set
fromAscList:fusion take 1.55% more at -O2. The other eight, Shaped's <$,
pure, stretchOuter, rnf, update.none, concatOuter.one, append.emptyR
and append.emptyL over boxed arrays, take more by fallbackReg leaving
out, for a vreg with preferences, the registers the assignments
in rc_jumpLocs give other vregs: with that left out the eight are back,
but 144 cells move, 91 up and 53 down, toList over small strided boxed
arrays taking 2.3% more and reduce 1.9% more. The compile cost
this commit adds on the battery's scaling program claims, a loop whose
body is one block of N steps, grows linearly with N and is mostly
that of the same exclusion, a trade: at -O0 and N=800 the stage-1
compiler allocates 4.2% more than the parent's and runs 4.6% more
instructions, the differences twice those at N=400, and without
the exclusion 89% of the added bytes and 67% of the added instructions
go, but then over the whole A2T benchmark, not its sample, 47 cells take
more instructions by over 0.2% and 14 fewer, 0.028% more
by the geometric mean, and megaparsec's benchmarks 0.024% more at -O1
(manyTill 0.33%).
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
926bf688 by Mikolaj Konarski at 2026-11-20T00:13:04+01:00
Free every register not live into a newly reached block (ISSUE 27981)
On the first jump to a block, joinToTargets_first recorded, beside
the block's assignment, the block's free registers, the source block's
with those of the vregs not live into the target released, and initBlock
started the block with them. A real register still allocated at the jump
and not live into the target, R1 above all where it is allocatable,
therefore stayed allocated in the target block until the block wrote
it and that value died: a value the block reloads cannot go back to it,
and the block's jumps may need fixup moves. initBlock now derives
the free registers on entry to every block: every allocatable one
but the real registers live into it and those holding the vregs
of its recorded assignment, if it has one; a recorded assignment
no longer carries free registers, and joinToTargets no longer computes
the registers to release (to_free), nor needs FR. In its reproducer
the previous commit already removes the fixups, so the reproducer does
not show this fix alone; its inline form, too, runs as many instructions
an element as with the parent commit. The test, T27981, is ISSUE 27981's
reproducer, its allocator statistics searched for fixup moves: it passes
with the parent commit's compiler, which already removes them, and fails
with that commit's parent's, which puts them on the loop's back edge.
allocateRealRegs marks the real registers among those live into a block
allocated, and is INLINABLE, so that x86's allocator runs
it specialised: with the pragma, the compiler runs up to 0.55% fewer
instructions compiling MR 16269's CmmDiamondChain at -O0 than without
it, and allocates up to 0.013% less compiling nofib's puzzle at -O0.
initBlock takes the procedure's initial free registers from RA_Context
(rc_initFree) rather than rebuild them for each block; runR starts
the allocator with them too, and with an empty block assignment,
register assignment and stack map, taking none of them as arguments;
joinToTargets_first, left with two statements, is inlined by hand
at its one call site.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs, vector's benchmarks and fannkuch-redux move by no more
than their noise; containers' benchmarks take 0.035% fewer (tree edges
1.4%, graph transposeG 1.3% and buildG 1.1%), none more beyond their
noise, and megaparsec's 0.25% fewer (many 1.2%, sepEndBy 0.85%
to 0.88%), none more. No benchmark's allocation changes beyond nofib's
run-to-run noise. The stage-1 compiler allocates 0.16% less compiling
perf/compiler's T3294, 0.74% less compiling T12707, 0.75% less compiling
T783 and 1.1% less compiling T9961, each at -O0, and up to 0.25% less
at -O and -O2. Compiling MR 16269's CmmDiamondChain, it allocates 4.3%
less at -O0 and 3.6% and 3.5% less at -O1 and -O2.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
61601520 by Mikolaj Konarski at 2026-11-20T00:13:05+01:00
Write the linear allocator's state only where it changes
releaseRegs, which genRaInsn calls twice for every instruction,
with the registers the instruction reads for the last time and
those it writes that die at once, wrote the assignment and the free
registers back to the allocator's state even where it had no register
to release; saveClobberedTemps, for every instruction that writes a real
register, folded over the whole assignment in the monad and wrote
it back even where no value sat in a clobbered register. Each write
builds a new RA_State. releaseRegs now returns at once where it has
nothing to release, and saveClobberedTemps picks the values to save
by a pure fold, in the order the monadic one took them, and writes
the state only where there are some. Both now take the dying registers
as the set the liveness annotation holds, where master's genRaInsn
listed the set's registers at every instruction for them: releaseRegs
folds over the set, and saveClobberedTemps tests a value's register
for membership in it. The generated code is the same.
The stage-1 compiler allocates 3.1% less compiling perf/compiler's T3294
at -O0 and 1.1% less at -O, 2.1% less compiling T12707 at -O0 and 0.69%
less at -O, 1.8% less compiling T783 at -O0 and 0.29% less at -O,
and 3.0% less compiling T9961 at -O0, though 0.016% less at -O.
Compiling MR 16269's CmmDiamondChain, it allocates 9.1% less at -O0
and 7.5% and 7.4% less at -O1 and -O2.
Assisted-by: Claude Opus 5.5
- - - - -
f7dcd444 by Mikolaj Konarski at 2026-11-20T00:13:05+01:00
Find the linear allocator's spill candidates in one fold
Where no register of a vreg's class is free, allocRegsAndSpill_spill
frees the register of another vreg: the first one that is in a register
and in a stack slot, else the first one only in a register, among
those it need not keep. It found them by filtering the whole assignment
to the vregs in a register, deleting those to keep, listing the rest
and searching the list twice. It now folds over the assignment once,
keeping the first vreg of each kind, in the order the list had them.
The generated code is the same.
The stage-1 compiler allocates 9.3% less compiling perf/compiler's T3294
at -O0 and 4.0% less at -O, and 0.51% less compiling T12707 at -O0;
its allocation compiling T783 and T9961 rises by 0.0055% or less.
Compiling MR 16269's CmmDiamondChain, it allocates 0.41% less at -O0
and 0.33% less at -O1 and -O2.
Assisted-by: Claude Opus 5.5
- - - - -
5f9868ff by Mikolaj Konarski at 2026-11-20T00:13:06+01:00
Walk register assignments without listing them
clobberRegs listed the whole assignment, for every instruction
that writes a real register, to move the vregs that are in a clobbered
register and in a stack slot to the slot only. saveClobberedTemps' fold
over the assignment, which picks the vregs in a clobbered register
to save, now picks those too and records them InMem, as it now records
a vreg it spills, so that master's clobberRegs only marks the clobbered
registers allocated. joinToTargets_again listed the recorded assignment
of a jump target and the current one, restricted to the vregs live
into the target, to compare them ignoring the formats. Master's
joinToTargets' now passes it the whole current assignment,
and recordedLocsHold tests on the two maps themselves that every vreg
of the recorded assignment is at its recorded location: a recorded
assignment holds only vregs live into its block,
and makeRegMovementGraph moves only the vregs it holds. The generated
code is the same but for the numbering of fixup labels after a jump
at which a vreg live into the target has a location that the recorded
assignment does not give it.
The stage-1 compiler allocates up to 0.095% less (T9961 at -O0),
and at most 0.00017% more, compiling perf/compiler's T3294, T12707, T783
and T9961. Compiling MR 16269's CmmDiamondChain, it allocates 6.9% less
at -O0 and 5.6% and 5.5% less at -O1 and -O2.
Assisted-by: Claude Opus 5.5
- - - - -
737add03 by Mikolaj Konarski at 2026-11-20T00:13:06+01:00
Sort a procedure's blocks only where its first block is not first
regAlloc sorted the linear allocator's blocks to keep the procedure's
first block at the front; it now sorts them only where that block
is not at the front already. The generated code is the same.
The stage-1 compiler allocates 0.094% less compiling perf/compiler's
T3294 at -O0, 0.33% less compiling T12707 at -O0 and 0.12% less at -O,
0.29% less compiling T783 at -O0 and 0.083% less at -O, and 0.51% less
compiling T9961 at -O0.
Assisted-by: Claude Opus 5.5
- - - - -
86f29929 by Mikolaj Konarski at 2026-11-20T00:13:07+01:00
Compute the dying registers and the live-in map of liveness strictly
liveness1 left, in each instruction's liveness, the registers read
for the last time there and those written there that die at once
as thunks, which the linear allocator forces at every instruction;
livenessSCCs likewise left the map of the registers live into each block
to be computed later, through the acyclic SCCs. They are now computed
as the liveness pass goes, but for the registers that die at a branch
because they are live into its targets only: livenessCyclic walks
a block again whenever a successor's live-in set has changed and keeps
only its last walk, and computing that set at every walk made
the stage-1 compiler run 8.8% more instructions than the parent commit's
compiling the battery's scaling program nest, 400 loops nested in one
procedure, at -O1, against 0.6% more with the set lazy, to save at most
0.045% of its allocation (T9961 at -O0). The generated code is the same.
The stage-1 compiler allocates 0.77% less compiling perf/compiler's
T3294 at -O0 and 0.25% less at -O, 0.55% less compiling T12707 at -O0
and 0.19% less at -O, 0.65% less compiling T783 at -O0 and 0.13% less
at -O, and 0.66% less compiling T9961 at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
1939d3d5 by Mikolaj Konarski at 2026-11-20T00:13:07+01:00
Skip the address registers x86's mkRU would drop
regUsageOfInstr on x86 and x86-64 added every register an address names
to an instruction's register lists, and mkRU then filtered out the ones
the allocators do not manage, such as Sp's %rbp, Hp's %r12 and BaseReg's
%r13, copying each list that held one: those of every access
to the stack or the heap. An address's registers that mkRU would drop
are now left out where they are added. This commit is a subset
of Sylvain Henry's MR 16843, whose register usage DSL adds each
register, an address's included, only where the allocators manage it.
The generated code is the same.
The stage-1 compiler allocates 0.83% less compiling perf/compiler's
T3294 at -O0 and 0.28% less at -O, 0.38% less compiling T12707 at -O0
and 0.12% less at -O, 0.35% less compiling T783 at -O0, and 0.25% less
compiling T9961 at -O0.
Assisted-by: Claude Opus 5.5
- - - - -
7f026802 by Mikolaj Konarski at 2026-11-20T00:13:07+01:00
List a CFG's edges once in block layout
sequenceChain listed the edges of the CFG twice, once for the chains
it builds and once for the edges left between them; it now lists them
once. The sets of the edges that buildChains and combineNeighbourhood
fuse, master's Sets of pairs of BlockIds, are now LabelMaps from each
block to the LabelSet of the blocks its fused edges enter,
and combineNeighbourhood lists each of its chains once by taking
it at the lowest of its ends, where master removed the repeats
with nubOrd. The generated code is the same.
The stage-1 compiler allocates 0.12% less compiling perf/compiler's
T12707 at -O, 0.16% less compiling T783, and 0.031% less compiling
T3294; at -O0 its allocation rises by 0.0019% or less. Compiling MR
16269's CmmDiamondChain at -O1 and -O2, it allocates 0.30% less.
Assisted-by: Claude Opus 5.5
- - - - -
f2f3f9c7 by Mikolaj Konarski at 2026-11-20T00:13:08+01:00
Build no lists of results in calcFreqs
calcFreqs, which static prediction runs for every procedure, built
a list of results for each block's out-edges (forM in calcOutFreqs) and,
for each block's predecessors, a list of Bools to test for irreducible
flow and a list of probabilities to sum. It now uses forM_, anyM
and a left fold from 0, which adds the probabilities in sum's order,
so that the frequencies are the same, and so is the generated code.
isBackEdge, master's, looks an edge up in an IntMap of IntSets rather
than in a Set of pairs.
At -O the stage-1 compiler allocates up to 0.099% less compiling
perf/compiler's T3294, T12707, T783 and T9961 (T12707); at -O0, where
static prediction is off, its allocation moves by 0.0045% or less.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.31%
less.
Assisted-by: Claude Opus 5.5
- - - - -
5603ac7e by Mikolaj Konarski at 2026-11-20T00:13:08+01:00
Give back edges no bonus where static prediction estimates the weights
optHsPatterns raised every back edge of positive weight by backEdgeBonus
(increaseBackEdgeWeight), after a depth-first search for them;
under -fcmm-static-pred, on at -O1 and -O2, staticPredCfg then replaces
the weights of the branches its heuristics cover with its predictions
and estimates frequencies from them. The bonus is now left out there:
optHsPatterns takes the back edges to raise, which optimizeCFG gives
as none where static prediction follows and as findBackEdges' elsewhere,
and the procedure's map of info tables in place of the procedure,
its equation for CmmData deleted: optimizeCFG, its one caller, returns
a CmmData's CFG unchanged. The bonus counted only at the branches static
prediction leaves alone, a heap or stack check's and those whose targets
are all back edges, and at a two-way branch back into the procedure's
entry, whose weights static prediction starts from, loopInfo counting
no edge into the entry a back edge. Leaving it out of those as well
changed no code measured. The generated code is the same on every
program measured: perf/compiler's T3294, T12707, T783 and T9961 at -O0
and -O, and nofib's programs at -O2 and -O1, whose objects
are identical.
At -O the stage-1 compiler allocates up to 0.15% less compiling
perf/compiler's T3294, T12707, T783 and T9961 (T783); at -O0, where
static prediction is off, its allocation moves by 0.00054% or less.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.47%
less.
Assisted-by: Claude Opus 5.5
- - - - -
d20eab44 by Mikolaj Konarski at 2026-11-20T00:13:09+01:00
In sccBlocks, look blocks up in the CFG, not in a set of them
sccBlocks, in GHC.CmmToAsm.Reg.Liveness, built a set of every block
of the CFG, which holds only reachable blocks, to keep the procedure's
blocks that are in it; it now looks each block up in the CFG itself.
The generated code is the same.
The stage-1 compiler allocates up to 0.24% less compiling
perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T783), and up
to 0.059% less at -O (T783). Compiling MR 16269's CmmDiamondChain at -O1
and -O2, it allocates 0.11% less.
Assisted-by: Claude Opus 5.5
- - - - -
2b473b71 by Mikolaj Konarski at 2026-11-20T00:13:09+01:00
Inline x86's takeRegRegMoveInstr
takeRegRegMoveInstr, which the register allocators and the liveness pass
call on every instruction they look for a register-to-register move in,
built a Just and a pair for each move it found. Most callers take both
apart at once. Inlined, it builds neither where its caller takes them
apart. The generated code is the same.
The stage-1 compiler allocates up to 0.13% less compiling
perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T9961); at -O
its allocation moves by 0.012% or less. Compiled by the boot compiler,
GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 12% more (9.23 against
8.22 GB).
Assisted-by: Claude Opus 5.5
- - - - -
47c937c7 by Mikolaj Konarski at 2026-11-20T00:13:09+01:00
Swap the registers of a cyclic join fixup where one instruction can
Where a jump's target has a recorded assignment, joinToTargets moves
the vregs into it, and where the moves form a cycle, handleComponent
spilled one source to its stack slot and reloaded it
into its destination after the other moves: a store and a load,
and a stack slot the vreg may not have had. The Instruction class now
has mkRegRegSwapInstr, which gives an instruction that swaps two
registers of a format where there is one, and by default Nothing; on x86
and x86-64 it is xchg for the general-purpose registers. handleComponent
now swaps a cycle's first source with its destination where it can,
so that a cycle of n moves takes n - 1 swaps; it spills as before
otherwise, as for floating-point and vector registers. An xchg is two
micro-ops on Zen 3, but breaking a cycle through a free register
instead, with three movs, ran in as many CPU cycles there and took more
instructions (megaparsec's benchmarks 0.114% more instructions at -O2,
skipManyTill 2.1% more); breaking floating-point cycles through a free
register changed nothing measured, the register cycles it would convert
occurring only a few times in all the suites. With master's allocator,
orthotope's $w$s$wequalT1 and $w$s$w$ccompare1 break register cycles
through stack slots.
The stage-1 compiler's allocation compiling perf/compiler's T3294,
T12707, T783 and T9961 moves by 0.0054% or less at -O0 and -O.
Of nofib's programs only puzzle moves by more than 0.2% in instructions:
it runs 0.41% fewer, and 0.7% fewer cycles. containers' benchmarks move
by less than 0.1% but for graph bcc.star,n=100, which runs 0.23% fewer;
vector's quickhull runs 0.99% fewer at -O1, its other benchmarks moving
by 0.028% or less, and megaparsec's run 0.40% fewer (skipManyTill 4.0%,
endBy1 1.4% to 1.7%), none more. In megaparsec's count, sepBy
and sepEndBy and in vector's quickhull, cycles through stack slots
become xchg instructions.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
9a831313 by Mikolaj Konarski at 2026-11-20T00:13:10+01:00
Store no value into the slot holding it at a join
expandNode turned a vreg that is InBoth in the same stack slot at both
ends of a join into a store into that slot, beside a register move where
the registers differ and alone where they do not, though the slot
already holds the value. Such a vreg now needs at most the move.
expandNode is now one closed form in place of master's cases: a vreg
already in place needs no move, and otherwise the value is moved
from the source's register where it has one, to the destination's
register unless it is the source's, and to the destination's slot unless
it is the source's, the register before the slot. Master's alternatives
and their recursive call give the same moves but for a destination slot
that is the source's, into which they stored the value.
Measured on x86-64 against its parent, in instructions: the change
removes stores and nothing else. vector's benchmarks take 0.28% fewer
at -O2 (leaffix 5.26%, rootfix 2.81%); nofib's programs move by less
than 0.2% at -O2, -O1 and -O0, and no benchmark of containers, vector
or megaparsec rises beyond its noise. The stage-1 compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 and MR 16269's
CmmDiamondChain moves by 0.014% at most.
Assisted-by: Claude Opus 5.5
- - - - -
28337a44 by Mikolaj Konarski at 2026-11-20T00:13:10+01:00
Make a join's slot-to-slot move through a free register (ISSUE 27638)
A vreg gets a new stack slot where its format outgrows its old one
(getStackSlotFor, ISSUE 26668), as a Double's does when x86's broadcast
writes its register in place at DoubleX2# (vector_float_broadcast_sse
and _avx shuffle the register of a Cmm local). On two paths to a join
it can then be in memory only, in a different slot on each,
and the join's fixup needs a move from one slot to the other, on which
makeMove panicked ("we don't handle mem->mem moves").
makeMove now moves the value through a register free at the jump,
at the narrower of the two formats, no more than the source slot holds
or the destination slot takes; where no register of that format's class
is free and the format is at most a word wide, through an integer
register free at the jump; and otherwise by the Instruction class's new
mkSlotSlotMoveInstr: on x86 and x86-64 a word at a time through %eax
or %rax, saved in the destination's first word and given back
by an exchange. Elsewhere the method gives Nothing, its default,
and makeMove panics with a message of its own. Such a move
is a component of its own in the graph of the fixup's moves, both slots
being its vreg's, so joinToTargets_again makes these moves before
the others, while every register free at the jump holds nothing;
joinToTargets needs FR again, for the free registers.
The exchange, XCHG with a memory operand, is locked whatever its prefix,
so it costs more cycles than the one instruction it counts as; how many
was not measured. PUSH of each source word and POP
into the destination's would need no lock, no register and one
instruction fewer, but between the two the stack pointer is a word lower
and nothing tells the unwinding tables, which get a row at each DELTA
from an UNWIND whose label the method cannot make. The move is rare:
at the series' end nofib's modules at -O1 and -O2 hold XCHG between
registers only.
Where the jump's target expects the value in a register as well
as in the other slot, handleComponent instead loads that register
from the source slot and stores the register into the other slot
at the narrower of the two formats, needing no free register;
the slot-to-slot move, and its panic, are left to a value the target
expects in a slot only. That fixup is in no cycle either, its source
slot being the vreg's own, and no other move of the fixup writes
the register or the slot. handleComponent loses master's argument
of the jump instruction, which none of its equations read, the cyclic
one only passing it on to its own recursive calls.
The test, T27638, broadcasts a Double in one arm of a case between two C
calls; the parent commit's compiler panics compiling it at -O0, -O1
and -O2. Its variants: T27638a broadcasts a Float#; in T27638b the other
arm, which comes first, the broadcast being the default, uses the Double
again, so that the jump's target expects it both in a register and
in a slot; in T27638c nineteen Doubles are live at the join, so
that the move goes through a general-purpose register, and in T27638d
thirteen Int#s beside them, both compiled at -O; T27638f, compiled
at -O, is T27638d with the other arm using the Double again and first,
as in T27638b, and with eleven Int#s loaded after the Doubles,
and T27638g, compiled at -O, is T27638d with eleven Int#s loaded after
the Doubles, so that no register is spare at its join. The parent
commit's compiler panics on T27638a and T27638b at -O0, -O1 and -O2
and on T27638c, T27638d, T27638f and T27638g at -O1 and -O2,
and this commit's compiler without mkSlotSlotMoveInstr panics on T27638g
at -O1 and -O2. This commit's compiler sends T27638b through the fixup
into a register and another slot at -O0, -O1 and -O2 and T27638f at -O1
and -O2, and both compile and run to their outputs at -O0, -O1 and -O2.
Without both the new equation and mkSlotSlotMoveInstr it panics
on T27638f at -O1 and -O2, no register of either class being spare
at its join; T27638b, with a register spare at its join, it compiles,
moving the value through that register. At the series' tip the compiler
without the equation and the method likewise panics on T27638f at -O1
and -O2, and with them compiles T27638b and T27638f, which run to their
outputs at -O0, -O1 and -O2. With the fix, ISSUE 27638's own reproducer
(T27638e, compiled at -O), where move coalescing gives a Double vreg
a dying vector's location and format, compiles at -O1 and -O2, as does
a generated program that panicked at -O0, its output master's.
Cost: compiling perf/compiler's T3294, T12707, T783 and T9961 and MR
16269's CmmDiamondChain at -O0, -O1 and -O2, the stage-1 compiler runs
at most 0.0062% more instructions (T9961 at -O0) and allocates at most
0.011% more (T9961 at -O), the assembly the same in every cell; measured
on an earlier form of this commit, the stage-2 compiler ran up to 0.060%
more instructions compiling nofib's puzzle (at -O0), its allocation
moving by 0.002% or less. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear.JoinToTargets allocates 29% more (0.684 against
0.529 GB) and its object is 36% larger, the cost of makeMove's
slot-to-slot clause.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
7a427822 by Mikolaj Konarski at 2026-11-20T00:13:11+01:00
Predict branches into loop heads that only a heap or stack check makes
staticBranchPrediction's loop exit heuristic, lehPredicts, says nothing
about a branch into a loop head. A heap or stack check that fails calls
the garbage collector, which returns to a block that jumps back
to the check, and loopInfo counts that cycle as a loop; so in a loop
that holds such a check, the check's block is a loop head,
and the heuristic said nothing about the test that stays in the loop
by branching to it. loopHeads now leaves out a head whose back edges all
leave a block of coldBlocks, and the loop levels the heuristic compares
count only the loops left: counting the others too would put a block
that heads only such a cycle a level deeper than its siblings,
so that the heuristic would predict any branch into it. The set
is coldBlocks, not checkFailures: static prediction runs after register
allocation, so the cycle can close from a block the allocator put after
one that follows the failed check, which coldBlocks holds
and checkFailures does not. loopInfo no longer counts loop levels
(liLevels), which staticBranchPrediction now counts over the loops left,
and loopLevels and loopMembers, which had no caller, go, with the import
of GHC.Data.Graph.Directed that only loopMembers used. A back edge
leaving a continuation that a call returns to as well as the garbage
collector counts the same, so a loop closed through such a call loses
its head too; telling the two apart moved no figure measured.
As committed, with the levels limited, this shows no saving in cycles:
nofib's programs ran 0.3% more in geometric mean (below). The saving
sought is in cycles, not instructions: with the stay side predicted,
the layout can let it fall through, a taken jump fewer an iteration,
and a conditional jump is one instruction whether taken or not. Before
the levels were limited, lookupGE3's loop in containers' lookupge-map
took one jump an iteration instead of two, the tag test's jump backward
in the layout to the heap check and then one out of the comparison,
and GE Twan ran 2% to 11% fewer cycles at no more than 0.03% more
instructions; limiting them leaves that loop's jumps as they were.
Measured against the parent commit, on x86-64: the instructions
of nofib's programs and of containers', vector's and megaparsec's
benchmarks move by 0.003% or less in geometric mean, and only intmap
fromSet past its bar, 1.0% fewer at -O1. In cycles nofib's programs fell
0.01% in geometric mean with the heads left out and rose 0.3%
with the levels limited, single programs moving by up to 12% either way
where unchanged code lands elsewhere: gcd's 4.7% rise comes
from its bignum code, unchanged but placed 80 bytes later,
and hartel/listcopy's 12% from code that a grown function moved.
The stage-1 compiler allocates 0.11% less compiling perf/compiler's T783
at -O and 0.061% less compiling T12707, its allocation compiling T3294
and T9961 moving by 0.0084% or less; at -O0 its allocation moves
by 0.0044% or less.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
ad900b35 by Mikolaj Konarski at 2026-11-20T00:13:11+01:00
NCG: invert floating-point conditional branches too
invertCondBranches turns a block's `jcc next; jmp other`
into `jncc other` only where the condition comes from an integer
comparison. maybeInvertCond complements the condition on the flags,
which nothing between the two jumps changes, so the swapped jumps take
the same path for every outcome of a floating-point comparison too,
an unordered one included, in each shape genCondBranch' emits for one.
Most such pairs nofib's objects keep at -O2 follow a ucomisd and go.
mandel2 runs 2.6% fewer instructions and smallpt 0.70% fewer at -O2;
no other program whose code changes moves by 0.1%.
Assisted-by: Claude Opus 5.5
- - - - -
90b9217f by Mikolaj Konarski at 2026-11-20T00:13:11+01:00
Drop the assignments that only a discarded assignment read
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant" and "Assign literals after computed values
at the end of a block".
Cmm sinking computes liveness once, before its walk, so where the walk
discards an assignment that nothing reads, such as a copy, it keeps
the assignments that only that one read (ISSUE 8327). Its liveness
is now faint: an assignment to a local register that is dead after
it uses nothing, so a register that only such assignments read is dead
as well. Master's annotate, which pairs each node with the registers
live after it, now leaves out every assignment to a local register dead
after it, so that sinking drops a chain of assignments that only one
another read in one pass, across blocks and loops; master's
shouldDiscard, the walk's test for such an assignment, is deleted,
the walk testing its other case, r = r, by noOpAssignment. Nothing
is folded or inlined again. Master's cmmLocalLivenessL is now
localLivenessBy given gen_killL, localLivenessBy taking the step
over a block's middle nodes, and sinking's liveness is localLivenessBy
given the faint step, so that sinking checks it as cmmLocalLivenessL
does, panicking where a local register is live on entry
to the procedure; by the faint liveness, a register that only
a discarded assignment reads no longer counts. At -O, hand-written Cmm
that reads a register before writing it on some path reaches sinking so:
stack layout checks only a procedure declared with a parameter list,
and only where it needs the liveness, as at a call, and CmmLint only
under -dcmm-lint. Without the check, on a procedure that returns
a register written on one branch only, the linear register allocator
panicked, and with -fregs-graph the compiler produced code that returns
a register nothing wrote.
A second sinking pass over every procedure, its liveness recomputed,
drops them as well, but in a trial it made the compiler allocate 60%
more compiling perf/compiler's T3294 at -O, and its constant folding,
which in that trial rewrote (a - b) + c to a + (c - b) whatever b and c
were, cost containers' elemAt benchmarks up to 2.4% more instructions.
Recomputing liveness until no assignment is dead drops them too,
but takes a pass for each link of a chain of assignments each read only
by the next: on a procedure with a chain of 400, the compiler allocated
9.2 times what master's does.
The test, T8327, is a Cmm loop that assigns a constant read only
by a copy that nothing reads; the constant must not appear in its Cmm.
With the parent commit's compiler it does.
Measured against the parent commit, on x86-64: vector's benchmarks
at -O1 run 2.1% fewer instructions (sum[base] 14.3%, map[base] 9.1%,
spectral 5.0%, generateIO 4.0%), none more by over 0.003%;
in sum[base]'s loop, the address of the SPEC token that vector's stream
fusion passes from one iteration to the next was loaded at each
iteration, read only by an assignment that sinking discarded. At -O2
none moves by more than 0.028%, and those that move most have the same
code. containers' benchmarks at -O2 run up to 9.5% fewer (nubOrd
noFusion_repeat 9.5%, issue1202_repeat 4.7%, set alterF:insert:present
2.9%, lookupge-map GE split 0.61%), none more; at -O1 only
Data.Sequence's code changes, and no benchmark moves beyond its noise.
megaparsec's benchmarks at -O2 run up to 1.0% fewer (skipManyTill 1.0%,
manyTill 0.66% to 0.71%), none more, and at -O1 none moves. Of nofib's
programs only rewrite's objects change, and no program moves by as much
as 0.2%; fannkuch-redux does not change. The stage-1 compiler allocates
0.095% and 0.092% less compiling perf/compiler's T3294 at -O and at -O2,
0.11% and 0.10% less compiling T12707, 0.052% to 0.056% less compiling
T783 and 0.13% less compiling MR 16269's CmmDiamondChain at -O1 and -O2;
at -O0, and compiling T9961, within 0.0038% of what it allocates
at the parent commit. Compiling nofib's puzzle at -O2, the stage-2
compiler allocates 0.12% less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
b1568b76 by Mikolaj Konarski at 2026-11-20T00:13:12+01:00
Keep Sp put across loops and tag tests in stack layout
To move into a merge request of its own, together with "Put a block's
reloads after its leading unwind in stack layout".
Stack layout gives a block the stack map of the first
of its predecessors it visits, and every later edge into the block gets
a fixup. It sets a diamond's frame (Note [diamond proc point]) up before
the tag test, trimmed to the variables live in the continuation,
and the continuation reloads them all, on the evaluated path too.
So in a loop whose body evaluates a variable, every iteration moves Sp
twice and stores the loop's invariants again, and where the variable
was evaluated already, it reloads registers that still hold their
values.
These changes to GHC.Cmm.LayoutStack keep Sp and the slots put:
* a loop head takes the stack map its back edges have in common,
by a second layout run where that pays, and the edge into the loop
pays the difference once (Note [Loop head stack maps]); a back edge
reached only through unlikely branches proposes nothing, and a head
every cycle through which makes a non-tail call to its own procedure
is left alone, its loop turning about once an entry (nofib's tak,
containers' foldrWithKey');
* a loop head that takes no such map, its back edges differing
in depth or needing no fixup, gets in the second run the depth
of the deepest continuation in its loop, with the loop's invariants
in the slots that continuation's frame gives them: a call returning
into the loop keeps that depth, where it moved Sp twice
an iteration, down at the call and up at the fixup on the edge where
its return path joins a path that made no call, and the edge
into the loop pays the Sp move and the invariants' stores once (Note
[Reserved frames in loops]), and where the second run seeds both
kinds of head and its seeds do not all hold, a third run seeds only
the heads that take a common stack map;
* the continuation becomes its reloads and a jump to its body, which
the evaluated path jumps to directly, where proc points
are not split and the reloads this adds at earlier proc points stay
at most two a diamond, or else for the diamonds whose tag test
follows no proc point whose reloads grow (Note [Tagged path skips
the reloads]); on a loop holding at most sixteen diamonds'
continuations the body takes every variable in its register but one
live across an inner loop that does not read it, and elsewhere only
those stored on the call's edge, reloading the rest itself where
they are used;
* the return address is stored on the call's edge only, where the call
is the only block returning to the continuation;
* a variable that at most one later call needs in a slot is stored
on the call's edge only too, that later call storing it on its own
path (Note [Tagged path skips the stores]);
* a diamond's frame keeps the stack's depth, its dead slots left
as holes (Note [Diamond frames keep their depth]);
* the frame a call into a diamond's continuation pushes is trimmed
to its live variables after layout, by a pass of its own, where,
among other conditions, proc points are not split and either
the procedure is called by a thunk of its Cmm group, as a lazy
list's producer is by the thunk of the list's tail, or trimming
takes at least half as many words as the frame keeps beside
its return address, the holes older than its youngest variable among
them, and the procedure is a thunk or the continuation is
on no loop: the call can evaluate a thunk that leads back to such
a frame, and each level of the recursion would hold the holes
(nofib's primes and multiplier); each call returning there moves Sp
up to the trimmed frame, the continuation moves it back down,
and the tagged path moves it nowhere (the same Note).
This fixes ISSUE 27991 for its example, whose loop stores nothing
on the stack at its iterations, and ISSUE 8905 in part: where a loop's
body evaluates a variable, the call's frame is set up on the call's path
only in the cases above, the others keeping the stores and reloads
it describes.
The reservation leaves these cases out, each having paid more
than it saved:
* a continuation reached only through unlikely branches, which
reserves nothing: a heap check's GC call returns into many a loop
that makes no other call, whose every entry and exit would pay
for a frame only that rare path uses (megaparsec's word32be,
containers' lookupGE). A block is reached so where every edge
into it is the unlikely side of a branch, the side a branch
on a literal never takes, or leaves another such block, in the least
set so closed, which leaves out a loop that only such blocks enter,
and this commit marks MAYBE_GC's test unlikely in rts/include/Cmm.h,
so that the primops whose `again: MAYBE_GC(again)` retries through
the GC call, newArray# and newAlignedPinnedByteArray# among them,
set up no frame on their fast path;
* a loop that only permutes the variables live at its head,
as integerAdd's swap of its arguments, which turns a few times
an entry;
* a loop making a non-tail call to its own procedure, each level
of the recursion then holding the reserved frame, a stack
the garbage collector scans (containers' foldl' over a line-shaped
tree);
* a loop holding a head seeded from its back edges, whose seed expects
its variables in other slots than the reserved frame gives them
(nofib's puzzle, six register swaps at a join).
A variable that the continuation's code saves at the first call
it reaches without a conditional branch, within eight blocks,
not redefining it on the way, is still stored before the test, whether
or not that code reads it: the tagged path would store it there anyway,
and the call's path would reload it at the continuation to store
it again (nofib's fasta, and A2T's zipWith5A and broadcast over small
arrays). In a procedure that makes a non-tail call of itself, and
for a diamond on a cycle of blocks, cold ones left out, that makes
no non-tail call into the procedure's recursion (its strongly connected
component in its Cmm group's call graph, computed once a group
in GHC.Cmm.Pipeline), those stores all stay only where the call's frame,
set up there, is no deeper with them all, and otherwise each only where
that frame has its variable in the slot the diamond's frame gives it,
in the call's own slot order or, where the frame is then no deeper
and its youngest slot of a variable that one or more later non-tail
calls of the procedure itself need, and of one that two or more need,
lies no younger than in that order, in the plain one: otherwise the slot
would deepen every level of the recursion (containers' PostOrder folds),
or a loop's seeded frame would be set up and dropped every iteration
(containers' intset insert and sequence update.10). Where tagSkip
refuses a diamond whose call's edge holds stores, those stores are made
before the test, at the end of the test's block after its Sp adjustment,
and not on both paths. A diamond laid out after its continuation stores
nothing on the call's edge only, the continuation's blocks having taken
each variable of its frame to be in its slot. No input was found
that lays a diamond out so, and by reading none comes from code
generated from Haskell, so no test reaches the case; measured
at the series' end, the guard costs the compiler 0.0053% more
instructions compiling T3294 at -O0, nofib's assembly at -O1 and -O2
unchanged, and testing instead whether the continuation has a stack map,
laid out or not, changes two procedures of compress2's Encode at -O2.
A procedure is matched with the calls into it, for its recursion
and for the thunks of its group that call it, by its info table's label,
which a call targets only where tables are next to code: elsewhere,
unregisterised, wasm32 and powerpc64le among them, calls target entry
labels, and stack layout lays every procedure out as one neither
recursive nor called by a thunk, as the comment at cpsTop's self_lbl
says.
tagSkip, which splits the continuations, checks the limit of two reloads
a diamond first against a bound read off the graph, each diamond's
variables taken in registers times the proc points whose regions hold
its tag test, and runs its analyses only where the bound exceeds
the limit; there it takes each block's live-in from the liveness
analysis, computing it only at a proc point that is no split
continuation, its loop rule (across) is one set a continuation,
the variables live across an inner component that the component does
not read, and the continuations on one loop share each block's
successors in it. laterSearch, which counts the later calls that need
a variable in a slot, searches only as far as each query needs,
over Steps that link each block to its successors' so that a search
looks up only its first block; across numbers each loop's blocks,
and liftFrames and tagSkip no longer walk every frame. Layout's search
for back edges, and has_loop, look for a back edge before testing
the cold blocks, so that the cold blocks are computed only where one
is found; the strongly connected components, shared by loopHeadSeeds
and reservedSeeds, are computed only where a loop head passes
loopHeadSeeds' other tests or, for reservedSeeds, an edge enters a proc
point that is not cold; liftFrames tests a frame against its size rule
before its loop, and asserts that a diamond's continuation takes one
word of arguments, layout recording a diamond only at such
a continuation; and a block's middle nodes are copied by (++) only where
something is appended. In GHC.Cmm.Info.Build, cafAnal takes a jump
into a split body as a reference to its continuation's info label,
asserting that the continuation is in contLbls, as a call's
continuation, the only kind a body is split off, always is: otherwise
each block's set gathered every later continuation, at a cost growing
with the square of a procedure's chain of evaluations. cafAnal panics
where a body is reached and its continuation is not, whose info table,
and the SRT covering the body, would then be dropped: no input shows it,
stack layout splitting a body off only where a call it lays out returns
there and leaving that call reached, and cmmSink, the one pass between
layout and cafAnal, changing no block's successors. The test is made
only where a body was split: made for every procedure, measured
at the series' end, it cost 0.0066% more instructions compiling T9961
at -O0. laterSearch goes depth first for 32 blocks and then on breadth
first from the blocks still to enter, which gives the same answer,
the answer being reachability over the states (block, whether a call
is counted): depth first only, a search ran down a loop's exit through
every later loop before the calls in the loop, and the stage-1 compiler
ran 3.0% more instructions compiling the battery's scaling program
lists, 400 loops in sequence over one list, at -O1; breadth first only,
it ran up to 0.036% more compiling perf/compiler's T12707 at -O0, both
against a form that started the search again breadth first
from the first block, in a second loop sharing the first's guards.
That form makes the stage-1 compiler run 0.127% fewer instructions
and allocate 0.125% less compiling lists at -O1 than the one loop,
the gap growing linearly with the number of loops; the one loop is kept
as the simpler. None of this changes the generated code.
Layout joins the block on a call's edge to the call's block where
it ends, where the call has no other way in and the procedure has
a diamond, by master's splice, which GHC.Cmm.ContFlowOpt now exports,
beside master's callContinuation_maybe, and marks INLINE (exported
without the pragma, it made the compiler allocate 0.018% more compiling
ManyBasicBlocks.cmm at -O0): unjoined, each tag test adds a block
to the maps the later passes keep of blocks, and at -O0, where no later
pass joins blocks, a jump.
A heap or stack check's GC call returns to a continuation that reloads
the variables and jumps back to the check. Where a split body jumps
to that check too, holding the variables in other registers
than the reloads give them, the allocator would fix the check's
registers from the retry and permute them on the hot path at every pass;
so, where the block the check's passing branch leads to ends in a jump,
or the block after it does where the first only jumps on, holding
at most unwinding information, ticks and comments, as under -g,
the retry, the jump to the check of the continuation or of the block
it jumps to, split body or not, jumps to a copy of the check, whose
passing branch leads to a copy of that block, and the hot check keeps
one way in (Note [Retries copy their checks]; A2T's rotate.inner
over large dense Storable arrays, which permuted its registers
by a cycle of xchg at each allocating check).
A change to GHC.CmmToAsm.BlockLayout goes with these:
* with the latch's fixup gone, a loop's exit can have the latch's
conditional edge and another block's unconditional one as direct
predecessors of near equal weight; buildChains, dropping the latch's
edge back into the loop as closing a cycle, left the latch's other
edge at its weight, so the other block fell into the exit
and the latch paid a jump an iteration (ISSUE 27799's reproducer,
with or without -fobject-determinism); where buildChains drops
a conditional edge from a chain's end into that chain's start,
the branch's other edge, if lighter and its target, unplaced
or starting a chain, has no info table, now takes the dropped edge's
weight (Note [Latch edges after a cycle]). It looks that edge up
in the CFG it holds, weighed by relevantWeight as the edges
sequenceChain gives it are, and puts its raised copy first, leaving
the edge, which then joins two placed blocks, to be passed over;
preferBackEdges raises some of the edges given too, but only edges
out of a block with one successor, and the latch's source has two.
relevantWeight, master's local of sequenceChain's directEdges,
becomes top-level for this, taking the blocks with an info table
as an argument.
Three tests in codeGen/should_compile check x86-64 assembly.
StackLayoutTagLoop, a loop that evaluates a list and then its head, two
diamonds whose frames differ, expects three moves of %rbp, Sp's
register, one where the loop is entered and one at each of its two
exits: master's compiler makes five, as does this commit's without
the loop-head seeds, and without a diamond's kept depth it makes six.
StackLayoutCallLoop, a loop calling a function on one of its paths,
checks the assembly for a return address stored below Sp, which
the parent commit's code stores; it is skipped on Windows and where code
is position-independent by default (Darwin and OpenBSD), where a label
is no immediate operand and the pattern cannot match, as master's
compiler passes it under -fPIC on x86_64-linux. Nothing was run
on those systems. The third, T27991, the example of ISSUE 27991,
searches the assembly for any movq of a register to an address off %rbp:
with the parent commit's compiler its loop stores two at every
iteration.
A loop head's seed in the second run keeps, of the slots its back edges
share, those within its depth: where the back edges arrive
from the deeper frames of continuations only unlikely branches reach,
a shared slot would lie below the seed's Sp, and the next call's frame,
set up from the seed, would index allocateIn's map of the stack out
of range. The test cmm_reserved_seed in cmm/should_run is such a loop
in hand-written Cmm, with one call and two more behind unlikely branches
whose continuations hold more variables; master's compiler compiles
it with -dcmm-lint at -O0, -O1 and -O2, and it prints the same values
at each. Without the restriction the compiler dies compiling it,
with "Ix{Int}.index: Index (6) out of range ((1,5))", in the ways normal
and optasm. It is not restricted to 64-bit targets and was run on x86-64
only.
Taking the variables in registers at the join is a trade: containers'
set foldMap_traverseSum takes 3.3% more instructions at -O1, and at -O2
map's fromSetA inner rows 0.43% to 0.45% more and intmap's Strict
fromSetA inner row 0.32% more (0.14% at -O1), the split continuation's
body moving its variables between registers at the join where
the parent's code used a memory operand; and orthotope's A2T benchmark's
window.zero, summed over large arrays, takes 5.04% more with boxed
elements and 3.37% more with Storable and Unboxed ones, its sumView
loading five to eight frame slots into registers on the path every
iteration takes; where a loop's elements take the call path, the split
continuation reloads the variables its body takes in registers at every
continuation, where the parent reloaded each at its use, as in A2T's
zipWith5A and concatOuter.map over small arrays, window over large runs
of Unboxed elements and rotate.inner over large dense Storable arrays.
The trade's toggle is Note [Tagged path skips the reloads]: the body
reading the variables from their slots instead makes nofib's compress
take 6.8% more instructions and queens 6.1% more.
Taking them in registers only on loops holding at most sixteen
continuations is a trade too: nofib's para takes 0.27% more instructions
at -O1, by one loop holding more, where taking them in registers saves
reloads and register moves at -O1 and costs reloads at -O2, nearly every
diamond there taking its call path. Lifting the limit reverts it,
but makes para take 0.50% more at -O2 and puzzle 4.38% more at -O1
and 2.23% more at -O2.
Storing on the call's edge only a variable that one later call needs
is a trade: at -O0 nofib's tak, mandel2, life, rfib, fasta and others
take more instructions, at -O1 multiplier, and at -O2 atom, ansi
and life, the path through a diamond's call paying a jump to the split
body and a register move more; the diamonds that lose and
those that gain differ only in their callers' arguments, which lie
outside the procedure that stack layout processes. In containers' graph
benchmarks the first of dfs's two calls stores on its edge a variable
the second call does not need, and line inputs gain by the smaller first
frame, dfs.line,n=1000000 24% fewer bytes at -O2 and -O1. Storing every
variable before the test instead makes nofib's programs take 0.91%
and 0.98% more instructions and containers' benchmarks 2.3% and 2.7%
more, at -O2 and -O1, and megaparsec's 3.4% more at -O2.
Stored in the older of two fresh slots, dfs's variable would leave
a hole in the second call's frame, a word a level of the recursion,
and make star inputs allocate a stack chunk more each time those words
add up to one. So for the frame of a non-tail call of the procedure
itself, in a procedure that loops, the variables later such calls need
take the older slots, where the frame would otherwise put one that none
of them needs in a slot older than one that one needs, and the next such
call's frame, once the others have died, trims from the young end.
This is a trade: against the commit without it, at -O2 and on graphs
of a million nodes, dfs.star allocates 10.2% fewer bytes and scc.star
and scc.line 5.4% fewer, and the depth-first searches over stars,
and scc and stronglyConnCompR over lines, take 0.5% to 1.65% fewer
instructions, while containers' other Data.Graph benchmarks take up
to 0.56% more, the most on graphs of a hundred nodes, the second
of dfs's calls moving Sp up to its trimmed frame where the hole kept
it put; and the compiler allocates 0.14% more compiling T9961 at -O0.
Ordering the slots of every frame instead costs an Sp move at each
trimmed call of other recursions, containers' foldMap_elem 1.2% more
instructions and nofib's binary-trees 0.76% more, and ordering every
frame of a procedure that calls itself and loops costs Sp moves at each
node of Data.Tree's folds over a node's children, Foldable1's foldMap1
over a line 6.8% more instructions. Whether the plain order puts
a variable that no later such call needs in an older slot than one
that one needs is asked in one pass over the frame's new variables,
which stops at the first such pair: comparing every pair, measured
at the series' end, the compiler ran 0.45%, 0.64% and 0.77% more
instructions compiling at -O1 a procedure that calls itself twice
and sums N words between the two calls and N after, the first call's
frame slotting N variables that no later call needs, with N at 200, 400
and 800.
Reserving a loop's frame is a trade: nofib's boyer2 takes 0.21% more
instructions, a loop's entry moving Sp and shuffling registers at each
iteration for a call path run less than half as often, and containers'
tree PostOrder.Foldable maximum 1.35% more at n=1000 and 0.39% more
at n=1000000; a further left-out case, for loops calling a procedure
private to the module, reverts them, but also gives back the gains
of nofib's sched (0.9%), transform (0.4%) and parstof (0.3%).
megaparsec's reachOffset-1000-1000 takes 1758 instructions
with or without that case, a few more than without the reservation:
the reservation's own trade. Giving a loop head the stack map its back
edges have in common is a trade too: a loop whose head is its exit test
and that runs no trip or one moves Sp down at its entry and up
at its exit, where the parent moved it at neither, so
that in orthotope's A2T benchmark Ranked's and Dynamic's scalar strided
cells over Storable and Unboxed elements take 2 and 3 instructions
a call more, the generate.scalar strided cells over Unboxed elements 2
to 6 more and Shaped's over Storable and boxed ones 1 more, and Shaped's
empty toVector and toUnorderedVectorT cells 3 to 4 more; leaving
the loop-head maps out reverts these with the gain on ISSUE 27991's
example. Copying such a head's exit test onto the edges into its loop,
where its map holds without the copy and the loop's exit reaches
no call, takes these back, but makes containers' intset fromAscList take
20% more instructions, in the garbage collector, and map
fromDescListWithKey 3.4% more at -O1.
Taking a block as cold where every edge into it is cold, rather than one
that an unlikely branch alone enters, is a trade: containers'
graphFromEdges takes up to 0.54% more instructions and nofib's awards
0.55% more at -O2 and -O1, where the wider rule changes the code
of GHC.Internal.Data.OldList and of awards' QSort, and containers' set
foldMap_traverseSum 0.77% fewer at -O2; the narrower rule leaves a frame
on the primops that retry through MAYBE_GC.
Code grows: nofib's objects take 1.3% more bytes at -O2 and 1.2% at -O1
(0.13% at -O0), as the split continuations' bodies move their variables
into registers at the joins and reload them at the continuations,
and each trimmed frame's call moves Sp up and its continuation moves
it back down. Not trimming takes back about a quarter of that and costs
primes' and multiplier's stack; the trade's toggle, the bodies reading
their variables from their slots, takes back the moves and reloads only
by storing on both paths, which makes code larger still.
The compile cost is that of these analyses and of the larger code:
against the parent commit the stage-1 compiler allocates 1.3% more
compiling perf/compiler's T12707 at -O0 (0.95% and 0.86% at -O and -O2),
0.87% more compiling T9961 and 0.56% more compiling T783 at -O0,
and 1.9% less compiling T3294 at -O0; over nofib's compilations
the stage-2 compiler allocates 1.7%, 1.6% and 0.79% more in geometric
mean at -O2, -O1 and -O0. Compiling MR 16269's CmmDiamondChain,
the stage-1 compiler allocates up to 0.059% less and runs 0.85% to 0.88%
fewer instructions. T12707's is a trade: of the 0.84% more instructions
the stage-1 compiler runs compiling it at -O0, turning tagSkip
and liftFrames off takes back about 0.6 points and gives up what they
gain, and the rest is layout's work a diamond and that of the passes
after it on the code layout changes; nofib's compile cost, at -O2
and puzzle's the most (the stage-2 compiler allocating 8.8% more
compiling puzzle at -O2), goes with the size trade, the passes after
layout working on the larger code.
Stack layout's local liveness is an LRegSet, as in master's
cmmLocalLivenessL, and the Data.Set form goes: GHC.Cmm.Liveness's
cmmLocalLiveness, noLiveOnEntry and the SPECIALIZE pragmas
of liveLattice and xferLive are deleted, those two now typed
at GlobalRegUse, their one remaining use, CmmLocalLive becomes LRegSet,
and liveLatticeL tests a change by isSubsetOfUniqueSet rather
than by the joined set's size; GHC.Cmm.Lint calls cmmLocalLivenessL;
insertReloadsAsNeeded runs over LRegSet; and setupStackFrame takes
the liveness map, as master's does, with a table, by unique,
of the defined variables live at any proc point, in which allocateIn
looks a variable up only where it stores it, testing membership
in the LRegSet. This is a trade, measured on an earlier form
of this change, which built from the table a Data.Set of the variables
live at each proc point: against the same tree with the Data.Set form,
the compiler runs 0.138% more instructions and allocates 0.017% more
compiling T783 at -O0, and 0.025% and 0.037% more compiling puzzle
at -O0 (T783's in Word64Set's operations on its small sets
and the table's walk; puzzle's instructions in the table, its walk
over every node's definitions and the Data.Sets built from it, the set
operations themselves running fewer, and puzzle's allocation
in Word64Set's insertions and deletions), and less in every other
compilation measured: T3294 at -O0 2.31% fewer instructions and 1.79%
less allocation, CmmDiamondChain at -O0 1.17% and 0.51%, puzzle at -O2
0.18% fewer instructions. Keeping the Data.Set form reverts both.
setupStackFrame, aheadSaves and cmmLayoutStack, for the variables live
at its proc points, look up the variables live on entry to a block
by a new liveOnEntry, which panics for a block without a liveness fact,
where master's setupStackFrame took the empty set: the analysis gives
a fact to every block the entry reaches, and every block they look up
is so reached.
Where the second run's seeds do not all hold, or the third's where
that runs, the heads whose seeds held run again with theirs alone (Note
[Loop head stack maps]). This is a trade: the run costs the compiler
0.016% more instructions and 0.020% more allocation compiling puzzle
at -O2, and nothing in the other compilations measured, and makes
nofib's gen_regexps take 9.05% fewer instructions at -O2 and -O1, two Sp
moves fewer a character of its inner walk over each string and one more
a string, cacheprof 0.38% fewer, containers' transposeG 2.9% to 3.4%
fewer and megaparsec's scientific 2.5% to 3.9% fewer at -O2. Keeping
the first run at once reverts both.
In GHC.StgToCmm.Utils, emitMultiAssign, master's code, no longer assigns
a variable to itself, as a self-recursive tail call or a jump
to a let-no-escape binding passing an argument unchanged did: layout
takes an assignment to a variable as leaving the variable's slot stale,
so that the next call stored it again. This is a trade: the compiler
runs 0.151% and 0.156% fewer instructions compiling T783 at -O and -O2,
and 0.022% and 0.023% more compiling T12707 at -O and -O2, where
it allocates 0.026% and 0.027% more, in maps and sets keyed by uniques,
which shift once those assignments are gone; the generated code differs
only in its labels. Emitting the assignments again, with layout
exempting them, reverts both.
Measured against the parent commit, on x86-64, in instructions: nofib's
programs take 3.8% fewer at -O2, 4.5% at -O1 and 0.73% at -O0
in geometric mean (gen_regexps 34%, queens 24% and bspt 20% at -O2,
k-nucleotide 40% at -O1), and some take more: at -O0 tak 1.45%, life
1.31%, mandel2 1.31%, rfib 1.02%, nucleic2 0.75%, parstof 0.68%, kahan
0.61%, digits-of-e1 0.58%, fasta 0.48%, fulsom 0.42%, atom 0.26%
and solid 0.23%, at -O1 life 1.32%, ansi 0.36%, multiplier 0.32%
and atom 0.31%, and at -O2 life 1.32%, ansi 0.33% and atom 0.32%.
containers' benchmarks take 6.2% fewer at -O2 and 6.7% at -O1 (graph
dfs.maxDAG,n=15 36%), and more in intmap's cps folds, 0.94% to 1.01%
at -O2 and -O1, set foldMap_traverseSum and the fromSetA rows above,
and sequence fromFunction.ix10000/5000, 0.82% at -O1. megaparsec's take
6.7% fewer at -O2 and 4.8% at -O1 (reachOffsetNoLine 23% at -O2, string'
13% at -O1), and vector's 4.3% fewer at -O2 and 10.6% at -O1 (minimumOn
31%), none of either more. Of the cells of A2T's sample that move
by 0.2% or more, all take fewer (toList and toVector over small dense
boxed arrays 28%) but the scalar and generate.scalar strided cells
above. No nofib program's allocation moves; containers' set
alterF:insert:absent allocates 3.11% more at -O2 and -O1, a stack chunk,
and intmap difference-common_nn_swap a stack chunk more at -O2, where
difference-common_sn_swap allocates one fewer. Compiled by the boot
compiler, GHC 9.12.4, GHC.Cmm.LayoutStack allocates 4.2 times as much
(7.87 against 1.89 GB) and GHC.Cmm.Pipeline 52% more (0.757 against
0.498 GB). Compiling the battery's scaling programs calls, lists
and allocs at -O1, from N = 100 to N = 400, the stage-1 compiler
allocates 1.4% to 1.9%, 9.6% to 9.2% and 1.2% to 1.7% more
than the parent commit's; the ratio no longer rises with N for lists
and rises by up to 0.5 points for calls and allocs.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
cc9b448d by Mikolaj Konarski at 2026-11-20T00:13:12+01:00
Load a field again after a call from its saved constructor
To move into a merge request of its own, on top of that of "Keep Sp put
across loops and tag tests in stack layout".
This commit's code lies outside GHC.CmmToAsm, which it changes only
in a comment and in its README: it changes stack layout,
GHC.Cmm.LayoutStack, sinking, GHC.Cmm.Sink, StgToCmm, which records
for it the registers a case alternative loads its constructor's fields
into, and the driver, which turns it on only for the Cmm that StgToCmm
generates.
A case alternative loads the fields of its constructor where it starts,
so a field used only after a call is loaded before the call and saved
across it (ISSUE 20334). Saving the constructor in place of its fields
could keep dead fields alive (ISSUE 20333), but where the constructor's
variable is saved across the call anyway, its slot keeps them alive
already. There stack layout now saves the field nowhere and loads
it from the constructor after the call, where the variable is reloaded,
or, in a body split off a tag test's continuation, after the test,
on the paths that use it.
This runs only under -fcmm-sink, without which the load before the call
would stay, and only over Cmm generated from STG: hand-written Cmm keeps
none of the convention it rests on, a local of a GC pointer's type there
able to hold any address, of memory the procedure or a call writes.
Master's CmmConfig gains cmmOptRefetchFields, which refetchPass tests,
which master's initCmmConfig sets False, and which master's doCodeGen
(GHC.Driver.Main.Compile), the one caller of cmmPipeline over the Cmm
that StgToCmm generates, sets from -fcmm-sink; so a Cmm file, and Cmm
that a client of the GHC API parses and runs cmmPipeline over,
as the testsuite's regalloc_unit_tests does, loads no field again.
StgToCmm records the registers of each case alternative that loads every
field of its constructor, two or more (a CgConFields statement
in the code, which emitProc collects into CmmStackInfo's con_fields
while flattening the code), and two rules decide the proc points where
a field is live. Where its constructor's variable c is live, a field
is left out at every such point or at none: at each where the field
is wanted after the call (used before the next proc point, saved at one,
or the region larger than the sixteen blocks walked), c must be used
there too. Where c is dead, the decision is made per call: c is saved
in place of the fields where every register of their alternative
is live, two or more of them are saved across no call where only some
of them are live, nor across a diamond's call whose body uses some
of them, one of them is live at some proc point that is neither
the procedure's entry nor reached only through unlikely branches,
as a continuation only calls to the collector return to is, and no proc
point where c is dead and all of them are live is on a cycle of blocks,
none of them cold, that assigns none of them and uses one of them,
and nowhere else, so that it keeps no dead field alive, its store
replaces two or more, a diamond's tagged path keeps the fields
in registers, and no loop reloads c on every trip.
Wherever a field is live, c must hold the constructor the field
was loaded from, so a field is saved where it is live at the start
of a block assigning c, or loaded in a block that assigns c after
the load (the walk assigns, in fieldRefetches): for x = W_[c + 7]; c =
W_[c + 15]; call f(x), with x and c live after the call, in one block
as written or once cmmCfgOpts has merged two, x would otherwise
be loaded from the new c. Code generated from Haskell is taken
not to have that second shape, a field's load being its register's only
assignment and preceding its uses, and the register of a binder in scope
being assigned again only by a self-recursive tail call or a jump
to a recursive join point, after which the field is dead: an argument
from StgToCmm's conventions, not a proof. Measured at the series' end,
nofib's assembly at -O1 and -O2 is the same with and without that rule,
and with hand-written Cmm left out no test reaches it.
A function closure loads its free variables where its code starts,
and their registers are listed as an alternative's too, so
that the closure is saved in their place across a call after which they
are live and it is dead (ISSUE 20333), and across a diamond's call.
Against its parent, nofib's puzzle runs 5.7% and mate 2.4% fewer
instructions at -O1, and no program runs 0.2% more at -O1 or -O2;
containers' IntMap symmetricDifference benchmarks run up to 9.0% fewer
at -O1 and the map and set cpsOneShotSum folds 2.6% to 4.0% fewer at -O2
and -O1; T20333's code at -O has half as many stores of a double
to the stack; and the stage-2 compiler takes 1.3% fewer instructions
and 0.48% less allocation compiling puzzle at -O1, and 0.23% fewer
instructions and 0.060% more allocation at -O2, its code changed
at both. Past their bars upward: containers' intmap union-disj_nn
and union-disj_nn_swap at -O1, 111% and 104% more instructions,
allocating 33496 bytes against 728, a stack chunk more (on an earlier
form of the series the benchmark's warm-up call stayed within
the initial stack and the measured call overflowed it, and with a larger
initial stack they ran fewer instructions and allocated the same),
and the rows allocating one stack chunk more, intmap
difference-common_nn_swap at -O1 and symmetricDifference-mix_ns
and mix_sn_swap and sequence splitAt/append.100 at -O2; intmap
restrictKeys:random, 0.46% more instructions at -O2, and the intmap
symmetricDifference-disj_nn_swap row, two instructions more at -O2;
megaparsec's scientific benchmarks, 0.17% to 0.24% more at -O2 and 0.56%
to 0.85% more at -O1, and reachOffsetNoLine 0.49% more at -O1;
and the reshape cells of orthotope's A2T sample, four instructions
a call more (0.31% to 0.61%), and its Storable and Unboxed stretchOuter
cells one more (0.25%).
Stack layout follows the alternatives in one walk over the proc points,
leaving one once fewer than two of its registers remain to be saved
in place of its constructor's variable: over every alternative at every
proc point the compiler allocated 0.49% more compiling Data.Colour.Names
at -O2, whose one function closure's free variables are each live up
to one call of a chain, and it now allocates within 0.03% of what
the series' end allocates without this commit.
Saving the closure holds it from its assignment to the call beside
the free variables used on the way, so where the blocks reached
from its assignment without passing a proc point hold a loop, on the way
to the call or not, it is saved in their place only where one of them
is used in none of those blocks that assign the closure or start
with it dead: in spectral-norm's timesAtAv, whose loops use two
of its closure's four free variables and a call after them the other
two, the closure otherwise held one register more in the loops and ran
5.9% more instructions. Without a loop the register held more costs one
spill and reload at most, and saving the closure in place of k free
variables saves k - 1 stores for one load more. A constructor's
alternative keeps the rule above: declining where a loop before the call
used three of four fields cost two instructions a call, and in loop-free
code declining moved nofib's fish by +0.28%, its gains in multiplier
and boyer being those of the rule for heap checks below. The test costs
instructions compiling puzzle at -O2, in stack layout's own walks.
At a diamond, saving the closure in place of k free variables saves
the tagged path k loads and k stores for a move of the closure out of R1
and its store, and costs its reload and the k loads from it, which fold
into their uses as reloads from the stack do: 2k - 3 instructions fewer,
less one for each used after a store to the heap, which its load does
not pass.
Where none of an alternative's registers is live at a proc point
that is neither the procedure's entry nor reached only through unlikely
branches, as a continuation only calls to the collector return to is,
they are saved across those calls and its constructor's variable is not:
holding the variable to the check costs the path passing it a register,
nofib's boyer copying it to another one, and saving it in their place
saves stores only on the path to the collector. Against this commit
without the rule, nofib's multiplier runs 0.26% and boyer 0.21% fewer
instructions at -O2, 0.22% and 0.21% at -O1, and no program runs 0.2%
more at -O2, -O1 or -O0, where no object changes; megaparsec's
benchmarks run 0.30% fewer at -O2 and 0.53% at -O1 by their geometric
mean, up to 3.0% fewer, and none more; no containers benchmark runs 0.1%
more and no vector benchmark moves by 0.05%; and the compiler's
allocation moves by under 0.01% compiling T3294, T12707, T783, T9961
and CmmDiamondChain, and rises by 0.1% on no module of containers,
vector or megaparsec.
Sinking, GHC.Cmm.Sink, now carries a load that may read the heap past
an assignment to Hp: master's conflicts held every such load above any
assignment to Hp, and so above a heap check, also where only the path
passing the check uses it, so that the fields loaded again at a proc
point, or in a body split off one, that ends in a heap check would
not fold into their uses. An assignment to Hp writes no memory,
and a load whose address uses Hp stays above it, the assignment writing
a register the load reads; below it, the stores into the new object
conflict with every load that may read the heap, and the collector runs
only in the check's call, which no load from memory crosses. So a load
moved below the check reads on the passing path the word it read above
it, and after a collection the code runs again from the call's
continuation through what the frame saved, which stack layout fixed
before sinking runs; the rule that an assignment to Sp conflicts
with a read of the stack stays.
That is a trade, measured on a form of the series' end without master's
rule against an earlier form with it, where stack layout loaded below
such a check the fields passing through it. It costs containers' intmap
fromList and fromListWith benchmarks over random duplicate keys 0.17%
to 0.22% more instructions at -O2 and 0.18% to 0.24% more at -O1, one
register move in one block, where a field's load passes the assignment
of the register holding its address, and nofib's maillist 0.03% more
at every level, in ghc-internal's hClose_help. Against that, nofib's
programs run 0.007% fewer instructions at -O2 and -O1 by the geometric
mean and fannkuch-redux 0.24% and 0.22% fewer, containers' IntSet
symmetricDifference benchmarks run 0.11% to 0.74% fewer at -O2 and 0.23%
to 0.65% fewer at -O1, and megaparsec's scientific benchmarks as many
but at the largest size, 0.16% and 0.17% more, inside the spread
of the runs with the rule.
Where all of an alternative's registers are live and its constructor's
variable is dead at a proc point on a cycle of blocks, none of them
cold, that assigns none of them and uses one of them, the fields
are saved, their stores running once before the cycle, where
the variable would be reloaded on every trip: orthotope's
genericFoldlStored, folding a boxed vector by a call at each element,
ran one instruction more an element with the vector saved in place
of its three fields. And a loop head's seed (Note [Loop head stack
maps]) can move an inner loop's head off the depth at which its back
edges arrive, which then move Sp twice a turn of the inner loop,
as in orthotope's sumA over a strided view; such a head, its back edges
at one depth needing no fixup in stack layout's first run, is now seeded
with their first-run map in one run more, kept if all its seeds hold,
at the cost of one instruction an entry of an inner loop that does
not turn. Against this commit without both, in orthotope's A2T benchmark
the large boxed Dynamic sumA, rerank and rerank.one cells run 0.50%
to 4.2% fewer instructions and anyA's large runs and window cells
of Storable and Unboxed arrays 11% to 14% fewer, all of them,
in the forced mode, back to the parent commit's counts, and the small
ones 1.1% to 1.6% fewer; vector's map[lens] runs 1.1% fewer at -O2
and -O1, back to the parent's count; no nofib program moves by 0.2%
at -O2 or -O1, nor any containers or megaparsec benchmark at either,
nor any other vector benchmark by 0.05%; and the compiler's instructions
and allocation move by 0.011% or less compiling T3294, T12707, T783,
T9961 and CmmDiamondChain.
Measured on an earlier form of the series, against that form's tip,
with an earlier form of this change: containers' benchmarks ran 0.58%
fewer instructions at -O2 and 0.77% fewer at -O1, the rows that rose,
in instructions or by one stack chunk's allocation, rising no more
under a larger initial stack; and in orthotope's A2T benchmark every
rotate cell allocated the same and none ran more than 0.1 instructions
a call more, rotating an empty dense Storable array taking 620.78
instead of 626.76.
The test T20334 greps the assembly of three functions for Doubles stored
on the stack: the reproducer posted on ISSUE 20334, a variant whose call
is to length, and one whose constructor is dead across the calls, saved
in place of its fields. Of the 11 the parent commit stores, only
the three of V's constructor function's entry to the GC remain. T20333
greps the same in ISSUE 20333's example, in Double#s, and in a variant
whose closure's free variables are used after a call: of the 16
the parent commit stores, only the 8 of foo's and bar's entry to the GC
remain. T20333b and T20333c grep the offsets of the stores below Sp:
where a function closure's four free variables are used in both arms
of a branch before a call and after it, the closure's entry stores one
value on each path where the parent commit's code stores four; and where
a case alternative uses its constructor's four fields across a loop
and a call, the parent commit's two stores below Sp in its function go.
Two tests in cmm/should_run are hand-written Cmm, skipped on 32-bit
targets. cmm_refetch_store loads a word through a local of a GC
pointer's type at an offset that is no multiple of the word size, has
a call, or the procedure itself between two calls, store to that word,
and returns the word loaded: with fields loaded again in Cmm files,
its procedures returned 353123 and 101016162 in place of 353025
and 101016065. cmm_refetch_reassign loads a field from c
and then assigns c in the same block, in one block as written and in two
that cmmCfgOpts merges, and prints 66049 for each, where the field
loaded again from the new c printed 66050; with no field loaded again
in Cmm files it no longer reaches the walk that saves such a field.
Measured at the series' end, leaving the reload off for Cmm files keeps
the same assembly for every .cmm file of rts and libraries that compiles
alone at -O2, plain and with -DTHREADED_RTS, the vector variants
of Jumps and AutoApply not compiled.
Master's cmmLayoutStack now maps the lowering of safe foreign calls
over the blocks only in a procedure where a block ends in one,
and rebuilds the graph from a list of blocks only where it lowered
a call or joined an edge block; elsewhere it returns the graph
that insertReloadsAsNeeded, master's too, now returns in place
of its list of blocks.
Measured with stage-1 compilers against the parent commit, the compiler
runs 0.075% more instructions and allocates 0.023% less compiling
perf/compiler's T12707 at -O, whose assembly changes, and 0.065% more
and 0.024% less at -O2; it runs 0.0028% and 0.0050% fewer instructions
and allocates 0.025% less compiling T3294 at -O and -O2, and runs 0.14%
and 0.15% fewer instructions compiling MR 16269's CmmDiamondChain at -O1
and -O2, their assembly unchanged; and for T9961 at -O and -O2
it changes by 0.014% or less, while it runs 0.085% fewer instructions
and allocates 0.14% less compiling T783 there and allocates 0.29% less
compiling CmmDiamondChain. Compiled by the boot compiler, GHC 9.12.4,
GHC.Cmm.LayoutStack allocates 31% more (10.30 against 7.87 GB),
the simplifier allocating 35% more and the code generator 28% more,
as the module holds 31% more lines of code. Collecting the alternatives'
registers while flattening the code and deciding once a procedure
whether any field is loaded again took 0.065 points off T12707's
instructions at -O. What remains, in a procedure with a proc point other
than its entry, is the walk over every middle node that finds the field
loads: with the analysis after it skipped, the compiler runs within
0.003 points of these figures compiling T3294 and T12707 at -O
and CmmDiamondChain at -O1, and with the pass that loads them again off,
no more than the parent commit's; only the code generator listing
the loads as it emits them could spare the walk, which was not tried.
At -O0, where the analysis is off and the assembly the same,
the compiler runs 0.27% fewer instructions compiling T9961, 0.14% fewer
for T12707, 0.28% fewer for T783, 0.17% fewer for CmmDiamondChain
and 0.030% fewer for T3294, and allocates 0.086% to 0.56% less:
cmmLayoutStack no longer rebuilding its graph in every procedure, at any
level or in Cmm files, ofBlockList inserts a quarter fewer blocks
compiling T9961 at -O0, and CmmDiamondChain, a Cmm file, falls alike
at -O0, -O1 and -O2. Compiling nofib's programs, the stage-1 compiler
allocates 0.064% more for simple at -O1 and 0.053% more at -O2, 0.059%
and 0.080% more for bspt, 0.054% and 0.20% for sorting, 0.069%
and 0.054% for sphere, 0.044% and 0.054% for anna, 0.019% and 0.041%
for transform, and 0.001% and 0.003% for clausify. The cycles of blocks,
none of them cold, on which an alternative's registers are all live
and none assigned are found once for all of its proc points; with them
found by a walk from each proc point, the compiler allocated 0.45%
and 0.27% more compiling simple and bspt at -O1.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
26433c22 by Mikolaj Konarski at 2026-11-20T00:13:13+01:00
Jump conditionally to a likely false comparison's false target
genCondBranch jumps to the true target conditionally and to the false
one after, and ignores cml_likely. Where the layout makes either target
a fall-through, invertCondBranches and dropJumps leave one conditional
jump whichever order it emits; where neither jump falls through,
the conditional jump is the shorter way to its target,
so invertCondBranches now swaps the two jumps of an integer comparison
likely false whose true target does not come next. After layout rather
than before genCondBranch: swapped there, every heap and stack check's
jumps were swapped and swapped back by invertCondBranches, costing up
to 0.29% more instructions compiling at -O0. invert examines a block's
last two instructions once and chooses between the old rule and the new
one. Master's test that the conditional jump's target is the next block
becomes a call of GHC.CmmToAsm.BlockLayout's fallsTo with the target's
label, which looks past the blocks between that hold only meta
instructions and have no info table, as a block whose jump the layout
dropped holds its unwinding information under -g, so that such
information changes no inversion.
Measured on x86-64 against its parent, in instructions: containers'
IntMap fromSet and fromSetA rows take 0.32% to 0.46% fewer at -O2
and fromSet 0.36% fewer at -O1, beyond the leftover jump "Drop jumps
over blocks dropJumps empties" removes there; no benchmark rises beyond
its noise, and the stage-1 compiler's allocation moves by 0.052% or less
compiling each of perf/compiler's T3294, T12707, T783 and T9961 and MR
16269's CmmDiamondChain, at every level measured.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
28ab5db0 by Mikolaj Konarski at 2026-11-20T00:13:13+01:00
Add an estimate of block frequencies for the linear allocator
blockFrequencies in GHC.CmmToAsm.CFG makes mkGlobalWeights' estimate
of how often each block runs, for the linear allocator, from the native
CFG before allocation: static prediction's edge probabilities
(the two-way rule factored out of staticBranchPrediction
as predictBranch, shared, given the procedure's tagRegisters
as the layout's estimate is) and calcFreqs' fixpoint, with loops found
by one depth-first search and the whole computation in two arrays.
The arrays take every edge's target for a node of the CFG, which a debug
compiler asserts: getCfg makes a node of every block it reaches,
and a later writer adds an edge by addEdge, which makes its target one.
A later commit passes it to the linear allocator. Compiled by the boot
compiler, GHC 9.12.4, GHC.CmmToAsm.CFG allocates 20% more (3.88 against
3.24 GB).
Assisted-by: Claude Opus 5.5
- - - - -
419155c1 by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Use block frequencies to order the linear allocator's SCCs
Where block frequencies are estimated, linearRA_SCCs allocates the SCCs
in an order computed before allocation from the estimate and the jumps
(hotFirst): the procedure's first block first where no loop holds it,
then the earliest in dependency order among those it can allocate,
and it sets aside an entry other than the first block while a block
it jumps to, not yet reached, runs more than 1.2 times as often
as the entry; where nothing can be allocated, the entry set aside
that the estimate calls hottest goes next, the entries set aside kept
in a set by estimate, hottest first and ties to the earlier, from which
each such fallback takes the first still set aside. This replaces
the deferral of the blocks the garbage collector returns to and
of a continuation entering a call-free loop, which stay where there
is no estimate: on x86-64 without -fcmm-static-pred, as at -O0,
and on other targets, where allocCold is empty and only
the continuation's deferral stays. They stay too where the estimate
lacks one of the procedure's blocks: under -finfo-table-map, where
the native code generator drops no dead code, liveness keeps
the continuation of a call that cmmToCmm made unreachable, while
the CFG, and so the estimate, holds only the blocks the entry reaches
(ISSUE 28088); hotFirst returns Nothing there, and linearRA_SCCs takes
its branch without an estimate. The first block first keeps a loop
calling itself on the argument registers (Data.Tree's and Data.Map's
folds); the hottest entry set aside first gives a join of two
continuations, both waiting, the hotter's registers (Data.IntMap's
mapKeysMonotonic at -O1). hotFirst is NOINLINE, so that its local thunks
are not allocated for every procedure at -O0, where it is not called.
CmmToAsm passes Linear.regAlloc the estimate of block frequencies
from a given entry where static prediction is on (-fcmm-static-pred),
as for the layout's estimate, and regAlloc computes it
from the procedure's first block.
The test T27800_itm in regalloc, the loop of cmm/should_compile/T27800
and a call behind a branch on a constant, compiled with -finfo-table-map
on x86-64, checks by -ddump-asm-stats that only the continuation's jump
into the loop pays a fixup move: allocated in the given order, each
of the loop's two jumps went through a block moving a register. Measured
at the series' end, a compiler tracing hotFirst's branch for a missing
block took it for the test's procedure and never while compiling nofib
at -O1 under -finfo-table-map. Keeping the entries set aside in a list,
filtered and folded over for the hottest at each fallback, the compiler
ran 0.51 and 15.0 thousand million instructions compiling at -O1
a procedure of 400 and 3200 two-way branches in sequence whose arms each
end in a call, where it runs 0.34 and 2.44, measured at the series' end.
The users' guide's entry of -fcmm-static-pred, master's, now says
that the prediction also orders the blocks the linear register allocator
allocates, master's sentence that the flag has no effect
under -finfo-table-map now limited to the layout, and that the flag has
no effect on other architectures than x86-64.
Within a cyclic SCC that holds a block whose first jump target in
it and another differ in estimate by a factor of 1.2, and
that is entered at some block, reached from outside it or an entry,
hotFirst gives the blocks hottest first (hotOrder), starting from every
such block, each block's jump targets in the SCC reached as it goes,
so that the hotter side of the branch fixes its join's registers
and the colder side pays the moves. Entered at more blocks, its joins
also meet registers fixed apart from the order, an outside predecessor's
at a block reached from outside and none at an entry, and the order
ranks such blocks by an entry's heat, the estimate's guess for the call
or evaluation returning to it. Ordering such an SCC too is a trade:
measured at the end of the series against that end with only the SCCs
entered at one block ordered, orthotope's A2T runs 0.52% to 0.54% fewer
instructions in its eight indexIndex cells over small arrays (Dynamic
and Ranked, Storable and Unboxed, dense and strided), and the compiler
runs 0.40% more instructions and allocates 0.15% more compiling nofib's
puzzle at -O2, whose loops are entered at many blocks, puzzle's run
unchanged. Measured with the order placed at the end of the series,
against that end, in instructions: megaparsec's skipManyTill, manyTill
and endBy take fewer at -O2, and nofib's wheel-sieve1 fewer at -O2
and -O1, wheel-sieve2 too, and k-nucleotide at -O2, and no benchmark
takes more beyond its noise; no compile-cost cell moves beyond
its noise.
Measured on x86-64 against its parent, with both stage-1 compilers
over the same libraries, in instructions by the geometric mean: at -O2
and -O1 nofib's programs take 0.177% and 0.156% fewer, containers'
benchmarks 0.439% and 0.481%, vector's 0.354% and 0.567%
and megaparsec's 0.403% and 0.190%, and orthotope's A2T benchmark takes
0.410% fewer. No program's allocation moves by 0.2%, and nofib's objects
take 0.349% and 0.358% fewer bytes at -O2 and -O1, puzzle's 0.55%
and pidigits' 0.30% more at -O2 and scc's 0.20% more at -O1.
The order is a trade, its toggle the order itself (hotFirst's guard
in linearRA_SCCs). Against its parent these rows rise past their bars.
In loops closed through a call, which the estimate rates at a trip
multiplier far below the run's, containers' map
fromList-distinctAsc:fusion takes 2.4% more and set
fromDistinctDescList:fusion 2.0% more at -O2. Where the block now
allocated first fixes a join's registers for the blocks after it,
megaparsec's count', some, skipSome and sepEndBy1 take more moves
an element, 0.26% to 0.88% more at -O1 and -O2, a continuation's reloads
landing in other registers, and containers' fromAscListWithKey
and fromDescListWithKey, 0.42% and 0.36% more at -O2, and map alterF's
lookup present, 0.79% and 0.39% more at -O2 and -O1, and lookup absent,
0.37% more at -O1, take a move or a shuffle more at a join. Containers'
map fromListWith-asc:fusion and fromListWithKey-asc:fusion take 0.97%
to 0.98% more at -O2 and map fromDistinctDescList:fusion 0.85% more
there, megaparsec's sepBy and sepBy1 0.35% to 0.37% more at -O1,
vector's next/prevPermutation baseline 0.10% more at -O2, nofib's fasta
2.7% more at -O2, puzzle 0.60% more at -O2 and cacheprof 0.23% more
at -O1, and 17 cells of orthotope's A2T benchmark more than 0.2%, up
to 0.69% (Dynamic's ==.units over small strided Unboxed arrays).
The other rises are a trade against allocating the SCCs hotter first
among those that can be allocated, as an earlier form of this commit
did: nofib's scs takes 1.8% more at -O2 and -O1, 1.3% with the SCCs
hotter first, fasta 1.5% more at -O1 and cacheprof 0.24% more at -O2,
neither rising with them, containers' intset fromList:asc:sparse:fusion
0.94% more at -O2, not moving with them, and megaparsec's scientific
1.26% to 1.41% more at -O1 and 1.09% to 1.57% at -O2, 0.10% to 0.43%
and 0.64% to 1.19% with them, and the compiler runs 0.28% more
instructions compiling nofib's kahan at -O1, 0.08% with them.
But the SCCs hotter first give up what this order gains over them,
orthotope's A2T taking 0.163% fewer instructions rather than 0.410%
and vector's benchmarks at -O2 0.070% fewer rather than 0.354%, and make
megaparsec's choice take 1.2% more at -O1.
Two other uses of the estimate, which the Note's bullets name,
were refuted. Taking at wideMoveDests the destination of the hottest
of the blocks that give a vreg one moved containers' benchmarks both
ways, 17 rising and 16 falling at -O1 and 49 and 71 at -O2
(intersection-mix 2.5% fewer instructions, symmetricDifference-common
1.35% more), 0.007% and 0.081% fewer in all. Counting a write
in regClobbers only where its block's estimate is at least half
that of the block allocating the vreg made containers' benchmarks take
0.108% more instructions at -O1 (85 rising, 59 falling) and 0.170% more
at -O2 (92 and 30), and the compiler allocate 14% to 17% more compiling
CmmDiamondChain.
The estimate and the order are the compile cost: the stage-1 compiler
allocates at most 0.042% more at -O0 (T9961) and 0.058% more at -O
and -O2 (T783 at -O) compiling perf/compiler's T3294, T12707, T783
and T9961, and runs up to 0.33% more instructions (T783 at -O);
compiling MR 16269's CmmDiamondChain at -O1 and -O2 it runs 0.57% more
instructions and allocates 0.063% more; compiling nofib's programs
at -O1 and -O2 it runs 0.155% and 0.169% more instructions
by the geometric mean, up to 0.83% more (puzzle at -O2), and allocates
0.050% and 0.058% more. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 17% more (10.78 against 9.23 GB).
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
ba6a6330 by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Propagate wide move destinations back, preferring the target's register
The last preference of "Prefer the register a later block moves a vreg
into where it dies", a vreg's wide destination, now reaches back along
moves: wideMoveDests also gives a vreg moved where it dies, in a warm
block, into a vreg that has a wide destination, that destination, up
to four moves back, and the walk of the blocks checks it as it checks
the others. A vreg given a destination so first takes the first-used
register of the vreg it is moved into, the claims test skipped,
as that vreg, dead, still claims its register: given the destination
itself, a closure moved into a join's vreg took the register that vreg
is moved into later, not the one it has at the join, and every path
into the join ended in a move (containers' map fromListWith-asc, 1.26%
more at -O1). Note [Register preferences in the linear allocator] says
that this preference, the fourth, is not counted where the fallback
leaves out, for a vreg with preferences, the free registers that one
of the assignments the block's jumps lead to, a recorded jump target's
or that of a block up to three jumps past a target not yet recorded,
gives any vreg: noPrefs does not count it. Where a procedure has
no candidate the propagation returns at once, and it shares its list
of moves with the walk. The commit also keeps wideMoveDests
from inlining until the last simplifier phase (NOINLINE [0]),
and linearRegAlloc' flattens a procedure's SCCs into one list, once,
for wideMoveDests and the three other walks over the blocks. Inlined,
wideMoveDests had its local bindings floated out as thunks built
for every procedure, so that the stage-2 compiler, built by the series'
stage-1 compiler, allocated 0.14% more than the parent's compiling
perf/compiler's T9961 at -O0. The pragma alone made the stage-1
compiler, built by GHC 9.12.4, allocate up to 0.107% more than without
it in ten of the fifteen compile cells below, as without it the CSE
of GHC 9.12.4 had shared one flattened list among the four walks, which
flattening once now does by design.
In containers' tree PostOrder foldl'_sum a loop's carry is now computed
in R2's %r14, where the recursive call takes it, rather than in another
register moved there and back. Measured on x86-64 against its parent,
in instructions: vector's maximumOn takes 15.4% fewer, containers' tree
PostOrder folds 0.77% to 4.4% fewer, nofib's k-nucleotide 0.60% fewer
at -O2 and 0.48% at -O1, and clausify and digits-of-e2 0.31% to 0.39%
fewer at both.
The propagation is a trade, its toggle propagating along no move, which
reverts every gain with the rises: against its parent, map
fromDescListWithKey takes 0.33% more at -O1, a move every fourth element
where the step entered after each descLinkTop or ascLinkTop swaps
the stack and its left subtree. Megaparsec's reachOffsetNoLine-0 rows,
which the toggle reverts too, take 0.65% more at -O1 against the parent.
A propagated destination yields to a vreg directly destined
for that register and born while the propagated one is live only where
the estimate of "Add an estimate of block frequencies for the linear
allocator" runs that vreg's own move into the register more often
than the move ending the propagated chain, the walk of the blocks
then also taking the blocks that write such a vreg: this takes back
the rows of map fromAscList and fromDescList at -O2, 0.36% of their
0.39% more, and keeps maximumOn's gain and the fused rows.
fromDescListWithKey's -O1 rise stays the trade, the estimate rating
its loop exit above its in-loop tail call. Against its parent,
the stage-1 compiler allocates less and runs fewer instructions in every
compile cell (perf/compiler's T3294, T12707, T783 and T9961 and MR
16269's CmmDiamondChain, each at -O0, -O1 and -O2), by more than 0.01%
and 0.005% in most and by up to 0.173% and 0.086%, compiling T3294
at -O0; the stage-2 compiler allocates 0.20% less compiling T9961 at -O0
(394109104 against 394903232 bytes), and less in every cell under +RTS
-A3G -V0. The code generated is the same with and without the pragma
and the flattening, every object built for the measurements being
identical but for symbol names derived from uniques in orthotope's A2T
benchmark, so the run-time figures above stand.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
1aeb784b by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Give a vreg the register a recorded join holds it in
Where a register is free for a vreg but the first register
that the assignments the block's jumps lead to, a recorded jump target's
or that of a block up to three jumps past a target not yet recorded
(rc_jumpLocs), give the vreg is another one, held by a vreg
that no instruction left in the block reads and that one
of those assignments has in its slot and none in a register,
allocRegsAndSpill_spill now spills the holder, a store the way there
would need anyway and none where the holder is in its slot already,
and gives the vreg its register in place of the free one. The test uses
the position of each instruction in its block and the block's last reads
of the vregs live out of it, built where the test consults them.
joinToTargets' now reads the registers live into each block
from the allocator's context (rc_live), so that master's linearRA,
raInsn, genRaInsn, joinToTargets and joinToTargets_again no longer pass
them on.
Measured on x86-64 against its parent, in instructions: megaparsec's
manyTill benchmarks take 0.074% to 0.14% fewer at -O2, and nofib's
puzzle 0.26% fewer at -O2 and 0.70% fewer at -O1, no benchmark taking
more. The stage-1 compiler allocates 0.081% to 0.12% more compiling
at -O0.
Assisted-by: Claude Opus 5.5
- - - - -
bcca6ae7 by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Spill a vreg its block reads no more
Of the vregs in both a register and their slot, else of those
in a register only, allocRegsAndSpill_spill evicts the first
that no instruction left in the block reads, else the first, except
that a vreg live into a jump target with no recorded assignment
that another block jumps to as well counts as read again where neither
the block nor that target is in a cycle. Evicted, such a vreg would
be in its slot in the assignment the block records for the join,
so that every later jump there would store it and the code after
the join reload it: in megaparsec's someTill the cold paths of a UTF-8
decoder, allocated before the hot one, so cost a store and a reload
an element. Where the block or that target is in a loop, as a loop's
head is, the eviction stands: there it keeps a register free
for the loop. The victim is sought in one fold over the assignment,
and only where a vreg of the evicted register class is live out
of the block, the previous choice standing elsewhere; the map of last
reads is built only where it is consulted, and a procedure's joins
outside cycles once, where building a block's last reads first consults
them.
Before that choice, the previous commit's rule applies where no register
is free as well: where the first register that the assignments
in rc_jumpLocs, a recorded jump target's or that of a block up to three
jumps past a target not yet recorded, give the vreg has a holder
that no instruction left in the block reads, and one
of those assignments has the holder in its slot and none in a register,
the holder goes to its slot here rather than on the way to that block,
and the vreg takes its register. The test runs only where a vreg
of the class is live out of the block, as such a holder is, and where
an assignment it could consult is recorded. With it at the end
of an earlier form of the series, against that end, nofib's puzzle
at -O2, containers' bcc.star and megaparsec's scientific benchmarks take
fewer instructions, no benchmark of nofib, containers or megaparsec
taking more beyond its noise, and the compiler's allocation
and instructions barely rise in each compilation measured.
Each of allocRegsAndSpill_spill's evictions now goes through one local
function, ahead, which spills a vreg in a register only by spillR
and recordSpill and ends in evicted, which updates the assignment, loads
the vreg if need be and allocates the rest: the previous commit's rule
takes it, and so does the victim, in place of master's two cases
of eviction and their own copies of that code, the assignment of a vreg
in both a register and its slot now set before the load rather
than after, neither reading what the other writes. The fold keeps
the highest rank so far with the first vreg of that rank (Victim),
a trade against keeping a candidate of each kind: measured on an earlier
form of the series, the compiler ran 0.0185% more instructions compiling
ManyBasicBlocks.cmm at -O0, 0.0225% more at -O1 and 0.0246% more at -O2,
allocating 0.025% to 0.029% less, and compiling T3294 0.021% fewer
at -O0 and 0.009% to 0.010% fewer at -O and -O2, allocating 0.32% less
at -O0, the assembly the same.
Master's anyUFM and allUFM, in GHC.Types.Unique.FM, now walk the map
by Foldable's any and all; liveOutClass tests a live-out set
by uniqSetAny.
Measured on x86-64 against its parent, in instructions, besides the rows
above: vector's awshcc takes 4.7% fewer at -O2, tridiag 1.7%
and quickhull 1.0%, containers' IntSet and IntMap union
and symmetricDifference benchmarks fall at -O2, and nofib's dom-lt takes
0.73% fewer at -O2 and 0.72% at -O1 and scs 0.45% at both, no benchmark
of those suites taking more beyond its noise. With the previous commit
the stage-1 compiler allocates 0.73% less compiling perf/compiler's
T3294 at -O0, and compiling MR 16269's CmmDiamondChain it runs 0.45%
to 0.55% more instructions and allocates 0.28% to 0.36% more, part
of them this commit's set of a procedure's joins outside cycles.
In orthotope's A2T benchmark, against the previous commit, the rule
is a trade: ==, /=, compare and < over large Storable arrays take 6.1%
to 7.1% more instructions, in a nest whose block before the inner loop,
needing a register for the loop's index, evicts the loop's bound, which
it reads no more, so that the loop reloads the bound at every trip; max
over large strided Unboxed arrays takes 13% fewer, and < over large
scaled and zipWith3A over large scalar Unboxed arrays gain alike.
Leaving the rule out reverts both. Counting such a vreg as read again
where a hotter block reads it, and storing it before a jump
into a hotter block or a loop that does not read it, with or without
a test of the loop's register pressure, each took back the rise but lost
elsewhere.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
eb44b362 by Mikolaj Konarski at 2026-11-20T00:13:15+01:00
Copy small loop heads over the jumps to them after block layout
Block layout lets one edge into a loop head fall through and makes
the others jump: the loop's entry once a run, every other back edge once
an iteration. copyLoopHeads, a new NcgImpl method that x86-64 implements
in GHC.CmmToAsm.X86.CodeGen and that cmmNativeGen runs under the chain
layout, after sequenceTop and before invertCondBranches, copies a loop
head of at most eight instructions and a conditional branch
over the jumps to it that the layout left: a block whose one successor
is the head, and which still ends in a jump to it, ends in the head's
instructions instead and goes straight on to whichever of the head's
successors its branch picks, the copy's last jump dropped where
its target is placed next, as dropJumps drops a jump. A copy
into the loop's entry saves the jump into the loop; a copy into a back
edge's source rotates the loop for that edge. Note [Copying loop heads];
Note [CFG based code layout] lists the new step.
A loop head is a target of a back edge that optimizeCFG now returns
with the weights: one of static prediction's loops (mkGlobalWeightsWith
returns loopInfo's back edges too), or, where static prediction does
not run, one of findBackEdges', which optHsPatterns raises.
copyLoopHeads looks only at the jumps to the back edges' targets,
and cmmNativeGen runs it only in a procedure with back edges. Where
static prediction runs, optimizeCFG also returns those of findBackEdges'
back edges that are none of the loops' and not into the entry, which
only an irreducible region has and calcFreqs finds; cmmNativeGen reads
them only for the layout's search below. The layout runs on the CFG
it has under -fno-asm-copy-loop-heads, so the block it lets fall through
into a head takes no copy, and no path through a copy executes more
instructions than through the jump it replaces. A copy's edges
in the CFG are the head's, unscaled: after layout only
invertCondBranches reads them. A block that follows a failed heap
or stack check takes no copy. Under -g a head's leading unwind
annotations are passed over, and left out of its copies, and a head
is copied only into a block whose unwinding rules at its jump
are the head's for each register whose rule both state, each side's
annotations folded into the rules in force after them, a later
annotation winning register by register: the one that follows a C call's
DELTA names MachSp alone, leaving the block's rule for Sp in force,
so that a block that calls C and does not move Sp afterwards takes
the copy under -g as without it. Where the block states no rule
for a register, as a fixup block of register allocation states none
at all, the copy runs under the rules DWARF has in force at the block's
own code, those of the code before it in the final layout, which can
differ from the head's own. BUG: after a C call those rules are wrong
already, master's addDefaultUnwindings (GHC.CmmToAsm.Dwarf) completing
every table that does not name Sp with the rule Sp has
at the procedure's entry, so that the rest of the block's code, a copy
at its end included, is unwound by that rule; Note [Copying loop heads]
says so, and master's compiler prints such rows too. The tests
CopyLoopHeadsCall and CopyLoopHeadsCallG count the head's comparison,
three times, in a loop whose jumps to the head each follow a C call,
without -g and with it; with the annotations compared whole, the second
found it once. Measured at the series' end against that comparison,
nofib's assembly without -g is the same at -O1 and -O2, and under -g
it changes in ben-raytrace's Sampler and in fannkuch-redux at both
levels.
Where the layout placed neither of the head's successors after a block
that takes a copy, the copy ends in a conditional jump and a jump.
pullRuns then moves to after the copy the run of blocks that one
of the two successors starts, the head's likelier successor tried first,
where no block falls into the run: the copy then falls into it,
or invertCondBranches makes it do so. No path loses a fall-through,
as neither the copy, nor the block before the run, nor the run's last
block fell into the block after it. The run that moves is not the first,
which holds the entry, nor one that starts with an info table, nor one
after which the copy's own run has already moved. A run moves only
if the last instruction of its last block transfers control
unconditionally, the test by which endsRun ends a run, so that pullRuns
does not rest on the code generator ending every block in such
a transfer; a TODO says that the test can go if that is made binding,
verifyBasicBlock checking, in a DEBUG compiler, only that no other
instruction follows a jump. A run also ends at a copy that ends
in a conditional jump and a jump where the block placed next has an info
table, which nothing falls into or past (fallsTo), as the continuation
that returns into a loop's head where its code is the head's: an info
table, no code, and the fall into the head. No fall-through is lost,
block layout keeping the jump into a block with an info table
and invertCondBranches dropping none into one. Taken to run on
into the head's run, a copy in the block placed before such
a continuation, as in the loop's entry, kept its conditional jump
and its jump where the copy made before layout fell into the loop's
exit: measured at the series' end on a program that builds a star graph
of 10000 vertices with Data.Graph's buildG and forces it 200 times,
as containers' benchmark buildG.star does, whose rnf of a list, entered
once an array element, has that shape, the program ran 177,686,901
instructions with the copying before layout, 179,686,689 with no run
ended there, one more an element, and 177,686,902 with it at -O2,
and 176,021,604, 178,021,322 and 176,022,116 at -O1. Every procedure
of nofib whose assembly that end of a run changes, at -O1 and -O2, holds
fewer instructions, most of them one fewer. A block that holds only meta
instructions, as one whose jump the layout dropped holds its unwinding
information under -g, counts as holding no code for the copy's last jump
and for the runs, so that the copies and the moves do not depend on -g.
pullRuns finds the first run of the chain of moved runs that a deciding
run ends in a map from each such chain's last run to its first, kept
with the map back by one insertion in each at a move: walking up
the chain run by run instead, measured at the series' end on a harness
calling copyLoopHeads on loops in sequence whose moves chain through
them, it ran 103.5e9 instructions at 16000 loops where it runs 4.0e9,
growing 3.5 to 4.1 times at each doubling where it grows 2.1 to 2.2
times.
Where no run moves, the copy still ends in a conditional jump
and a jump, neither to the block placed next, as the head has them:
in nofib's real/parser the copy of pgAlts's test in the loop's entry
ended in je exit; jmp body, the je never taken. Where the head's branch
says nothing of its likely side (cml_likely), which invertCondBranches
goes by, and the head's edge to the last jump's target weighs
over a tenth more than its other edge, the two jumps swap (orient),
so that the likelier path executes one jump, unless the conditional
jump's target has an info table (below). The margin leaves out the pairs
that static prediction weighs equal, which only a tie-break tells apart:
optimizeCFG's favourFewerPreds tilts the two edges of an evaluatedness
test toward the successor with fewer predecessors (as in nofib's
queens), and with the pair oriented by any difference in weight, queens
ran 0.5% more instructions at -O1, and grep, fibheaps and mate 0.2%
more, than with the copying before layout. TODO: the margin of a tenth
is arbitrary and should be generalised.
orient leaves a copy as it is where its conditional jump's target has
an info table: optHsPatterns' penalizeInfoTables lowers the weight
of an edge into such a block, since no block falls into it, and static
prediction starts each branch from the weights so lowered, so
that the lighter weight of that edge states no likelihood. A head
that tests whether a closure is evaluated and goes straight
to the continuation that the evaluation returns to has such an edge
on its evaluated side: in lookupGE4_fMin of containers' benchmark
lookupge-intmap that edge weighs less than the other, and with the jumps
swapped the copy in the procedure's entry jumps conditionally
to the code that enters the closure, the evaluated path paying the jump.
Where the last jump's target has an info table and its edge still weighs
over a tenth more, the swap stands. Measured at the series' end against
swapping those copies too, lookupge-intmap's GE Milan far runs one
instruction fewer a call of lookupGE4_fMin, hartel/sched 0.167%
and 0.174% fewer at -O1 and -O2, and hartel/parstof 0.058% fewer at -O1,
which was not traced. In nofib's assembly the rule undoes only the swaps
of copies that test a pointer's tag bits, and every procedure it changes
holds as many instructions, so that a program runs more where its paths
through those copies more often enter the closure than find
it evaluated: paraffins runs 0.0053% and 0.0043% more instructions
at -O1 and -O2 than with the copying before layout, hartel/transform
0.0070% and 0.0060% more and anna 0.0079% more at -O2, a cause deduced
from the code and not traced.
Where optimizeCFG returns no back edge, the blocks the entry reaches
hold no cycle that avoids it, and the chain layout's own search for back
edges could find only edges into the entry, which it raises none of,
raising a back edge only above another edge into its head
that is neither a back edge nor a self loop: an edge into the entry
from a block the entry reaches is one or the other, and the CFG holds
no other, getCfg taking only the blocks the entry reaches (ISSUE 28088).
So it now skips that search: cmmNativeGen hands the fact to master's
sequenceTop, which hands it to master's sequenceChain, each gaining
a Bool argument. This is a trade, measured against this commit with only
the skip reverted: compiling T9961 at -O0 the compiler runs 0.0070% more
instructions and allocates 0.0060% more, the cost of carrying one more
value through cmmNativeGen, mapM's loop and sequenceTop; against that,
compiling T783 it runs 0.141% fewer instructions and allocates 0.148%
less at -O and 0.132% and 0.138% at -O2, T12707 0.080% and 0.088% at -O
and 0.070% and 0.079% at -O2, and T3294 0.012% and 0.010% at -O
and 0.012% and 0.011% at -O2, the assembly the same.
The flag -fasm-copy-loop-heads, on at -O1 and -O2 as -fblock-layout-cfg
is, lets the copying be turned off; the tests CopyLoopHeads
and CopyLoopHeadsOff check both settings.
cmmNativeGen now passes Linear.regAlloc the estimate of block
frequencies rooted at the graph's g_entry, the first native block
on x86-64, in place of the function of an entry that regAlloc applied
to the procedure's first block.
In master's cmmNativeGen, optimizedCFG is now bound strictly, together
with the layout's flag and the copying step, from optimizeCFG's result
by one chain of tests before maybeDumpCfg, and branchOpt cases
on the copying step: where it runs, invertCondBranches is mapped
over the copied blocks with the CFG holding the copies' edges. invert
takes that CFG, and branchOpt's local invertConds is deleted. The step
is bound strictly, as a function of the blocks as layout placed them,
so that where it does not run it is a static Nothing: with the copies
and their CFG bound strictly instead, the compiler ran 0.029% more
instructions and allocated 0.040% more compiling T9961 at -O0, where
nothing is copied, and with them bound in branchOpt's where, 0.023%
and 0.027% more. With the step's own tests made after sequenceTop, every
decl, a data decl too, ran them after maybeDumpCfg's return, reloading
from the stack the variables cmmNativeGen holds in registers there:
by callgrind, compiling T9961 at -O, cmmNativeGen ran 53 instructions
more a decl, and the compiler ran 0.010% and 0.011% more instructions
compiling T9961 at -O and -O2 than with the copying before layout.
optimizeCFG returns the CFG and its two lists of back edges evaluated,
as master's cmmNativeGen forced the CFG that optimizeCFG returned there:
left lazy, the CFG made the compiler allocate 0.048% more compiling
T9961 at -O0 and 0.019% more at -O. Master's binding config = ncgConfig
ncgImpl, at the top of cmmNativeGen, gains a bang: left lazy, config
is a thunk that the code generator's state holds and that every read
of the config, the platform or the weights enters, an indirection after
its first evaluation; measured on master, the bang alone makes
the compiler run 0.143% fewer instructions compiling T9961 at -O0,
0.155% fewer compiling T3294 and 0.106% fewer compiling T12707 there,
the assembly the same (under +RTS -A3G -V0, where these compiles collect
nothing; under GHC's own RTS options the gain compiling T9961 at -O0
is about half). Below that binding, the chain's settings,
-fblock-layout-cfg, -fasm-copy-loop-heads and whether the backend
maintains the CFG, are read from config once a decl and bound strictly
as one Int, which the chain's two guards test: with config bound
strictly and the settings read in those guards instead, the compiler ran
0.012% more instructions compiling T9961 at -O0, and 0.002% and 0.003%
more at -O and -O2. Step 11 of the overview at the top of GHC.CmmToAsm
names the copying, and the README in compiler/GHC/CmmToAsm names Note
[Copying loop heads] for step 11 and, among the flags to switch off,
-fno-asm-copy-loop-heads before -fno-block-layout-cfg, which stops
the copying too.
Measured against the parent commit, in instructions, with no benchmark
of the battery rising by more than its noise: at -O2 nofib's programs
take 0.24% fewer (fannkuch-redux 2.1%, knights 1.3%, eff/CSD 1.1%,
digits-of-e1 1.0%), containers' benchmarks 0.51% fewer (intmap
lookup_half 7.2%, lookup_most 5.7%, lookup_hits 5.6%, intset member
3.4%, nubInt issue1202_repeat 3.3%), megaparsec's 0.35% fewer (string'
1.1% to 1.2%, skipManyTill 1.1%) and vector's 1.3% fewer
(nextPermutation 5.3%, nextPermutationBijective 4.1% to 4.8%, hybcc
0.97%); at -O1 nofib's 0.22% fewer (fannkuch-redux 1.9%), containers'
0.58%, megaparsec's 0.35% (reachOffsetNoLine 1.6%, reachOffset 0.92%
to 1.3%) and vector's 1.1% (leaffix 0.62%, awshcc 0.61%); at -O0, where
it does not run, nofib's 0.15% fewer, through the libraries' code.
This takes back some of the trades of the commit that lets a loop's back
edge outrank its entry: IntSet's difference and intersection benchmarks
take 0.85% to 0.87% fewer instructions than at the parent at -O2
and -O1, nubInt's noFusion_repeat 2.4% fewer, megaparsec's reachOffset
at -O1 0.92% to 1.3% fewer; and vector's awshcc at -O1, whose loop's two
back edges both jumped, executes fewer jumps a call, those of one
of those back edges among them. Code grows: nofib's objects' text
by 0.66% at -O2 and 0.54% at -O1, the stage-2 compiler's by 0.75%.
The stage-1 compiler runs 0.0196% and 0.0158% more instructions
and allocates 0.0200% and 0.0214% less compiling perf/compiler's T9961
at -O and -O2, as measured on this commit with config forced by the Int
alone, the bang unwritten (TODO: the rise is the work the copying does
a procedure; by callgrind at -O on this commit without the Int
and the bang, where the rise was 0.0222%, deciding on and running
the copying, in cmmNativeGen, copyLoopHeads and invertCondBranches
over the copies, makes 0.015% of the instructions, testing its three
settings, kept live in cmmNativeGen across register allocation, 0.0073%,
and the skip's test 0.0017%, against 0.0017% fewer from the rest
of the change; this commit's rise is not split so), allocates 0.045%
and 0.13% less for T12707 and T783 at -O, for skipping the chain
layout's search for back edges (above), and 0.045% and 0.010% more
with that search kept, and the stage-2 compiler 0.11% and 0.14% more
for nofib's puzzle and reptile at -O2, its code generator working
on the copies.
Against the form of this change that copied loop heads before layout,
measured at the series' end with both stage-1 compilers over the same
libraries, in instructions, the lowest of three rounds: nofib's programs
take 0.009% fewer in total at -O1 and 0.025% fewer at -O2, dom-lt 0.43%
and 0.47% fewer, last-piece 0.32% and 0.35% fewer and hartel/sched 0.17%
and 0.18% fewer at -O1 and -O2, and mkhprog 0.53% and infer 0.34% fewer
at -O2; parser runs within 0.002% of its counts there; and no program
takes 0.05% more. Compiling T9961 at -O and -O2, where its assembly
differs, the compiler runs 0.003% and 0.002% more instructions,
allocating 0.009% and 0.004% less. Measured at an earlier form
of the series' end, it ran 0.041% and 0.034% fewer instructions
compiling ManyBasicBlocks.cmm at -O1 and -O2, 0.013% fewer compiling
T9961 at -O0, allocating 0.021% less, and 0.010% fewer compiling T12707
there.
Measured on the battery with the copying after layout but before orient,
against the form before layout: containers' nubInt and nubOrd
noFusion_repeat rows ran one instruction more an element, 2.0% to 2.8%
more at -O2 and -O1, vector's small next/prevPermutation rows 1.97% more
at -O2, and the stage-2 compiler 0.047% and 0.041% more instructions
compiling T3294 at -O and -O2, in a loop of GHC.Cmm.Sink entered
from a copy of its head's test left ending in a conditional jump
and a jump, as containers' nubIntOn's is. On programs that hold
those rows' code, compiled at the series' end with orient switched off
and on, orient takes the nubInt and nubOrd repeat rows from 1.9%
and 1.7% more than the form before layout to 0.002% more,
and the Permutation rows from one instruction more a call to 14,463
fewer over 3 x 9! calls; Sink's loop, read and not run, then has
the entry path of the form before layout and one jump more on an entry
that leaves at once.
Measured on the battery at the series' end against the form before
layout, containers' Set and Map fromDistinctAscList:fusion benchmarks
run 0.59% and 0.73% more instructions at -O2 and 0.60% and 0.73% more
at -O1, one jump more every two elements, with no copy involved:
in their fused loop a block that joins three paths back to the loop's
test has, by static prediction, its heaviest edge from the block
that runs when the stack is empty, which block layout lets fall through,
as it does under -fno-asm-copy-loop-heads. Before, the entry's copy,
made ahead of layout, gave the loop two entries, findBackEdges' search
took the two other edges into that block for back edges,
and preferBackEdges raised them: a gain by the search's order,
not by the weights. containers' bcc.line,n=100 runs 0.12% more at -O1,
one jump more a vertex, and, measured on a build of the benchmark's
module, about six instructions a vertex fewer than without the copies:
a copy there ends in a conditional jump and a jump, each of whose
targets another block falls into, so that pullRuns moves neither, where
the copy made before layout had taken one of the two falls. A2T's cells
run a few instructions a call more or fewer, under 1%, about as many
cells each way; that orient's choices on predictions near a coin flip
account for them is inferred, not traced.
The bound of eight instructions, measured on the form that copied loop
heads before layout: at four, nubInt's issue1202_repeat keeps a third
of its gain; at six, nofib's x2n1 runs 0.86% more instructions at -O2
and at -O1, in the loops of (^), whose heads hold eight. Against six,
eight trades code size for run time: no program runs more instructions
or allocates more by 0.2%, and nofib's objects grow by 0.01% in total
at -O2 and 0.03% at -O1, x2n1's by 3.1%. A bound of ten gained no more,
its objects larger; nor did heads of up to 64 copied only over a jump
weighted at least a sixteenth for each instruction beyond six, their
objects larger too. Not taken: a block ending in a conditional branch
and a jump to the head copying it too, which moved nothing in nofib;
and a second pass, its back edges found again by findBackEdges, which
cost CmmDiamondChain 0.5% more compile allocation.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
3461f01e by Mikolaj Konarski at 2026-11-20T00:13:15+01:00
Use one estimator of block frequencies for the layout and the allocator
Static prediction made the layout's estimate by mkGlobalWeights
over LabelMaps: loopInfo's dominators and loops,
staticBranchPrediction's probabilities, normalised
by cfgEdgeProbabilities, and calcFreqs' fixpoint; blockFrequencies made
the linear allocator's in two arrays by the same rules. Both are now
made by one estimator, freqEstimate, the allocator's array code, which
returns the probabilities and the back edges too, on two CFGs:
staticPredCfg calls it on the CFG shortcutting leaves,
and blockFrequencies on the CFG as instruction selection gives it;
and loopInfo, LoopInfo, mkGlobalWeights, mkGlobalWeightsWith,
staticBranchPrediction, cfgEdgeProbabilities, calcFreqs and CFG's
revPostorderFrom are deleted, with the commented-out traces naming them.
The graph allocator's spill costs no longer scale the counts of uses
and definitions by block frequencies, which nothing reads: chooseSpill
takes the lifetimes alone, and pprSpillCostRecord, the one function
that names the counts, has no caller. Each use and definition counts 1,
as where no CFG was passed, and master's slurpSpillCostInfo, regAlloc
and regAlloc_spin lose their CFG argument, cmmNativeGen no longer
passing livenessCfg.
Where a loop head has back edges from blocks it dominates
and from blocks it does not, its loop is now the dominated ones',
as loopInfo's was, where blockFrequencies left the head out;
and a loop's levels count the blocks reached from its warm back edges,
as staticBranchPrediction counted them, where blockFrequencies counted
the whole loop. calcFreqs' irreducible skip stays for the layout: given
True, as staticPredCfg gives it, freqEstimate skips a block entered
by a back edge from a block it does not dominate, which then runs once
each time a loop holding it, or the procedure, runs where it heads
a loop, and else never; given False, as blockFrequencies gives it,
it sums the block's inflow as before. A branch's weights are made
probabilities once, before the rules apply, where both estimators made
them so again after the rules, so that the rules' probabilities
are rounded once; this moves blocks in a few of nofib's objects at -O1
and -O2, their instruction counts the same.
ohPredicts, static prediction's rule that a comparison with a literal
comes out unequal, which "Add an estimate of block frequencies
for the linear allocator" moved out of master's staticBranchPrediction,
read which side of a two-way branch an edge is on off the label
the branch was made with (s1 == ltrue), as master's did. The edge
no longer ends at that label once a fixup block of the register
allocator (addNodesBetween) or a shortcut (shortcutWeightMap) has moved
it: where the moved true edge's new target had the smaller label
of the two, the layout's estimate took the likely side for the unlikely
one. The fault is master's; it costs only speed, on x86-64
under -fcmm-static-pred. The BUG statement at ohPredicts that says
so is deleted. getCfg now records the side on the edge: master's
BranchInfo gets the constructors NoInfoTrue and HeapStackCheckTrue
for the edge made for a CmmCondBranch's true target, isTrueSide reads
them, ohPredicts goes by it, and predictBranch loses the label
it compared. An edge keeps its EdgeInfo wherever it is moved,
so the side stays that of the branch; a branch whose two targets are one
block has one edge, recorded as the true side. Master's CmmSource's
trans_info becomes strict and master's getCfg evaluates a branch's info
where it makes the edges, so that the two sides' sources replace the one
source and its thunk; master's isHeapOrStackCheck matches both check
constructors; and master's invertCondBranches (GHC.CmmToAsm.X86.CodeGen)
compares the two edges' Cmm nodes where it compared their
TransitionSources, which now differ between a branch's sides,
and accepts what it accepted, the info being a function of the node.
The test StaticPredShortcut in testsuite/tests/cmm/should_compile has
a true edge that -fasm-shortcutting moves to a block whose label
is smaller than the false target's, and checks on x86-64 that the false
target's code comes before the true target's in the assembly, as it does
without -fasm-shortcutting; with the side read off the label, the layout
put the true target's first.
Measured against its parent. Compiling, the stage-1 compiler runs 8.04%
and 8.02% fewer instructions and allocates 9.0% and 8.9% less on MR
16269's CmmDiamondChain at -O1 and -O2, 2.8% and 2.6% fewer instructions
on T783 at -O and -O2, 2.5% and 2.3% on T12707, 0.72% and 0.69% on T3294
and 0.054% and 0.068% on T9961, and moves by 0.026% or less at -O0;
the stage-2 compiler runs 2.4% and 3.4% fewer instructions on nofib's
puzzle at -O1 and -O2 and, over nofib's modules, 1.3% and 1.5% fewer
instructions and 2.0% and 2.1% less allocation at -O1 and -O2 (geometric
means).
The generated code is the same at -O0; at -O1 and -O2, a few of nofib's
objects differ, the estimates differing by rounding only but
for the allocator's of one procedure in spectral/para at -O2, which
moves by the rule above, and for the branches whose side a stale label
inverted; no nofib program moves by 0.2% in instructions or allocation,
and at -O1 and -O2 containers' benchmarks move by 0.046% at most,
megaparsec's by none past 0.05%, and vector's by 0.028% at most.
Over containers at -O1 and -O2 and nofib at -O1 and -O2, no two-way
branch's probability moves but by rounding, or where a stale label
inverted it, and the back edges are the same as the old estimator's,
and the layout's frequencies differ from its by rounding only,
or by such a branch.
Measured at the series' end against it without the recorded side,
with stage-1 compilers over the same libraries: an instrumented pair
traced every branch ohPredicts predicts in nofib's modules and every
move of an edge, and replaying the moves, the recorded side
is the branch's on every edge with a stale label at -O1 and -O2,
and equal to the old reading on every other; the old reading
was inverted nowhere at -O1, and at -O2 in real/fluid,
shootout/k-nucleotide, spectral/hartel, imaginary/bernouilli
and shootout/n-body. nofib's assembly is the same at -O1 and differs
at -O2 in modules of those programs but n-body. Of their executed
instructions (five interleaved rounds, the lowest) none rises beyond
its spread, spectral/hartel/ida's fall by 0.0025%,
and shootout/k-nucleotide's lowest is 0.012% lower, within the spread
of the rounds with the recorded side. Compiling T3294, T12707, T783
and T9961 at -O0, -O and -O2 and ManyBasicBlocks.cmm at -O0, -O1
and -O2, the compiler runs no more instructions in any cell
and allocates at most 0.006% more (T783 at -O0); with the side
as a third field of CmmSource instead, it allocated up to 0.026% more.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
cd45ff8f by Mikolaj Konarski at 2026-11-20T00:13:15+01:00
Count irreducible regions in layout frequencies and duplicate small runs
The layout's estimate skipped, as calcFreqs did, every block entered
by a back edge from a block it does not dominate: such a block ran once
each time a loop holding it, or the procedure, ran where it headed
a loop, and else never, whatever flowed into it. freqEstimate now sums
its inflow as for any other block, as the allocator's estimate does,
and loses its Bool argument.
Counting the region's blocks changes the layout of orthotope's
$wabsAxesAndStartT: the small block that returns, which more than one
copy of the loop's head wants, is no longer placed after the back edge's
source that the loop's path takes, so the copying moves it after
the first copy in placement order that wants it, the entry's,
and the loop's path through its own copy jumps to it, one jump more
a call. So a copy left ending in a jump to a small run that another copy
took now ends in a duplicate of that run instead: at most eight
instructions, the bound of a copied head, and a jump, with no info
table, call or label, the condition inverted where the run
is the conditional jump's target. Under -g the duplicate drops
the unwinding information ahead of the run's first instruction,
as a copy drops a head's, and is made only where the copying block's
rules at its end agree with the run's for each register both state;
a run holding such information after an instruction, as one whose code
adjusts Sp does, is not duplicated.
Measured against its parent without the duplication, here and
in the next paragraph. Compiling, the stage-1 compiler runs 0.012% fewer
instructions on MR 16269's CmmDiamondChain at -O1 and -O2, and within
0.0025% elsewhere.
At -O1 and -O2, some of nofib's objects differ. nofib's mkhprog at -O2
and eliza and megaparsec's many and skipMany at -O1, which this change
moved on earlier forms of the series, move by 0.06% or less; containers'
benchmarks move by 0.041% at most, vector's by none past 0.05%.
Over containers at -O1 and -O2 and nofib at -O1 and -O2, no two-way
branch's probability moves and the back edges stay the same;
the frequencies differ from the parent's in some procedures
of containers' and of nofib's at -O1 and -O2.
Measured against this commit without the duplication, in instructions:
orthotope's A2T benchmark takes 0.068% fewer by the geometric mean, 114
cells fewer by more than 0.2% and none more; megaparsec's benchmarks
0.065% fewer at -O1, 13 falling and none rising, and at -O2 none rises
or falls; at -O2 seven of containers' benchmarks fall and none rises;
vector's move by none past 0.05%; and no nofib program runs more
instructions or allocates more by 0.2%. No compile cell moves past 0.01%
in allocation or 0.005% in instructions, and their assembly is the same.
The duplicates trade code size for run time: nofib's objects grow
by 0.137% in total at -O2, 24 programs' by more than 0.2%
(fannkuch-redux 1.58%, pidigits 1.47%, primetest 1.25%), and by 0.083%
at -O1, 18 programs' by more than 0.2% (pidigits 1.30%, puzzle 1.13%);
in nofib's assembly every block the duplication changes has a jump
replaced by its target's code.
Assisted-by: Claude Opus 5.5
- - - - -
9656b83b by Mikolaj Konarski at 2026-11-20T00:13:16+01:00
Walk liveness first over instructions as the code generator gives them
natCmmTopToLive wrapped every instruction as LiveInstr (Instr i)
Nothing, in a list of its own, which the first liveness walk dropped
at once for a LiveInstr carrying the liveness. Now natCmmTopToLive
returns the procedure's SCCs of NatBasicBlocks, and the walk takes
an accessor giving each element's InstrSR: Instr on the first walk,
a LiveInstr's own when the graph allocator walks again. regLivenessOf
is INLINE and livenessSCCs is a wrapper around a local loop, so
that the first walk's copy for x86 has the accessor constant
in its loops over the SCCs: as a plain recursive function, specialised
to x86 with the accessor an argument, it made the compiler run 0.046%
more instructions and allocate 0.056% more compiling CmmDiamondChain
at -O0. livenessBlock takes the accessor as an argument: INLINE, it made
the compiler run 0.05% more instructions compiling T3294 at -O0.
livenessBack is a wrapper around a local loop too, which does not pass
the accessor, the platform and the block map again at each instruction.
sccBlocks, master's, now returns beside the SCCs a map of each block's
jump targets, the lists its graph's nodes carry, and LiveInfo, master's,
carries the map in a fifth field, matched with one field more at each
of its sites: Liveness.hs's, Linear.regAlloc's, and the graph
allocator's in Spill.hs, SpillClean.hs and SpillCost.hs, which pass
it through or ignore it. livenessCyclic takes a block's predecessors
in the SCC from the map and linearRegAlloc' its context's rc_succs,
where each walked every instruction of the SCC or of the procedure
(jumpSuccs, deleted): the compiler runs fewer instructions compiling
T9961 at -O0 and allocates less compiling CmmDiamondChain at -O0.
The liveness pass is pure: master's cmmTopLiveness and regLiveness,
and regLivenessOf, return the declaration itself, where they returned
it in UniqDSM without drawing a unique, and Liveness no longer imports
GHC.Types.Unique.DSM. cmmNativeGen maps the pass over the procedures
by strictMap and gives the allocators usGen, the supply the pass
returned untouched, and the graph allocator binds the code it walks
again by let and map. Master's livenessSCCs and livenessBack no longer
take the starting values of their accumulators, which their one caller
gave as empty.
Measured with stage-1 compilers against the parent commit on x86-64:
the assembly of perf/compiler's T3294, T12707, T783 and T9961 at -O0, -O
and -O2 and of MR 16269's CmmDiamondChain at -O0, -O1 and -O2
is byte-identical, and so is that of T3294 and T9961 at -O
under -fregs-graph and -fregs-iterative. The stage-1 compiler allocates
1.76% less compiling T3294 at -O0, 1.55% less for T9961, 1.17%
for T12707 and 1.01% for T783, 0.051% to 0.57% less at -O and -O2,
and 0.63% to 0.72% less for CmmDiamondChain, and runs 0.057% to 1.05%
fewer instructions, counted with an allocation area larger than all
a compilation allocates.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
ff5b0a1d by Mikolaj Konarski at 2026-11-20T00:13:16+01:00
Lower master's NCG helpers' compile cost and drop needless blocks
mapWeights in GHC.CmmToAsm.CFG rebuilt the CFG by a fold over the list
of its edges, inserting each edge again by addEdge with its new weight.
It now maps over the CFG's nested maps, which keep their shape.
adjustEdgeWeight and setEdgeWeight looked the edge up and inserted
it again by addEdge. They now adjust the edge in place by mapAdjust,
setEdgeWeight by adjustEdgeWeight.
optHsPatterns' favourFewerPreds counted the predecessors that could fall
through into a block in a reversed copy of the CFG filtered
to those edges, taking the length of the block's list of successor edges
there, for both targets of each conditional branch of equal weights.
It now counts them for every block by one fold over the CFG into a map,
and skips a branch whose two targets have equal counts, whose weights
the adjustment by zero left as they were. Master's alternative
of its local modifiers for equal counts, which adjusted both edges
by zero, is deleted, unreachable under the skip.
sequenceChain in GHC.CmmToAsm.BlockLayout built a set of the blocks
its chains placed and filtered every block of the procedure against it,
for a list of unplaced blocks that is empty unless the layout has
a fault. The set and the filter now run only where the chains' list
of blocks is not as long as the procedure's map of blocks. Where
the lengths are equal and a block is unplaced, the list names a block
twice or one not in the map, which fails later, in the assembler
or in getBlock, with the unplaced blocks appended or without;
the assertion that every block is placed stays.
In the same module, buildChains' fuseChain took the fused chain's first
block as the head of takeL 1 and its last as the head of takeR 1, each
building a list out of the chain's OrdList: fromOL walks the chain's
left spine and fromOLReverse its right one, allocating as they go.
It now takes them by headOL and lastOL, which give the same block
and build no list. The two agree on every chain buildChains builds: each
is made by chainFromList of two blocks, chainSingleton, chainSnoc,
chainCons and chainConcat, the last three on non-empty chains,
so no part of a chain is an empty list, and headOL and lastOL panic only
on a list with an empty part; a test of the OrdList module over every
chain those build up to depth three, and over long spines of each kind,
found no difference. Measured at the series' end against it without
this change, nofib's assembly at -O1 and -O2 and the compile cells'
are the same, no cell runs 0.005% more instructions or allocates 0.01%
more, and ManyBasicBlocks compiles with 0.025% and 0.027% fewer
instructions and 0.116% less allocation at -O1 and -O2; the diamonds
scaling probe allocates 0.4%, 0.9% and 2.0% less at N = 100, 200
and 400, the bytes saved growing as N squared. On the parent of "Copy
small loop heads over the jumps to them after block layout", where
deadchain's chains fuse in fuseChain, the change also lowers deadchain's
allocation by 2.4% at N = 400.
combineNeighbourhood's applyEdges took the first and last blocks of each
chain it fused by getFronts and getEnds of the new chain, and the parts'
other ends by getFronts c1 and getEnds c2. getEnds is takeR, the first
two of fromOLReverse, which walks the chain's OrdList down its right
spine, allocating as it goes, until it meets the last blocks; getFronts
walks the left spine alike. Where chains fuse one after another
onto the front of one chain, its right spine grows by one at each
fusion, and the walks cost a quadratic in the fusions. FrontierMap's
entries now hold both of a chain's ends, computed once a chain
as before, and a fused chain's are taken from its parts': its first
blocks are the first of c1's and then of c2's, its last the last of c2's
and then of c1's. Those are the same lists in the same order, as fromOL
and fromOLReverse of an appOL are those of its parts appended: a test
of the OrdList module found them equal for every pair of lists
its functions build up to depth two, and for long spines of each kind.
One entry now serves both maps. The code is master's but for one line,
applyEdges' result, which "List a CFG's edges once in block layout"
wrote. Measured at the series' end against it without this change,
nofib's assembly at -O1 and -O2 and the compile cells' are the same,
no cell runs 0.005% more instructions or allocates 0.01% more, T3294
compiles with 0.107% and 0.103% less allocation at -O and -O2 and T12707
with 0.043% and 0.040% less; the deadchain scaling probe at -O1
allocates 2.4%, 4.8% and 9.2% less at N = 200, 400 and 800 and runs
0.7%, 1.6% and 3.4% fewer instructions, the probes allocs and calls
allocate 0.2% to 0.5% less from N = 100 to 400, chain and nest 0.1%
to 0.3% less, and every probe's assembly is the same. On the parent
of "Copy small loop heads over the jumps to them after block layout"
the change lowers the allocation of T3294, T12707, allocs, calls, chain
and nest as here, the walks costing there already, and moves deadchain's
by 32 bytes: the quadratic on deadchain entered at that commit.
shortcutBranches in GHC.CmmToAsm applied the mapping of the blocks
it cut to every procedure even where it cut none. Where the mapping
is empty it now returns the procedures as they are.
shortcutBranches' build_mapping shorted only a block of exactly one
instruction, a jump. Under -g a block that holds only its jump also
holds the location and unwinding information that -g adds, so
it was kept, and static prediction and layout saw another CFG
than without -g. Under -g on ELF targets a block whose instructions
are meta instructions and then one jump is now shorted as a lone jump
is; elsewhere the test is master's. That information covered only
the jump, and the debug block of a label that is gone is dropped
by cmmDebugLink as it was for a shorted block. The BUG statement
at build_mapping now names the targets where the block is still kept,
those where ncgDwarfUnwindings does not hold, Windows among them.
x86's genCondBranch passed genCondBranch' whether the platform
is 32-bit, which genCondBranch' did not read; genCondBranch' is now
genCondBranch's body, and Note [CFG Edge Weights] in GHC.CmmToAsm.CFG
names genCondBranch as the place that adds 3 to the weight
of a floating-point comparison's false edge.
tryToInline in GHC.Cmm.Sink inlined a trivial assignment that is live
after the node into the node, rebuilding and folding the node, even
where the node does not mention the assignment's register. Such
an assignment is now kept with the node left as it is. Where it does
inline and keep an assignment, it passes on the counts of the registers
the node uses with the right-hand side's added, as it does where
it inlines and discards one, so that a register an earlier kept inlining
brought into the node is counted.
sccBlocks in GHC.CmmToAsm.Reg.Liveness listed a block's jump targets
by `concatMap jumpDestsOfInstr`. On x86 the block of a floating-point
comparison that tests for an unordered result ends in jumps that name
one target twice, so the list held that target twice. It now leaves out
the single target of a jump that repeats one of the first two distinct
such targets of the block, and lists a jump table's targets as before;
the list keeps every target, in the order of its first jump.
Master's raInsn in GHC.CmmToAsm.Reg.Linear kept, in a block comment,
a trace of the move it eliminates that names r_dying and w_dying, which
are not in scope there, so that the trace would not compile if enabled;
it is deleted, and the comment above it, which said that a fixed source
register is allocatable, as otherwise it would not be in r_dying, names
liveDieRead, the set in which the move's guard looks the register up.
joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets takes a jump's
destinations once, and a jump table lists a target once for each entry
naming it. Where such a target needed a fixup block, its first entry
made one and the jump was patched to send every entry naming the target
there; each later entry then made the same moves again, into a block
nothing jumps to, which was given an edge in the CFG, laid out
and emitted. Once joinToTargets_again has made the fixup block, it now
drops the target's later occurrences from the destinations still
to consider. The BUG statement there is deleted. The test JumpTableFixup
in testsuite/tests/cmm/should_compile compiles a jump table that names
such a target in three entries and checks that the linear allocator
records one fixup block, on x86-64.
In GHC.CmmToAsm.Reg.Graph.SpillCost, under the comment's statement
of Chaitin's formula, which weights each use and def by its block's
frequency, a sentence now says that slurpSpillCostInfo counts every use
and def once, whatever the frequency of its block.
GHC.CmmToAsm.Reg.Linear.Base's ReadingOrWriting, which no code used
and the module did not export, is deleted, and so is the module's
LambdaCase pragma, which no code of the module uses.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
162 changed files:
- compiler/GHC/Cmm.hs
- compiler/GHC/Cmm/Config.hs
- compiler/GHC/Cmm/ContFlowOpt.hs
- compiler/GHC/Cmm/Graph.hs
- compiler/GHC/Cmm/Info/Build.hs
- compiler/GHC/Cmm/LayoutStack.hs
- compiler/GHC/Cmm/Lint.hs
- compiler/GHC/Cmm/Liveness.hs
- compiler/GHC/Cmm/Node.hs
- compiler/GHC/Cmm/Opt.hs
- compiler/GHC/Cmm/Pipeline.hs
- compiler/GHC/Cmm/ProcPoint.hs
- compiler/GHC/Cmm/Reg.hs
- compiler/GHC/Cmm/Sink.hs
- compiler/GHC/Cmm/UniqueRenamer.hs
- compiler/GHC/Cmm/Utils.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Config.hs
- compiler/GHC/CmmToAsm/Dwarf.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64.hs
- compiler/GHC/CmmToAsm/LA64/CodeGen.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PIC.hs
- compiler/GHC/CmmToAsm/PPC.hs
- + compiler/GHC/CmmToAsm/README.md
- compiler/GHC/CmmToAsm/RV64.hs
- compiler/GHC/CmmToAsm/RV64/CodeGen.hs
- compiler/GHC/CmmToAsm/Reg/Graph.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Base.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Coalesce.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Linear/AArch64.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Base.hs
- compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- compiler/GHC/CmmToAsm/Reg/Regs.hs
- compiler/GHC/CmmToAsm/Reg/Target.hs
- compiler/GHC/CmmToAsm/Wasm/FromCmm.hs
- compiler/GHC/CmmToAsm/X86.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToAsm/X86/Regs.hs
- compiler/GHC/Data/Graph/Directed.hs
- compiler/GHC/Data/Word64Map/Internal.hs
- compiler/GHC/Data/Word64Map/Lazy.hs
- compiler/GHC/Data/Word64Map/Strict.hs
- compiler/GHC/Data/Word64Map/Strict/Internal.hs
- compiler/GHC/Driver/Config/Cmm.hs
- compiler/GHC/Driver/Config/CmmToAsm.hs
- compiler/GHC/Driver/Config/StgToCmm.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Platform/Reg.hs
- compiler/GHC/Platform/Reg/Class.hs
- compiler/GHC/StgToCmm/Bind.hs
- compiler/GHC/StgToCmm/Config.hs
- compiler/GHC/StgToCmm/DataCon.hs
- compiler/GHC/StgToCmm/Monad.hs
- compiler/GHC/StgToCmm/Utils.hs
- compiler/GHC/Types/Unique/FM.hs
- compiler/GHC/Types/Unique/Set.hs
- docs/users_guide/using-optimisation.rst
- rts/Weak.c
- rts/include/Cmm.h
- + testsuite/tests/cmm/should_compile/CmmRegOffW16.cmm
- + testsuite/tests/cmm/should_compile/JumpTableFixup.cmm
- + testsuite/tests/cmm/should_compile/StaticPredShortcut.cmm
- + testsuite/tests/cmm/should_compile/StaticPredShortcut.stderr
- + testsuite/tests/cmm/should_compile/T27800.cmm
- + testsuite/tests/cmm/should_compile/T27980.cmm
- + testsuite/tests/cmm/should_compile/T8327.cmm
- testsuite/tests/cmm/should_compile/all.T
- + testsuite/tests/cmm/should_compile/cmm_fold_elemAt.hs
- + testsuite/tests/cmm/should_compile/cmm_fold_lit.cmm
- + testsuite/tests/cmm/should_compile/cmm_fold_scaled.cmm
- + testsuite/tests/cmm/should_compile/cmm_fold_scaled.stderr
- testsuite/tests/cmm/should_run/all.T
- + testsuite/tests/cmm/should_run/cmm_addnf.hs
- + testsuite/tests/cmm/should_run/cmm_addnf.stdout
- + testsuite/tests/cmm/should_run/cmm_addnf_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_refetch_reassign.hs
- + testsuite/tests/cmm/should_run/cmm_refetch_reassign.stdout
- + testsuite/tests/cmm/should_run/cmm_refetch_reassign_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_refetch_store.hs
- + testsuite/tests/cmm/should_run/cmm_refetch_store.stdout
- + testsuite/tests/cmm/should_run/cmm_refetch_store_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_regoff.hs
- + testsuite/tests/cmm/should_run/cmm_regoff.stdout
- + testsuite/tests/cmm/should_run/cmm_regoff_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_reserved_seed.hs
- + testsuite/tests/cmm/should_run/cmm_reserved_seed.stdout
- + testsuite/tests/cmm/should_run/cmm_reserved_seed_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_scaledlit.hs
- + testsuite/tests/cmm/should_run/cmm_scaledlit.stdout
- + testsuite/tests/cmm/should_run/cmm_scaledlit_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_sinkoff.hs
- + testsuite/tests/cmm/should_run/cmm_sinkoff.stdout
- + testsuite/tests/cmm/should_run/cmm_sinkoff_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_swoff.hs
- + testsuite/tests/cmm/should_run/cmm_swoff.stdout
- + testsuite/tests/cmm/should_run/cmm_swoff_cmm.cmm
- + testsuite/tests/codeGen/should_compile/ClosureTblAmode.hs
- + testsuite/tests/codeGen/should_compile/ClosureTblAmode.stderr
- + testsuite/tests/codeGen/should_compile/CopyLoopHeads.hs
- + testsuite/tests/codeGen/should_compile/CopyLoopHeads.stderr
- + testsuite/tests/codeGen/should_compile/CopyLoopHeadsCall.hs
- + testsuite/tests/codeGen/should_compile/CopyLoopHeadsCall.stderr
- + testsuite/tests/codeGen/should_compile/CopyLoopHeadsCallG.stderr
- + testsuite/tests/codeGen/should_compile/CopyLoopHeadsOff.stderr
- + testsuite/tests/codeGen/should_compile/EnumTagOffset.hs
- + testsuite/tests/codeGen/should_compile/EnumTagOffset.stderr
- + testsuite/tests/codeGen/should_compile/StackLayoutCallLoop.hs
- + testsuite/tests/codeGen/should_compile/StackLayoutTagLoop.hs
- + testsuite/tests/codeGen/should_compile/StackLayoutTagLoop.stderr
- + testsuite/tests/codeGen/should_compile/T20333.hs
- + testsuite/tests/codeGen/should_compile/T20333.stderr
- + testsuite/tests/codeGen/should_compile/T20333b.hs
- + testsuite/tests/codeGen/should_compile/T20333b.stderr
- + testsuite/tests/codeGen/should_compile/T20333c.hs
- + testsuite/tests/codeGen/should_compile/T20333c.stderr
- + testsuite/tests/codeGen/should_compile/T20334.hs
- + testsuite/tests/codeGen/should_compile/T20334.stderr
- + testsuite/tests/codeGen/should_compile/T27991.hs
- testsuite/tests/codeGen/should_compile/all.T
- testsuite/tests/codeGen/should_gen_asm/T24813.asm
- testsuite/tests/codeGen/should_gen_asm/bytearray-memcpy-unroll.asm
- testsuite/tests/codeGen/should_gen_asm/bytearray-memset-unroll.asm
- + testsuite/tests/regalloc/T27619.hs
- + testsuite/tests/regalloc/T27800_itm.cmm
- + testsuite/tests/regalloc/T27981.hs
- testsuite/tests/regalloc/all.T
- testsuite/tests/regalloc/regalloc_unit_tests.hs
- + testsuite/tests/simd/should_run/T27638.hs
- + testsuite/tests/simd/should_run/T27638.stdout
- + testsuite/tests/simd/should_run/T27638a.hs
- + testsuite/tests/simd/should_run/T27638a.stdout
- + testsuite/tests/simd/should_run/T27638b.hs
- + testsuite/tests/simd/should_run/T27638b.stdout
- + testsuite/tests/simd/should_run/T27638c.hs
- + testsuite/tests/simd/should_run/T27638c.stdout
- + testsuite/tests/simd/should_run/T27638d.hs
- + testsuite/tests/simd/should_run/T27638d.stdout
- + testsuite/tests/simd/should_run/T27638e.hs
- + testsuite/tests/simd/should_run/T27638f.hs
- + testsuite/tests/simd/should_run/T27638f.stdout
- + testsuite/tests/simd/should_run/T27638g.hs
- + testsuite/tests/simd/should_run/T27638g.stdout
- testsuite/tests/simd/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/7f773c2981b4257b7fc19aa779321eā¦
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/7f773c2981b4257b7fc19aa779321eā¦
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