-
aff1b84b
by Duncan Coutts at 2026-11-30T04:10:39-05:00
Move idle GC tracking to its own file, step 1 of 2
Add a new IdleGC.{c,h} module. Move the RecentActivity type,
recent_activity variable and {get,set}RecentActivity wrappers.
-
1d0d3378
by Duncan Coutts at 2026-11-30T04:10:39-05:00
Move idle GC functionality to its own file, step 2 of 2
We can now fully encapsulate the recent_activity state, exposing just
three hooks, and one query used in the scheduler and timer tick.
This is a prelude to making changes to the implementation of tracking
when to perform an idle gc.
-
a691243d
by Duncan Coutts at 2026-11-30T04:10:39-05:00
Correct comments in idle GC code
The comments still referred to stopTimer/startTimer. These were
replaced recently by pauseTimer/unpauseTimer, but the comment was not
updated.
-
fb5fde91
by Duncan Coutts at 2026-11-30T04:10:39-05:00
Make signal handling be a responsibility of the I/O manager(s)
Previously it was scattered between I/O managers and the scheduler, and
especially the scheduler's deadlock detection.
Previously the scheduler would poll for pending signals each iteration
of the scheduler loop. The scheduler also had some hairy signal
functionality in the deadlock detection: in the non-threaded RTS (only)
if there were still no threads running after deadlock detection then it
would block waiting for signals.
But signals can and (in my opinion) should be thought of as just a funny
kind of I/O, and thus should be a responsibility of the I/O manager.
So now we have the I/O managers poll for signals when they are polling
for I/O completion (and removing the separate poll in the scheduler).
And when I/O managers block waiting for I/O then they now also start
signal handlers if they get interrupted by a signal. Crucially, if there
is no pending I/O or timers, the awaitCompletedTimeoutsOrIO will still
block waiting for signals.
This patch puts us into an intermediate state: it temporarily breaks
deadlock detection in the non-threaded RTS. The waiting on I/O currently
happens before deadlock detection. This means we'll now wait forever on
signals before doing deadlock detection. We need to move waiting after
deadlock detection. We'll do that in a later patch.
-
6737f45e
by Duncan Coutts at 2026-11-30T04:10:39-05:00
Clean up the RTS internal signal handling API
Now that the I/O manager is responsible for signals, we can simplify the
API we present for signal handling.
We now just need startPendingSignalHandlers, which is called from the
I/O managers. We can get rid of awaitUserSignals. We also don't need
RtsSignals.h to re-export the platform-specific posix/Signals.h or
win32/ConsoleHandler.h
We can also hide more of the implementation of signals. Less has to be
exposed in posix/Signals.h or win32/ConsoleHandler.h. Indeed,
posix/Signals.h becomes empty and we remove it. Partly this is because
we don't need inline functions (or macros) in the interface.
Also remove signal_handlers from RTS ABI exported symbols list. It does
not appear to have any users in the core libs, and its really an
internal implementation detail. It should not be exposed unless it's
really necessary.
-
bd9d3d53
by Duncan Coutts at 2026-11-30T04:10:40-05:00
Remove variable n_haskell_handlers which has become write-only
The previous commit removed the last read of this variable.
-
de8455fe
by Duncan Coutts at 2026-11-30T04:10:40-05:00
Narrow the window in which signals might be missed before poll/select
Any signals delivered just before poll/select block will be missed until
they are woken later by unrelated events. This arbitrarily delays the
delivery of signals.
This is not a complete solution. It is a cheap way to narrow but not
close the window. A full solution will have to come later. This issue
existed already, and is documented in issue #27540.
-
73381f34
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
b206520f
by Duncan Coutts at 2026-11-30T04:10:40-05: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
-
49a75a4c
by Duncan Coutts at 2026-11-30T04:10:40-05: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
-
cf8f2888
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
a1d2e786
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
61769cec
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
c4de27e0
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
b53a9113
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
7eb3b4bd
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
b32b1f2a
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
a1939765
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
90285b5c
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
3747864c
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
a65d0b02
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
46ae539f
by Duncan Coutts at 2026-11-30T04:10:40-05: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.
-
9f964bcf
by Duncan Coutts at 2026-11-30T04:10:41-05: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.
-
257f8e57
by Duncan Coutts at 2026-11-30T04:10:41-05:00
Add and use USED_IF_PREEMPTION to avoid warnings
-
5d077511
by Duncan Coutts at 2026-11-30T04:10:41-05: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.
-
7dc34c0f
by Duncan Coutts at 2026-11-30T04:10:41-05: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: test that performDeadlockDetection works
T26408e: make sure that we can detect a system deadlock with idle GC
disabled, after the idle GC timeout has elapsed.
T26408f: same as e but with manually invoked major GC
-
ed9cc1f5
by Duncan Coutts at 2026-11-30T04:10:41-05: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.
-
75d87e51
by Simon Peyton Jones at 2026-11-30T04:11:23-05:00
Make pushCast pure, and move it to Simplify.Utils
pushCast and pushCastMCo were in the SimplM monad, but no longer do
anything monadic. (Historically, pushing a coercion into an argument
used to simplify that argument; but now the coercion is recorded in
the sc_cast field of ApplyToVal.)
This patch makes them pure functions, and moves them, together with
addCastMCo, optOutCoercion and Note [The sc_cast field of ApplyToVal],
from GHC.Core.Opt.Simplify.Iteration to GHC.Core.Opt.Simplify.Utils,
alongside the SimplCont type they manipulate.
No change in behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
52207c2f
by Simon Peyton Jones at 2026-11-30T04:11:23-05: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 any IdInfo that isn't allowed in a lambda-binder, we now zap the
IdInfo in the join point:
let x = <> in b ==> join j x' = b in j <>
where x' is like x (definitely the same unique) but with zapped IdInfo.
See (SB3) in Note [StrictBind].
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
6c168645
by Simon Peyton Jones at 2026-11-30T04:11:23-05: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@anthropic.com>
-
7519ed3c
by Simon Peyton Jones at 2026-11-30T04:11:23-05: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@anthropic.com>
-
e274a92b
by Simon Peyton Jones at 2026-11-30T04:11:23-05:00
Add splitThunkCpr
This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form
of "thunk splitting" for strict bindings that have CPR information.
See Note [Thunk splitting] in WorkWrap.hs for the details.
It catches a previously-unrecognised optimisation opportunity
(see #28158) but it only helps in fairly obscure cases, so
I don't expect a big impact in practice.
As usually I did lots of refactoring along the way.
LLM disclosure: lots of interaction with Claude, but I wrote all the
code and comments.
-
309b7f0e
by sheaf at 2026-11-30T04:12:13-05:00
Make FunDepEqns a non-empty list
This avoids creating a 'FunDepEqns' with no equations. This means that
consumers dealing with [FunDepEqns] can reliably use "null fun_dep_eqns"
to decide whether there are any equations.
-
9bb95671
by sheaf at 2026-11-30T04:12:14-05:00
tryFamEqFunDeps: (CF1) only for closed tyfams
This commit makes (CF1) in Note [Exploiting closed type families] only
apply to *closed* type families, not *open* type families.
This allows the program reported in #28082 to continue to be accepted,
fixing a regression.
Fixes #28082
-
51e14298
by Sylvain Henry at 2026-11-30T04:13:04-05:00
x86-64 NCG: check that address displacements fit in 32 bits (#28105)
Three clauses of getAmode put a constant in the displacement of an
address without a valid check that it fits in a signed 32-bit integer,
so the assembler rejected the module:
- x + ((y << shift) + offset): the guard checked the offset only for
shift 3, because && binds tighter than ||.
- CmmRegOff x offset + (y << shift): no check.
- x - lit: the guard checked lit, but the displacement is -lit, which
does not fit for lit = -2^31.
Each clause now checks the constant that goes in the displacement and
narrows it to the target word width, as litToImm does: the Integer of
a CmmInt can be out of the range of its width, and truncation with the
host Int is wrong for a 64-bit host that compiles for a 32-bit target.
When the constant does not fit, the clause does not match and a later
clause computes it in a register.
See Note [Displacements fit in 32 bits].
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
8aca9c73
by David Eichmann at 2026-11-30T04:13:46-05:00
testsuite: fix framework failure on window for tests using all_available_io_managers_except()
-
2858a265
by David Eichmann at 2026-11-30T04:13:46-05:00
testsuite: use `all_available_io_managers` for various tests
Affected tests:
* T10590
* T21969
* T21969a
* T21969b
* T21969c
* T21969d
* T21969e
* T21969f
-
ef652c33
by Sylvain Henry at 2026-11-30T04:14:36-05:00
testsuite: Do not pass $(WAY_FLAGS) to GHCi in Makefile tests (#28166)
Since 543c108e6a9 the driver sets WAY_FLAGS for Makefile tests. Some
GHCi tests passed $(WAY_FLAGS) to ghc --interactive, where it was empty
before. In the optasm and optllvm ways it now contains -O, and the
byte-code backend ignores -O with a -Winconsistent-flags warning. This
warning made the tests fail.
Pass $(WAY_FLAGS) to the compilation steps only. GHCi reuses the object
files that these steps make with -O, thus the tests stay useful in the
optimised ways.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
56abdcf4
by Alan Zimmerman at 2026-11-30T04:15:17-05:00
EPA: Introduce LayoutFrame stacks in ExactPrint state
The exact print process keeps the current layout offset in its state,
for use in printing and updating for makeDelta.
Update it to use a stack rather than a single value, so it properly
handles nested layout, in particular when the layout is introduced but
the printing is empty.
Also simplify the exact print repl test runner to use a relative path
to the GHC libdir.
-
385430d5
by Simon Peyton Jones at 2026-11-30T10:17:16+00:00
Add GHC.Utils.Misc.mapConst
Add `mapConst :: a -> [b] -> [a]`, and use it for many of the
occurrences of (map (const x) xs).
No change in behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
bdeb9f1e
by Simon Peyton Jones at 2026-11-30T12:06:24+00:00
Align data-con strictness with worker value args (#28186)
Some of a data constructor's existential type variables can be
coercion variables (Note [Existential coercion variables]), and they
are /value/ arguments of the worker. But `dcStricts` covered only
`dataConRepArgTys`, so anywhere we zipped the value arguments of a
worker with its strictness marks, the zip was mis-aligned if there was
a CoVar. This patch fixes that, and tidies up along the way.
* GHC.Core.DataCon
- `dcStricts` now always lines up 1-1 with `dataConRepArgTys`
(it used to be [] for an all-lazy constructor).
- New field `dcArgCbvInfos :: [ArgCbvInfo]`, one per /value/ argument of
the worker, /including/ existential CoVars:
data ArgCbvInfo = ArgCbv | ArgCbn | ArgRepPoly
ArgCbv means "certainly evaluated" (a bang, or an unlifted type).
See Note [ArgCbvInfo], which explains why consumers treat ArgRepPoly
conservatively, but in opposite directions.
See also (EXCO1) in Note [Existential coercion variables].
- New field `dcIsLazy` (accessor `dataConRepIsLazy`): all arguments
are ArgCbn. This replaces `isLazyDataConRep`, which said only that
there were no bangs.
* exprIsHNF, exprOkForSpeculation (app_ok) and SpecConstr now use
`dataConRepArgCbvInfos`, so they line up with the worker's value args.
* The worker's demand signature (GHC.Types.Id.Make.mkDataConWorkId) now
has a lazy demand for each existential CoVar too, so that its length
is the worker's arity. It is still bang-only: demand analysis cares
about bangs, not about liftedness. A lazy field of unlifted type is
evaluated before the call, not by the constructor, so adding a seqDmd
for it would make an absent field look used (e.g. T25177).
* dmdTransformDataConSig now takes the worker's DmdSig, rather than a
list of StrictnessMarks, and finds the strict fields from that, using
the new `GHC.Types.Demand.isStrDataConDmd`.
* Similarly, adjustFieldsIdInfo (which marks pattern-bound variables of
strict fields as evaluated) and mkDupableAlt in the Simplifier take
their strict fields from the worker's DmdSig, which is aligned with
the case-alternative binders. (Marking an /unlifted/ field as
evaluated would gain nothing, and its OtherCon[] unfolding makes
`interestingArg` say NonTrivArg, which changes inlining; that made
bytestring's $wcompareBytes inline, and T19695 allocate 2.5% more.)
The Simplifier's fast path for data constructors with no bangs (Note
[Fast path for lazy data constructors]) is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
1d8b341d
by Simon Peyton Jones at 2026-11-30T12:06:24+00:00
Unary classes: (MkC e) is ok-for-speculation only if e is (#28183)
For a unary class C, (MkC e) is represented by `e` alone; the MkC
disappears in CorePrep. So (MkC e) is a value, or ok-for-speculation,
only if `e` is. exprIsHNF had a special case for this, but app_ok did
not, and so claimed that (MkC (error "boom")) was ok-for-speculation.
Now app_ok has the same special case.
We do /not/ achieve this by giving MkC a strict field: that leaks into
DmdAnal, StrictArg and the field seqs of Note [Strict fields in Core],
and made T5321FD allocate 10% more. See (UCM3b), a new wrinkle in Note
[Unary class magic].
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
285ad773
by Simon Peyton Jones at 2026-11-30T12:06:24+00:00
Simplifier: treat unlifted data-con fields as strict (#28169)
The Simplifier's fast path for "lazy" data constructors (no bangs) also
caught constructors with /unlifted/ fields, such as I# or (#,#). So
I# (case x of (a,b) -> a#)
did not get the StrictArg treatment, and the case was not floated out
to give (case x of (a,b) -> I# a#). This patch fixes that, and makes
`rebuildCall` cheaper along the way.
* Data constructors: see Note [Simplifying data constructor applications]
- (SDC1) A completely lazy constructor (`dataConRepIsLazy`: all fields
lifted and none banged) still zooms straight to `rebuild`.
- (SDC2) Any other constructor goes straight to `rebuildCall`, skipping
simplOutId, with a new, much smaller, form of ArgInfo:
SimpleArgInfo { ai_fun_id :: OutId, ai_app :: OutExpr
, ai_arg_cbvs :: [ArgCbvInfo] }
which has its own, much simpler, equation in `rebuildCall`. It needs
no rules, discounts, bottoming check or ArgSpec list.
- (SDC3) An unsaturated worker application is a value, so all its
arguments are treated as lazy. We use the new, non-allocating,
`saturatedCont`, which also replaces `countValArgs` in `mkArgInfo`.
* Simple functions: see Note [Simple functions]. A function with no
rules, no unfolding and a nop demand signature (e.g. any imported
function at -O0, or a lambda-bound function) also uses SimpleArgInfo,
with its argument strictness taken from its type: only unlifted
arguments are strict. So do data-con wrappers that are not inlined
(i.e. before FinalPhase); see `mkArgInfo`.
* A SimpleArgInfo always uses Plan B (a join point) in Note [Duplicating
StrictArg]. This replaces the `isDataConId` test in
mkDupableContWithDmds; see (DJ4) in Note [Duplicating join points],
which now has an example.
* Making rebuildCall cheaper (it handles every function application, so
this benefits all programs):
- The general case of `rebuildCall` takes the ArgInfo apart once and
loops over the pieces that change, rather than allocating a fresh
ArgInfo for every argument.
- `ai_dmds` is now a `DmdType` rather than an infinite list of demands;
use the new `GHC.Types.Demand.splitArgDmd`. So we never build
(demands ++ repeat topDmd).
- `simplArg` no longer takes a `Maybe ArgInfo`; the one caller that
wanted an informative Stop continuation (rebuildCall) does it itself.
- The CallCtxt and SubDemand fields of `Stop` are strict.
- Rename `ai_fun` to `ai_fun_id`.
Local measurements of compile-time allocation, relative to master (not
perfectly like-for-like): T19695 -0.9%, T15164 -0.8%, T5321FD and T9020
within +1%, T9961 about 0%. Before the improvements to rebuildCall,
treating unlifted fields as strict cost T5321FD +10.5%, T9961 +4.7%,
T9020 +2.4%, T15164 +2.4% (CI).
Test: simplCore/should_compile/T28169
T16122 and T16402 now show the case floated out of the I64#/W64# box,
as intended; accept the new output.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
4d39e768
by Simon Peyton Jones at 2026-11-30T12:06:24+00:00
Add INLINE pragmas to tiny MCoercion functions
Now that interestingArg returns TrivArg for an OtherCon [] argument,
mkSymMCo (and friends) no longer inline in the type-family rewriter,
where their argument is evaluated but its constructor is unknown.
That cost ~2.5% allocation in T9872{a,b,c,d} and TcPlugin_RewritePerf:
mkSymMCo went from 0 to 1.9M out-of-line calls in T9872b, and the
MRefl fast path in GHC.Tc.Solver.Rewrite was lost.
The benefit of inlining comes from downstream consumers of the result,
which neither the argument nor the call context reveals, so we use
INLINE pragmas instead. See the new
Note [Inline tiny MCo functions] in GHC.Core.TyCo.Make.
Also add a paragraph to (IA2) in Note [Interesting arguments] explaining
the trade-off, and pointing to the new Note.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
543c67d3
by Simon Peyton Jones at 2026-11-30T16:24:12+00:00
Fix evaluated-ness bug in Simplifier (#26548)
`adjustFieldsIdInfo` decided whether to attach evaluated-ness to the
pattern-bound variables of a case alternative by testing whether the
data constructor has a wrapper (`dataConWrapId_maybe`). But a
constructor can have strict fields and yet no wrapper, so we failed to
mark its strict fields as evaluated. Main change:
* Drive `addFieldsIdInfo` from the strictness signature its worker.
Fixing this gives many more variables an OtherCon [] unfolding, which
disturbs the inlining heuristics. So also:
* `interestingArg` returns TrivArg (rather than NonTrivArg) for an
argument with an OtherCon [] unfolding: knowing only that an argument
is evaluated rarely makes inlining worthwhile (e.g. maMB in T18140).
See (IA2) in Note [Interesting arguments].
* `interestingCallContext` treats a StrictBind continuation as
RhsCtxt NonRecursive rather than BoringCtxt.
* A lambda argument remains a `ValueArg`; new (IA5) in
Note [Interesting arguments] explains why, and discusses T17516.
* In some benchmarks (notably T9233) `addFieldsIdInfo` seems to be quite a hot
path, so I optimised it a bit:
(a) build the result list strictly; it is consumed in full right away
(b) update each field binder's IdInfo at most once, rather than once
for evaluated-ness and once more for occ-info
(c) leave alone a field binder that is dead and will stay dead
I factored out `fieldOccInfoStable`; and make the `seq#` case simpler too.
T17516 allocates about 1% more at compile time. Because of (IA2), `max`
on positions (called on merely-evaluated arguments) no longer inlines into
the parser combinators of T17516A; so they stay small and inline more into
T17516. T17516A gets cheaper to compile and T17516 dearer.
Metric Increase:
T17516
New test T26548. T26615.stderr is regenerated (only its fEqList lines
are checked).
T28158.stderr: because of (IA2), one `reverse xs` (with xs evaluated)
no longer inlines.
Authored with help from Claude.
-
2377997e
by Simon Peyton Jones at 2026-11-30T17:23:20+00:00
Do not unconditionally inline data-constructor join points (#28229)
(DJ3)(c) of Note [Duplicating join points] made `uncondInlineJoin` return
True for a join point whose RHS is a data constructor applied to its own
binders, such as
join $j a = K a
That is harmful, now that unlifted fields get the StrictArg treatment
(#28169). Consider (test T28229b)
tsignum !j = S (case j of { S i -> ...; P _ -> 1#; N _ -> -1# })
Plan B of Note [Duplicating StrictArg] makes (join $j a = S a), and (DJ3)(c)
then duplicated S into every branch. A client doing
case tsignum c of x -> ...x...
then did case-of-case and made a join point abstracting over the boxed `x`,
so it lost the known constructor and allocated S boxes. (We saw this as a
20% allocation increase in nofib's digits-of-e1, via integerSignum, although
the (IA2) change of #26548 now happens to avoid it there.)
* `uncondInlineJoin` now inlines only a trivial RHS, or an indirection to
another join point. This is simpler too: it no longer needs the binders.
* (DJ3)(c) was introduced for #25723, where
case f x of (a,b) -> jump $j a b where $j a b = (a,b)
is an identity case in disguise. Now `mkCase1` looks through a saturated
jump to a join point whose unfolding is a constructor application: see
(EIC4) in Note [Eliminate Identity Case]. To support this, `mkCase` and
`mkCase1` take an InScopeSet. T25723 is unaffected.
Tests: simplCore/should_compile/T28229a, T28229b
T24229a and T24229b now keep (join $j ww1 = Just ww1), rather than
duplicating the Just; accept the new output.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>