[Git][ghc/ghc] Pushed new branch wip/supersven/fix-aarch64-mul2u-clobber
by Sven Tennie (@supersven) 29 Nov '26
by Sven Tennie (@supersven) 29 Nov '26
29 Nov '26
Sven Tennie pushed new branch wip/supersven/fix-aarch64-mul2u-clobber at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/supersven/fix-aarch64-mul2u-c…
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] 39 commits: Move idle GC tracking to its own file, step 1 of 2
by Marge Bot (@marge-bot) 29 Nov '26
by Marge Bot (@marge-bot) 29 Nov '26
29 Nov '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
b3c73baa by Duncan Coutts at 2026-11-29T06:59:28-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.
- - - - -
fcdeef8e by Duncan Coutts at 2026-11-29T06:59:28-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.
- - - - -
ae824de1 by Duncan Coutts at 2026-11-29T06:59:28-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.
- - - - -
704ae4e1 by Duncan Coutts at 2026-11-29T06:59:28-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.
- - - - -
fd281390 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
eff2020e by Duncan Coutts at 2026-11-29T06:59:29-05:00
Remove variable n_haskell_handlers which has become write-only
The previous commit removed the last read of this variable.
- - - - -
fb938818 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
bce2c8a3 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
7895de69 by Duncan Coutts at 2026-11-29T06:59:29-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
- - - - -
3d72774a by Duncan Coutts at 2026-11-29T06:59:29-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
- - - - -
a30c4034 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
845b58a2 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
81f9209d by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
bb5e018b by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
8ad91450 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
448f0079 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
a1d267e6 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
7e989bfa by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
80dbc6c7 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
c4ecb59e by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
7763414c by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
80a3a13b by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
c171d650 by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
a66110b3 by Duncan Coutts at 2026-11-29T06:59:29-05:00
Add and use USED_IF_PREEMPTION to avoid warnings
- - - - -
912fe99e by Duncan Coutts at 2026-11-29T06:59:29-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.
- - - - -
9024800b by Duncan Coutts at 2026-11-29T06:59:30-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
- - - - -
9c864048 by Duncan Coutts at 2026-11-29T06:59:30-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.
- - - - -
0946333d by Simon Peyton Jones at 2026-11-29T06:59:31-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(a)anthropic.com>
- - - - -
c257e4f4 by Simon Peyton Jones at 2026-11-29T06:59:31-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(a)anthropic.com>
- - - - -
cca3e1f7 by Simon Peyton Jones at 2026-11-29T06:59:31-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(a)anthropic.com>
- - - - -
4fcb7cf5 by Simon Peyton Jones at 2026-11-29T06:59:31-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(a)anthropic.com>
- - - - -
a8a2afca by Simon Peyton Jones at 2026-11-29T06:59:31-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.
- - - - -
de30172f by sheaf at 2026-11-29T06:59:38-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.
- - - - -
8328859c by sheaf at 2026-11-29T06:59:38-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
- - - - -
18181fe2 by Sylvain Henry at 2026-11-29T06:59:44-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(a)anthropic.com>
- - - - -
def94739 by David Eichmann at 2026-11-29T06:59:45-05:00
testsuite: fix framework failure on window for tests using all_available_io_managers_except()
- - - - -
b06b0f35 by David Eichmann at 2026-11-29T06:59:45-05:00
testsuite: use `all_available_io_managers` for various tests
Affected tests:
* T10590
* T21969
* T21969a
* T21969b
* T21969c
* T21969d
* T21969e
* T21969f
- - - - -
dc1cf818 by Sylvain Henry at 2026-11-29T06:59:51-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(a)anthropic.com>
- - - - -
baf64129 by Alan Zimmerman at 2026-11-29T06:59:52-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.
- - - - -
109 changed files:
- + changelog.d/28105
- + changelog.d/T27962
- + changelog.d/T27963
- + changelog.d/T28082
- + changelog.d/idle-gc-and-deadlock-detection
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/Core.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Make/Box.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/Expr.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Tc/Instance/FunDeps.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Id.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Utils/Monad.hs
- 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/Capability.c
- rts/IOManager.c
- rts/IOManager.h
- + rts/IdleGC.c
- + rts/IdleGC.h
- rts/Linker.c
- rts/RtsFlags.c
- rts/RtsSignals.h
- rts/RtsStartup.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/js/environment.js
- 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/Signals.h
- rts/posix/Timeout.c
- rts/posix/Timeout.h
- rts/rts.cabal
- rts/win32/AsyncMIO.c
- rts/win32/AsyncMIO.h
- rts/win32/AsyncWinIO.c
- rts/win32/AsyncWinIO.h
- rts/win32/AwaitEvent.c
- rts/win32/ConsoleHandler.c
- rts/win32/ConsoleHandler.h
- testsuite/driver/testutil.py
- + testsuite/tests/codeGen/should_compile/T28105.cmm
- + testsuite/tests/codeGen/should_compile/T28105b.hs
- testsuite/tests/codeGen/should_compile/all.T
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/ghci/prog-mhu005/Makefile
- testsuite/tests/ghci/prog-mhu006/Makefile
- testsuite/tests/ghci/prog-mhu007/Makefile
- testsuite/tests/ghci/prog020/Makefile
- testsuite/tests/ghci/prog022/Makefile
- testsuite/tests/ghci/prog025/Makefile
- + testsuite/tests/indexed-types/should_compile/T28082.hs
- testsuite/tests/indexed-types/should_compile/all.T
- 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/T26408e.hs
- + testsuite/tests/rts/T26408e.stderr
- + testsuite/tests/rts/T26408f.hs
- + testsuite/tests/rts/T26408f.stderr
- testsuite/tests/rts/all.T
- testsuite/tests/rts/symbols/rts-check-symbols.stdout
- 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/T27965b.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/dd3d2d34a6d6e56589eedfc76cc480…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/dd3d2d34a6d6e56589eedfc76cc480…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/romes/global-break-action] 24 commits: CoreMap: look up a non-recursive let with the key order of the store
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
29 Nov '26
Rodrigo Mesquita pushed to branch wip/romes/global-break-action at Glasgow Haskell Compiler / GHC
Commits:
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
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
- - - - -
01a5b0ac by Sylvain Henry at 2026-11-22T16:35:34-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>
- - - - -
e4498112 by Andreas Klebinger at 2026-11-22T16:35:34-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>
- - - - -
f59fb957 by Sylvain Henry at 2026-11-22T16:35:34-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>
- - - - -
2091b89a by fendor at 2026-11-22T16:36:17-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
- - - - -
cfd4fb67 by Ryan Scott at 2026-11-22T16:36:59-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.
- - - - -
06e71ddf by Simon Peyton Jones at 2026-11-22T16:37:40-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)
- - - - -
cd6c2a96 by Simon Jakobi at 2026-11-22T16:38:23-05:00
Cmm: drop eliminated blocks from the graph in CBE
Previously, common block elimination only made the eliminated blocks
unreachable. They stayed in the graph until stack layout discarded
them.
Removing these blocks right away reduces the potential for confusion
(e.g. #27368). It does not appear to make any significant difference
to compiler allocations.
Assisted-by: Claude Opus 5.5
- - - - -
c0764c69 by Hannes Siebenhandl at 2026-11-22T16:39:04-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`.
- - - - -
242f8daf by Alan Zimmerman at 2026-11-22T16:39:46-05:00
EPA: Use AnnList in DecBrl
Via updating the TTG extension point payload
- - - - -
1e568190 by David Eichmann at 2026-11-22T16:40:28-05:00
Fix race condition in IOManager test
- - - - -
64f821c6 by Simon Peyton Jones at 2026-11-22T16:41:09-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.
- - - - -
ed5124b3 by mangoiv at 2026-11-22T16:41:50-05:00
ci: nightly push can run on any arch
- - - - -
1340d255 by ARATA Mizuki at 2026-11-23T20:13:03-05:00
rts: Fix unwinding information for StgRun
The unwinding rule for rsp updated in a5ec467ee3d4e77c026437a545981269acde3434
was wrong. It gave the value of rsp _after_ the call instruction (i.e.
on entry to StgRun), whereas it should give the value _before_ the call
instruction (i.e. the caller's rsp).
Fixes #27637
- - - - -
56bb91d9 by Alan Zimmerman at 2026-11-23T20:13:44-05:00
EPA: Replace AnnListLayout / AnnListBrackets with EpLayout
We have harmonised the use of `AnnListLayout` and `AnnListBrackets` to
be equivalent to `EpLayout`.
We now take the final step, and remove them completely in favour of
`EpLayout`.
The change looks bigger than it is, because a lot of golden test
output gets updated.
- - - - -
2c614766 by Rodrigo Mesquita at 2026-11-26T11:13:26+00:00
test: make T3171 not fragile and add version for ext interp too
- actually test the sleep of the user-given expression gets interrupted
- the ext interp version tests two things:
- Requests can be cancelled without terminating the ext interp (#18852)
- The stmt being evaluated gets interrupted in the ext interp (that
is, ^C gets sent to the thread running the user-given expression
and doesn't affect the ext interp main thread)
- testing ext interp requires sending ^C to whole process group
Fixes #15383
- - - - -
a94df054 by Rodrigo Mesquita at 2026-11-29T10:18:45+00:00
Global break action which uses a per-thread context map
Previously, everytime an expression was run in the interpreter (`sandboxIO`):
1) the RTS global variable `rts_breakpoint_io_action`, which is run
anytime any thread hits a breakpoint, got set to a new action that:
a) Wrote the breakpoint hit by the thread to the `statusMVar`
b) Blocked waiting on a newly created MVar `breakMVar` for a `resumeStmt` to
signal it.
2) Start the expression evaluation on a new "sandbox" thread
3) Block waiting on `statusMVar` for a breakpoint to be hit, and we'd
return the read `EvalBreak`
4) Set the `rts_breakpoint_io_action` to a no-op which prints "Ignored breakpoint..."
At some later point, we could `resumeStmt` with the `EvalBreak` context
by signaling the `breakMVar` on which the thread that hit the breakpoint
is blocked.
However, if you consider an expression which forks off threads which hit
breakpoints, surprising things may happen:
main = do
-- the `worker` code has a breakpoint
mapM (forkIO . worker) [1..10]
forever $ threadDelay 10000000
Interpreting this program, we'll do (1,2,3), and all workers will hit
their breakpoint and run `rts_breakpoint_io_action`. Here's a first
issue:
1. The first worker succeeds in `putMVar statusMVar`
2. The interpreter will read `takeMVar statusMVar` (3) and then (4)
3. The remaining workers are hitting the breakpoint concurrently:
- Some may block trying to `putMVar statusMVar`
- Some may run the no-op action which discards the breakpoint
Depending on whether the remaining workers hit the breakpoint or (4)
happens first, some workers will skip their breakpoint.
Now, let's pretend all workers can block on `putMVar statusMVar`. Since
the interpreter will take the breakpoints one by one, and resume them
one by one, it seemingly works. However, that's only fine when we assume
only one expression is evaluated at once. As soon as multiple
expressions can be evaluated at once (a desireable property of a
debugger, as well as something that can already happen today in some
scenarios (see `break049`)), it becomes madness:
The second issue comes the global break action being swapped by a second
evaluation and threads from the first evaluation running the "wrong" action.
Consider:
1. eval `expr_A` installs a break action that puts on `statusMVar_A`
2. `expr_A` forks off a few threads, they're running in the background
3. eval `expr_B` sets the break action to put on `statusMVar_B`
4. the `expr_A` forked threads hit a breakpoint and put `statusMVar_B`
5. `expr_B` returns with a breakpoint of `expr_A`, `resume expr_B` would
resume `expr_A`, etc...
A third issue with having a single MVar for all threads of an execution
is that there is no way to have fine-grained control over which threads
are resumed and which are stopped. This is often necessary to debug
multi-threaded programs too.
Therefore, it is imperative that the global break action does not
capture a global single MVar when many expressions with many
corresponding threads can be running in the interpreter/debugger at
once, if we want to support debugging multi-threaded programs at all.
---
This commit fixes these foundational issues by making the global break
action truly global (i.e. never modified and never capturing any locals).
The global break action is installed once in `sandboxIO` and never
removed (`withBreakAciton` and `noBreakAction` were killed). Subsequent
runs of `sandboxIO` re-rewrite the same break action (a no-op).
When any thread hits the global break action, it looks its `ThreadId` up
in the global per-thread context mapping, returning a `ResumeContext`
which contains that thread's `breakMVar` (now `resumeBreakVar`) and
`statusMVar` (now `resumeEvalStatus`). Each thread blocks on its own
MVar and replies on its own TVar. There is no longer one global status
nor break MVar.
To resume a thread by its `ThreadId`, we can simply fetch its
`ResumeContext` and signal the corresponding `resumeBreakMVar`
To wait for a result or for a breakpoint in a specific thread, we do
`readThreadEvalStatus`. To wait for any breakpoint hit in any thread at
all, we have `readAnyThreadEvalBreak`.
Some evaluations will only care to look at their own result and breaks
(so they run with `readAllBreaks` `= False`); and the main thread of an
evaluation should not be read by other evaluations. In short, only
threads forked off by the main thread of evaluations get read with
`readAnyThreadEvalBreak`. If two evaluations fork off threads in the
background, `readAnyThreadEvalBreak` may return threads from any of
them. There is no just way to distinguish their "parents" at runtime.
For instance, `compileParsedExprRemote` should run an expression until
completion without any existing threads interfering with its execution,
so it runs with `readAllBreaks = False`. Otherwise, by default, running
`main` on the REPL, we'll want to stop at any break any forked thread
hits, just like we did before.
P.S. Currently, we need to keep track of the "main expression thread"
being currently evaluated to fetch its result, but, when `evalStmt`
becomes asynchronous by returning the `ThreadId` of the "sandbox"
thread, the whole `evaluationMainThreadGlobalVar` hack can be deleted.
---
New tests observing behavior that we don't want to break (which I broke
at some point while developing this patch):
- break032: we don't stop at breakpoints in TH
- break033: :continue after -fbreak-on-exception doesn't hit exception breakpoint
- break034: test :abandon doesn't hang with -fbreak-on-error
- conc033: also run with the external interpreter
- ForceInterrupt(Ext): ^C during :force interrupts the forced expression
- break043: :continue of a forked thread reads main thread breaks/results too
- break046: evaluating expr while stopped doesn't change what :continue resumes
- break048: evaluating expr while forked thread is stopped doesn't hit again current breakpoint
New tests that failed before this commit:
- T3171(ext)nosandbox: T3171 with -fno-ghci-sandbox (T3171extnosandbox still fails)
- break050(ext): ^C during :continue of a forked thread interrupts that thread
Fixed ext-interp bc. resumeStmt now does unsafeUnmask, just like
sandboxIO, so the UserInterrupt reaches the resume.
- break049: breakpoints in forked threads don't get mixed up with other evaluations
This test demonstrates one way multi-threaded debugging can go wrong
bc the global break action used to capture a break MVar for a
specific thread that is shared by all threads (described above as
"the second issue"). Here is the annotated execution of the test
*before this commit*:
```haskell
ghci> main
Stopped in Main.inMain, break049.hs:30:12-18
_result :: IO () = _
[break049.hs:30:12-18] ghci> :force slow
-- ANN: the breakpoint we're ignoring on :force is the worker's
-- breakpoint, and it's just discarded
*** Ignoring breakpoint [break049.hs:27:14-20]
slow = 5
[break049.hs:30:12-18] ghci> :cmd return ""
-- ANN: we :continue `main`, but the worker should still be blocked
-- so `main` should block.
[break049.hs:30:12-18] ghci> :continue
-- ANN: however, it completes; recall the worker break was ignored
-- instead of stopping there
main done
-- ANN: after this commit, the worker break wouldn't have been read
-- by `:force`, and we'd see it when resuming `:main`, and
-- `:continue` here would resume the worker and only then main would
-- complete.
ghci> :continue
-- ANN: bc this is ghci before the commit, we see:
not stopped at a breakpoint
ghci>
```
- break042: main forks workers and all workers hit a breakpoint
This test witnesses "the first issue" described above, where the
workers hit breaks after the global break action was already removed
and so are lost.
Fixes #28124
- - - - -
04b20eca by Rodrigo Mesquita at 2026-11-29T10:18:45+00:00
ci: unset CI_COMMIT_MESSAGE to avoid Windows environment length limits
The previous commit consistently made the Windows runner fail with:
> find: The environment is too large for exec().
GitLab sets these environment variables by default, but we never read
them. Just unset them at the start.
- - - - -
207 changed files:
- .gitlab-ci.yml
- .gitlab/ci.sh
- + changelog.d/27694
- + changelog.d/27892
- + changelog.d/28124
- + changelog.d/T27137
- + changelog.d/T27637
- + changelog.d/T27862
- + changelog.d/T28123
- + changelog.d/T28135
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-link-nodes
- + changelog.d/make-depends-streaming-output
- compiler/GHC/Cmm/CommonBlockElim.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/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Driver/Config.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Hs/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/Quote.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/TyCl.hs
- + distrib/configure.ac
- docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/separate_compilation.rst
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Run.hs
- + libraries/ghci/GHCi/Run/Breakpoints.hs
- libraries/ghci/ghci.cabal.in
- rts/Interpreter.c
- rts/StgCRun.c
- testsuite/driver/my_typing.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- 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/concurrent/should_run/all.T
- + 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/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_mhu01.dep-json → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-makefile → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
- + testsuite/tests/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/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghci.debugger/scripts/Makefile
- testsuite/tests/ghci.debugger/scripts/T14690.stdout
- testsuite/tests/ghci.debugger/scripts/all.T
- testsuite/tests/ghci.debugger/scripts/break024.stdout
- + testsuite/tests/ghci.debugger/scripts/break032.hs
- + testsuite/tests/ghci.debugger/scripts/break032.script
- + testsuite/tests/ghci.debugger/scripts/break032.stdout
- + testsuite/tests/ghci.debugger/scripts/break033.hs
- + testsuite/tests/ghci.debugger/scripts/break033.script
- + testsuite/tests/ghci.debugger/scripts/break033.stdout
- + testsuite/tests/ghci.debugger/scripts/break034.hs
- + testsuite/tests/ghci.debugger/scripts/break034.script
- + testsuite/tests/ghci.debugger/scripts/break034.stdout
- + testsuite/tests/ghci.debugger/scripts/break042.hs
- + testsuite/tests/ghci.debugger/scripts/break042.script
- + testsuite/tests/ghci.debugger/scripts/break042.stderr
- + testsuite/tests/ghci.debugger/scripts/break042.stdout
- + testsuite/tests/ghci.debugger/scripts/break043.hs
- + testsuite/tests/ghci.debugger/scripts/break043.script
- + testsuite/tests/ghci.debugger/scripts/break043.stdout
- + testsuite/tests/ghci.debugger/scripts/break046.hs
- + testsuite/tests/ghci.debugger/scripts/break046.script
- + testsuite/tests/ghci.debugger/scripts/break046.stdout
- + testsuite/tests/ghci.debugger/scripts/break048.hs
- + testsuite/tests/ghci.debugger/scripts/break048.script
- + testsuite/tests/ghci.debugger/scripts/break048.stdout
- + testsuite/tests/ghci.debugger/scripts/break049.hs
- + testsuite/tests/ghci.debugger/scripts/break049.script
- + testsuite/tests/ghci.debugger/scripts/break049.stdout
- + testsuite/tests/ghci.debugger/scripts/break050.hs
- + testsuite/tests/ghci.debugger/scripts/break050.script
- + testsuite/tests/ghci.debugger/scripts/break050.stdout
- + testsuite/tests/ghci.debugger/scripts/break050ext.stdout
- + testsuite/tests/ghci/should_run/ForceInterrupt.script
- + testsuite/tests/ghci/should_run/ForceInterrupt.stdout
- + testsuite/tests/ghci/should_run/ForceInterruptExt.stdout
- testsuite/tests/ghci/should_run/Makefile
- testsuite/tests/ghci/should_run/T3171.stdout
- + testsuite/tests/ghci/should_run/T3171ext.stdout
- + testsuite/tests/ghci/should_run/T3171extnosandbox.stdout
- + testsuite/tests/ghci/should_run/T3171nosandbox.stdout
- testsuite/tests/ghci/should_run/all.T
- 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/module/mod185.stderr
- 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/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/T20846.stderr
- testsuite/tests/pmcheck/should_compile/T24234.stderr
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- testsuite/tests/printer/T18791.stderr
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/rts/IOManager.hsc
- testsuite/tests/rts/all.T
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/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/tcfail203a.stderr
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/b2ab554e384c7ea7112d96ea38aa17…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/b2ab554e384c7ea7112d96ea38aa17…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/romes/global-break-action] 33 commits: Asynchronous RPC with external interpreter
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
29 Nov '26
Rodrigo Mesquita pushed to branch wip/romes/global-break-action at Glasgow Haskell Compiler / GHC
Commits:
b63a56c8 by Rodrigo Mesquita at 2026-11-15T14:49:28+01:00
Asynchronous RPC with external interpreter
There's a single pipe to connect the host compiler to the external
interpreter. On this pipe, we have historically done synchronous
request/reply communication to invoke methods on the external
interpreter.
However, with the advent of multi-threaded debugging, it has become
necessary to do asynchronous calls on the external interpreter, where we
may block on the host waiting for a reply, but the external interpreter
should handle the request asynchronously and reply when ready. For
instance, we want to start the evaluation of the debuggee but not block
the interpreter waiting for it to finish or hit a breakpoint. Or e.g. we
want to resume two threads of the debuggee simulatenously instead of
blocking waiting for the resume result of each one sequentially.
And it turns out, we were already doing some ad-hoc asynchronous
communication to evaluate Template Haskell on the external interpreter.
It used to go as an ad-hoc "send request without expecting reply",
followed by handling on the host a set of 'THMessage's sent by the
interpreter, followed by "expect a response to arrive now". It worked
because there was still a fixed order of messages, but it fits an async
model in a non-ad-hoc way.
Asynchronous communication that unblocks the external interpreter main
thread will also make it possible to resolve issues such as #18852
(exceptions leaving the external interpreter in an unrecoverrable state)
The new design
--------------
The new invariant: every single request should receive a matching reply.
The pipe is bidirectional (the ext. interpreter can receive requests,
but it can also send requests for TH evaluation; the host can send
requests, but it can also receive TH requests from the interpreter).
When a request is sent in whichever direction, it always contains a
correlation-id header. The Sender places an empty MVar on a
pending-reply map keyed by id and waits on it for a response.
See 'remoteCall' and 'remoteTHCall'.
The pipe is associated to a thread which drains the read end. Because
it's bidirectional, two things may be read off the pipe:
- A Reply, with a correlation-id header, which we match against the
pending requests map to unblock the corresponding pending-reply MVar
- A Request, which is queued to the pending-request queue.
To handle a message, we take a Request from the pending-request queue
and run a handler that produces a Reply. Currently, the handler is run
synchronously in the thread, but it is trivial to make the handler run
in a forked thread for certain ("interruptible") messages in an upcoming
patch (when it is necessary for the multi-threaded debugger).
See 'handleRemoteCall' and 'handleRemoteTHCall'.
The old interp lock now just protect the pipe writing (reads don't lock
bc they are done exclusively by drainPipe), it doesn't need nor should
lock the full remote procedure call.
Fixes #27960
- - - - -
c02b05c5 by Rodrigo Mesquita at 2026-11-15T14:49:28+01:00
interp: Add separate mailboxes for TH async RPC
When the host sends a `RunTH` command to the interpreter, it expects a
few "reverse requests" from the interpreter (e.g. `NewName`) which must
be run in the same context that initiated the `RunTH`.
When the host is evaluating many splices at once, it will send many
`RunTH` commands to the interpreter and start listening for reverse
requests in the meantime. However, a received request previously had no
way to be associated to the scope of a particular `RunTH` invocation, so
the reverse commands could get replied to from incorrect contexts, or
e.g. a `RunTHDone` from the interp. could terminate early the wrong
`RunTH` computation.
In this commit we add independent mailboxes to the interpreter
asynchronous RPC infrastructure, allowing a RunTH to announce a
particular `InboxId` that all reverse requests for that RunTH should
use. On the host, we create that mailbox id and have
`handleRemoteTHCall` listen on that specific mailbox rather than for
requests without a specific mailbox address.
- - - - -
2bce180f by Rodrigo Mesquita at 2026-11-15T14:49:28+01:00
refactor: Move Async RPC abstraction into GHCi.Message.Async
Carves out the Async RPC over the Pipe abstraction to a new module,
making the GHCi.Message more about the specific interpreter messages
rather than about the IPC protocol.
- - - - -
13038cd0 by Rodrigo Mesquita at 2026-11-15T14:49:28+01:00
interp: If we have pending reads in the queue we can deliver them
We may still be able to reply even if the read end was closed.
As long as we have pending messages we should try to deliver them.
- - - - -
1fe95adc by Andrea Vezzosi at 2026-11-15T14:49:28+01:00
interp: close Handles when done with Pipe
Ensures we close the pipe handles (if created using 'mkPipeFromHandles')
on `closePipe`, and do `closePipe` on `Shutdown`.
The thread draining the read end always `'finally'` closes the read end.
And `closePipe` kills the draining thread and closes the write end.
When `remoteAsyncReq`, we throw PipeReadClosedException if the pipe read is
closed, since we wouldn't be able to receive the reply.
It's fine for the drain thread not to close the write end, even if it
dies without `closePipe` (which does close the write end), because:
- requests pending a reply will get PipeClosedException (we'll not be
able to read any further "real" reply)
- new calls to `remoteAsyncReq` will throw PipeReadClosedException
- pending pipe writes, in response to an already read request, might still succeed
And the clean up code should call close pipe to ensure the write end is
closed as well.
So, if the drain thread dies naturally and the read end is closed, may
still be attempted to be used, but it will throw accordingly. The user
likely wants to catch this to close the write end as well.
- - - - -
50b6d6c4 by Zubin Duggal at 2026-11-15T14:49:28+01:00
interp: fix external interpreter shutdown deadlock on Windows
On shutdown both GHC and iserv call `closePipe`, which stopped the drain
thread before closing the write end. On Windows the drain thread reads
with a safe foreign call to _read, which `throwTo' can't interrupt, so
the two sides were stuck in the deadlock deadlock.
Closing the write end first is not enough on its own. On Windows a read
on a pipe only unblocks once all write handles to it are closed [1].
However, all all four pipe ends were inheritable and we didn't close the
child's ends in the parent. This means a close on any one side wouldn't
unblock any reads, becuase the other side had another copy open.
* runWithPipes now uses System.Process.CommunicationHandle [2], which is
built for passing pipes to a child process: only the child's ends are
inheritable, and it simplifies our mess of CPP. Additionally, it is
important to close our copy of the endpoints passed to the child so
each side only keeps open copies it needs to allow a close to unblock
reads.
* readGhcHandle makes the handle non-inheritable so we don't have
additional references floating around that stop reads from unblocking
on close.
* In closePipe the ordering is subtle and important. We first fail any
requests still waiting for a reply, then close the write end so the
other side sees EOF. We take the write lock to close it, so we never
close under a concurrent write [3]. Only then do we stop the drain
thread, which closes the read end itself once its read has finished.
Bump bound to process >= 1.6.20 as this is the version with
System.Process.CommunicationHandle
[1] https://learn.microsoft.com/en-us/windows/win32/ipc/anonymous-pipe-operatio…
[2] https://github.com/haskell/process/pull/308
[3] https://gitlab.haskell.org/ghc/ghc/-/work_items/27801
- - - - -
e4c6f7ff by Andrea Vezzosi at 2026-11-15T14:49:28+01:00
GHCi.Server: handle RunTH and RunModFinalizers in forked thread
This commit makes the external interpreter able to many interpret
template haskell splices in parallel without blocking the main server
thread. Simply: fork off a thread to handle a RunTH request. The handler
will issue the reverse-requests on the given RunTH mailbox, to keep each
RunTH isolated from the others.
`handleRemoteCall` was generalised slightly by allowing `WriteReply` to
be used linearly in the handler directly, so that the caller of
`handleRemoteCall` may `WriteReply` in the forked thread rather than in
the main thread.
The only question is how can we guarantee `WriteReply` is used linearly
if we want to use it inside a forked thread? We need two guarantees:
1. `WriteReply` is used in the forked thread regardless of whether an
exception is thrown to that thread.
2. The forked thread is always awaited for, so that the main program
doesn't exit before the thread has a chance to actually use
`WriteReply`.
We introduced a small `ThreadManager` which provides a `spawnFinally`
that provides these two guarantees:
1. is guaranteed by `forkFinally`, which always runs the clean up action
exactly once.
2. is guaranteed by `ThreadManager` being abstract and the only exposed
function that introduces `ThreadManager` being `withThreadManager`,
which always awaits for all spawned threads.
Co-authored-by: Rodrigo Mesquita <rodrigo.m.mesquita(a)gmail.com>
- - - - -
e5f4c636 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: spawn fillPipe thread, writePipe now safely interruptible
Previously an async exception during a call to `writePipe` could have caused a
partial write, making any further write impossible to parse from the other end.
Now `writePipe` merely pushes the message onto a queue, and the actual write
happens in a separate `fillPipe` thread. As a result of this and previous
changes, `interpCmd` no longer needs `interruptibleMask` to preserve the state
of the protocol.
`writePipe` waits for the actual write to complete, and rethrows exceptions
raised in the write attempt, if any.
- - - - -
95bf6456 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
Follow `Note [Exceptions in TH]` in `qReport` implementation
`qReport b msg` should use `seqList msg` to trigger any exceptions in the
`String`, as explained in the note.
Through refactors the `seqList msg` call followed the bulk of the implementation
in `GHC.Tc.Gen.Splice.report`, but the call should be in `qReport` itself, so
that, even with -fexternal-interpreter, `msg` gets forced right away and any
exceptions get reported as a compilation error.
Follow up to 'interp: spawn fillPipe thread, writePipe now safely
interruptible'.
- - - - -
c86bbf7f by Rodrigo Mesquita at 2026-11-15T14:49:29+01:00
test: make T3171 not fragile and add version for ext interp too
- actually test the sleep of the user-given expression gets interrupted
- the ext interp version tests two things:
- Requests can be cancelled without terminating the ext interp (#18852)
- The stmt being evaluated gets interrupted in the ext interp (that
is, ^C gets sent to the thread running the user-given expression
and doesn't affect the ext interp main thread)
- testing ext interp requires sending ^C to whole process group
Fixes #15383
- - - - -
0a9fe296 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: cancel requests if async exceptions while waiting for reply.
- - - - -
b79b7199 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: do not terminate ext. interp. process on exception
`sendMessage` throwing an exception does not warrant terminating the external
interpreter process anymore, because communication can keep going no matter what.
`stopInterp` now resets the whole `Interp` state, so that a new
ExtInterpInstance can be later created and work correctly.
`withExtInterp` now calls `stopInterp` on a `PipeClosedException` and rethrows.
Fixes #18852
- - - - -
523eea29 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
remoteAsyncReq cleans up a pendingReply on exception.
- - - - -
d3da741b by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
remoteAsyncReq: send cancel if exception during writePipe
fixes gap in exception coverage.
- - - - -
86e01e71 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: single-threaded sendTHComputation
- - - - -
aecc6923 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: test: no deadlock when handleTHMessage throws.
it used to be that handleTHMessage throwing would neglect to notify and/or tear
down the external interpreter, causing it to deadlock (or fail with blocked
indefinitely).
Now we reply with the exception, before rethrowing it, so the external
interpreter can shutdown cleanly.
- - - - -
7af05b1c by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: test: panic in handleTHMessage does not deadlock
similar to TH_ReifyModuleFail but with a plugin.
- - - - -
c72bb720 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: cleanup on cancel
interp: don't drop pending frees if the drain is interrupted
interp: release RemoteRefs and RemotePtrs from replies of canceled requests
- - - - -
c18232cb by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: mask while handling RemoteRefs in dynLinkCompiledByteCode
Between 'createBCOs' and 'makeForeignNamedHValueRefs' the refs are not tracked,
so could have been leaked if interrupted.
Modified 'makeForeignNamedHValueRefs' so it does not have interruption points
when the interpreter is running.
- - - - -
688b96d7 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: return ForeignRef rather than RemoteRef whenever possible.
and more generally masking until a finalizer is attached.
Anything to do with EvalStatus_ is not fixed here, as it would require larger
changes to the API.
- - - - -
854366cb by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
linker: purge the symbol cache before unloading
Unloading might throw at which point it's uncertain which symbols are still
loaded, purging the symbol cache upfront means we don't risk holding a reference
to an unloaded symbol..
See Note [LoaderState may lag the interpreter].
- - - - -
db54fee2 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: add finalizer to ModFinalizer under mask
- - - - -
eca348e8 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
ghci: fixed 'freeForeignCallInfo' to properly free 'arg_types' array.
freeForeignCallInfo used to free the 'p->arg_types' field itself, rather than
the array it points to. Now reads the pointer stored at 'p->arg_types', frees
that, then frees 'p'.
- - - - -
b0114604 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: test resources are cleaned up when request interrupted.
- - - - -
580763a5 by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
interp: exit cleanly if pipe closed while replying to Shutdown.
iserv avoids reporting exceptions coming from pipe operations after we received
Shutdown: writing a reply after the host closed its end because the grace period
elapsed shouldn't look like a bug.
We do so by indicating the pipe is closing right after we receive Shutdown, so
both the main loop and any running handler threads can tell a closed pipe is
expected.
- - - - -
653e4ffc by Andrea Vezzosi at 2026-11-15T14:49:29+01:00
template-haskell: force arguments of Q primitives up front.
Exceptions in arguments of 'Quote Q' and 'Quasi Q' were not detected until the
last minute, where they could cause panics or cause implementation details to
leak into error messages.
Now they are 'deepseq'eq up front, types permitting, so any exceptions are
cleanly reported as originating from the splice.
Follow up to 'Follow `Note [Exceptions in TH]` in `qReport` implementation'
which already handled the `qReport` case.
Fixes #28112
- - - - -
2bd5c810 by Andrea Vezzosi at 2026-11-17T13:27:47+01:00
runWithPipes: fix on Windows when without -threaded
Test 'static-plugin-interp-panic' happens to build without -threaded
and would timeout on Windows CI.
Turns out that in such a configuration the 'Handle's we get from
'System.Process.CommunicationHandle' cause the whole process to lock.
Rebuilding them with 'hANDLEToHandle' fixes it.
- - - - -
6de946f5 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
interp: close pipes more promptly
- - - - -
0b9d2cf5 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
interp: time limit closePipe in stopInterp
- - - - -
43341d18 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
runWithPipes: avoid race to close their end on windows
`closeCommunicationHandle` will query info about the raw handle, using windows
primitives that block while a ReadFile is pending. We call it right after
createProcess for `iserv`, but `iserv` might still start reading from the pipe
first. If that happens then there's a deadlock, because we won't write anything
for iserv to read until we are done closing its read end in our process.
The fix is to use `closeHandle` directly, as that won't block for pending reads.
- - - - -
5fbd333c by Andrea Vezzosi at 2026-11-17T13:30:00+01:00
interp: cleanup with stopInterp outside interpLoader lock
On a PipeClosedException we want to stop the running external interpreter and
reset the state of the `Interp`, which includes the loader state.
So, to avoid deadlocks, we now have the PipeClosedException handler outside of places
where we take the loader state lock.
A new `SafeInterp` type is introduced to aid with this discipline: functions
that take a bare `Interp` must not take the loader state lock themselves.
We also fix a race between restarting the interpreter and the
PipeClosedException cleanup: if an interpreter's Pipe is open we don't terminate
it, as it must be a new instance.
- - - - -
abdfbbf3 by Andrea Vezzosi at 2026-11-17T14:34:55+01:00
interp: test concurrent use of one external interpreter
Threads share a GHC session: concurrent requests, killing waiting threads,
cancelling a running splice, and restarting after the interpreter dies.
- - - - -
b2ab554e by Rodrigo Mesquita at 2026-11-18T15:20:49+00:00
Global break action which uses a per-thread context map
Previously, everytime an expression was run in the interpreter (`sandboxIO`):
1) the RTS global variable `rts_breakpoint_io_action`, which is run
anytime any thread hits a breakpoint, got set to a new action that:
a) Wrote the breakpoint hit by the thread to the `statusMVar`
b) Blocked waiting on a newly created MVar `breakMVar` for a `resumeStmt` to
signal it.
2) Start the expression evaluation on a new "sandbox" thread
3) Block waiting on `statusMVar` for a breakpoint to be hit, and we'd
return the read `EvalBreak`
4) Set the `rts_breakpoint_io_action` to a no-op which prints "Ignored breakpoint..."
At some later point, we could `resumeStmt` with the `EvalBreak` context
by signaling the `breakMVar` on which the thread that hit the breakpoint
is blocked.
However, if you consider an expression which forks off threads which hit
breakpoints, surprising things may happen:
main = do
-- the `worker` code has a breakpoint
mapM (forkIO . worker) [1..10]
forever $ threadDelay 10000000
Interpreting this program, we'll do (1,2,3), and all workers will hit
their breakpoint and run `rts_breakpoint_io_action`. Here's a first
issue:
1. The first worker succeeds in `putMVar statusMVar`
2. The interpreter will read `takeMVar statusMVar` (3) and then (4)
3. The remaining workers are hitting the breakpoint concurrently:
- Some may block trying to `putMVar statusMVar`
- Some may run the no-op action which discards the breakpoint
Depending on whether the remaining workers hit the breakpoint or (4)
happens first, some workers will skip their breakpoint.
Now, let's pretend all workers can block on `putMVar statusMVar`. Since
the interpreter will take the breakpoints one by one, and resume them
one by one, it seemingly works. However, that's only fine when we assume
only one expression is evaluated at once. As soon as multiple
expressions can be evaluated at once (a desireable property of a
debugger, as well as something that can already happen today in some
scenarios (see `break049`)), it becomes madness:
The second issue comes the global break action being swapped by a second
evaluation and threads from the first evaluation running the "wrong" action.
Consider:
1. eval `expr_A` installs a break action that puts on `statusMVar_A`
2. `expr_A` forks off a few threads, they're running in the background
3. eval `expr_B` sets the break action to put on `statusMVar_B`
4. the `expr_A` forked threads hit a breakpoint and put `statusMVar_B`
5. `expr_B` returns with a breakpoint of `expr_A`, `resume expr_B` would
resume `expr_A`, etc...
A third issue with having a single MVar for all threads of an execution
is that there is no way to have fine-grained control over which threads
are resumed and which are stopped. This is often necessary to debug
multi-threaded programs too.
Therefore, it is imperative that the global break action does not
capture a global single MVar when many expressions with many
corresponding threads can be running in the interpreter/debugger at
once, if we want to support debugging multi-threaded programs at all.
---
This commit fixes these foundational issues by making the global break
action truly global (i.e. never modified and never capturing any locals).
The global break action is installed once in `sandboxIO` and never
removed (`withBreakAciton` and `noBreakAction` were killed). Subsequent
runs of `sandboxIO` re-rewrite the same break action (a no-op).
When any thread hits the global break action, it looks its `ThreadId` up
in the global per-thread context mapping, returning a `ResumeContext`
which contains that thread's `breakMVar` (now `resumeBreakVar`) and
`statusMVar` (now `resumeEvalStatus`). Each thread blocks on its own
MVar and replies on its own TVar. There is no longer one global status
nor break MVar.
To resume a thread by its `ThreadId`, we can simply fetch its
`ResumeContext` and signal the corresponding `resumeBreakMVar`
To wait for a result or for a breakpoint in a specific thread, we do
`readThreadEvalStatus`. To wait for any breakpoint hit in any thread at
all, we have `readAnyThreadEvalBreak`.
Some evaluations will only care to look at their own result and breaks
(so they run with `readAllBreaks` `= False`); and the main thread of an
evaluation should not be read by other evaluations. In short, only
threads forked off by the main thread of evaluations get read with
`readAnyThreadEvalBreak`. If two evaluations fork off threads in the
background, `readAnyThreadEvalBreak` may return threads from any of
them. There is no just way to distinguish their "parents" at runtime.
For instance, `compileParsedExprRemote` should run an expression until
completion without any existing threads interfering with its execution,
so it runs with `readAllBreaks = False`. Otherwise, by default, running
`main` on the REPL, we'll want to stop at any break any forked thread
hits, just like we did before.
P.S. Currently, we need to keep track of the "main expression thread"
being currently evaluated to fetch its result, but, when `evalStmt`
becomes asynchronous by returning the `ThreadId` of the "sandbox"
thread, the whole `evaluationMainThreadGlobalVar` hack can be deleted.
---
New tests observing behavior that we don't want to break (which I broke
at some point while developing this patch):
- break032: we don't stop at breakpoints in TH
- break033: :continue after -fbreak-on-exception doesn't hit exception breakpoint
- break034: test :abandon doesn't hang with -fbreak-on-error
- conc033: also run with the external interpreter
- ForceInterrupt(Ext): ^C during :force interrupts the forced expression
- break043: :continue of a forked thread reads main thread breaks/results too
- break046: evaluating expr while stopped doesn't change what :continue resumes
- break048: evaluating expr while forked thread is stopped doesn't hit again current breakpoint
New tests that failed before this commit:
- T3171(ext)nosandbox: T3171 with -fno-ghci-sandbox (T3171extnosandbox still fails)
- break050(ext): ^C during :continue of a forked thread interrupts that thread
Fixed ext-interp bc. resumeStmt now does unsafeUnmask, just like
sandboxIO, so the UserInterrupt reaches the resume.
- break049: breakpoints in forked threads don't get mixed up with other evaluations
This test demonstrates one way multi-threaded debugging can go wrong
bc the global break action used to capture a break MVar for a
specific thread that is shared by all threads (described above as
"the second issue"). Here is the annotated execution of the test
*before this commit*:
```haskell
ghci> main
Stopped in Main.inMain, break049.hs:30:12-18
_result :: IO () = _
[break049.hs:30:12-18] ghci> :force slow
-- ANN: the breakpoint we're ignoring on :force is the worker's
-- breakpoint, and it's just discarded
*** Ignoring breakpoint [break049.hs:27:14-20]
slow = 5
[break049.hs:30:12-18] ghci> :cmd return ""
-- ANN: we :continue `main`, but the worker should still be blocked
-- so `main` should block.
[break049.hs:30:12-18] ghci> :continue
-- ANN: however, it completes; recall the worker break was ignored
-- instead of stopping there
main done
-- ANN: after this commit, the worker break wouldn't have been read
-- by `:force`, and we'd see it when resuming `:main`, and
-- `:continue` here would resume the worker and only then main would
-- complete.
ghci> :continue
-- ANN: bc this is ghci before the commit, we see:
not stopped at a breakpoint
ghci>
```
- break042: main forks workers and all workers hit a breakpoint
This test witnesses "the first issue" described above, where the
workers hit breaks after the global break action was already removed
and so are lost.
Fixes #28124
- - - - -
112 changed files:
- + changelog.d/28124
- + changelog.d/T27960
- compiler/GHC/Driver/Config.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Env/Types.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Runtime/Interpreter/Init.hs
- compiler/GHC/Runtime/Interpreter/JS.hs
- compiler/GHC/Runtime/Interpreter/Process.hs
- compiler/GHC/Runtime/Interpreter/Types.hs
- compiler/GHC/Runtime/Interpreter/Wasm.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Runtime/Utils.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/ghc.cabal.in
- ghc/GHCi/UI/Monad.hs
- libraries/ghc-internal/src/GHC/Internal/TH/Monad.hs
- libraries/ghci/GHCi/FFI.hsc
- libraries/ghci/GHCi/Message.hs
- + libraries/ghci/GHCi/Message/Async.hs
- libraries/ghci/GHCi/Run.hs
- + libraries/ghci/GHCi/Run/Breakpoints.hs
- libraries/ghci/GHCi/Server.hs
- + libraries/ghci/GHCi/Server/Threads.hs
- libraries/ghci/GHCi/TH.hs
- libraries/ghci/GHCi/Utils.hsc
- libraries/ghci/ghci.cabal.in
- libraries/template-haskell/Language/Haskell/TH/Syntax.hs
- libraries/template-haskell/template-haskell.cabal.in
- rts/Interpreter.c
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/ghci.debugger/scripts/Makefile
- testsuite/tests/ghci.debugger/scripts/all.T
- + testsuite/tests/ghci.debugger/scripts/break032.hs
- + testsuite/tests/ghci.debugger/scripts/break032.script
- + testsuite/tests/ghci.debugger/scripts/break032.stdout
- + testsuite/tests/ghci.debugger/scripts/break033.hs
- + testsuite/tests/ghci.debugger/scripts/break033.script
- + testsuite/tests/ghci.debugger/scripts/break033.stdout
- + testsuite/tests/ghci.debugger/scripts/break034.hs
- + testsuite/tests/ghci.debugger/scripts/break034.script
- + testsuite/tests/ghci.debugger/scripts/break034.stdout
- + testsuite/tests/ghci.debugger/scripts/break042.hs
- + testsuite/tests/ghci.debugger/scripts/break042.script
- + testsuite/tests/ghci.debugger/scripts/break042.stderr
- + testsuite/tests/ghci.debugger/scripts/break042.stdout
- + testsuite/tests/ghci.debugger/scripts/break043.hs
- + testsuite/tests/ghci.debugger/scripts/break043.script
- + testsuite/tests/ghci.debugger/scripts/break043.stdout
- + testsuite/tests/ghci.debugger/scripts/break046.hs
- + testsuite/tests/ghci.debugger/scripts/break046.script
- + testsuite/tests/ghci.debugger/scripts/break046.stdout
- + testsuite/tests/ghci.debugger/scripts/break048.hs
- + testsuite/tests/ghci.debugger/scripts/break048.script
- + testsuite/tests/ghci.debugger/scripts/break048.stdout
- + testsuite/tests/ghci.debugger/scripts/break049.hs
- + testsuite/tests/ghci.debugger/scripts/break049.script
- + testsuite/tests/ghci.debugger/scripts/break049.stdout
- + testsuite/tests/ghci.debugger/scripts/break050.hs
- + testsuite/tests/ghci.debugger/scripts/break050.script
- + testsuite/tests/ghci.debugger/scripts/break050.stdout
- + testsuite/tests/ghci.debugger/scripts/break050ext.stdout
- testsuite/tests/ghci/custom-external-interpreter-commands/Main.hs
- + testsuite/tests/ghci/interp-cancellation/Main.hs
- + testsuite/tests/ghci/interp-cancellation/all.T
- + testsuite/tests/ghci/interp-cancellation/interp-cancellation.stdout
- + testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs
- + testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout
- + testsuite/tests/ghci/should_run/ForceInterrupt.script
- + testsuite/tests/ghci/should_run/ForceInterrupt.stdout
- + testsuite/tests/ghci/should_run/ForceInterruptExt.stdout
- testsuite/tests/ghci/should_run/Makefile
- testsuite/tests/ghci/should_run/T3171.stdout
- + testsuite/tests/ghci/should_run/T3171ext.stdout
- + testsuite/tests/ghci/should_run/T3171extnosandbox.stdout
- + testsuite/tests/ghci/should_run/T3171nosandbox.stdout
- testsuite/tests/ghci/should_run/all.T
- testsuite/tests/interface-stability/template-haskell-exports.stdout
- testsuite/tests/plugins/all.T
- testsuite/tests/plugins/plugins10.stdout
- + testsuite/tests/plugins/static-plugin-interp-panic-module.hs
- + testsuite/tests/plugins/static-plugin-interp-panic.hs
- + testsuite/tests/plugins/static-plugin-interp-panic.stderr
- + testsuite/tests/plugins/static-plugin-interp-panic.stdout
- + testsuite/tests/th/T8987b.hs
- + testsuite/tests/th/T8987b.stderr
- + testsuite/tests/th/T8987c.hs
- + testsuite/tests/th/T8987c.stderr
- + testsuite/tests/th/T8987d.hs
- + testsuite/tests/th/T8987d0.stderr
- + testsuite/tests/th/T8987d1.stderr
- + testsuite/tests/th/T8987d10.stderr
- + testsuite/tests/th/T8987d11.stderr
- + testsuite/tests/th/T8987d12.stderr
- + testsuite/tests/th/T8987d13.stderr
- + testsuite/tests/th/T8987d2.stderr
- + testsuite/tests/th/T8987d3.stderr
- + testsuite/tests/th/T8987d4.stderr
- + testsuite/tests/th/T8987d5.stderr
- + testsuite/tests/th/T8987d6.stderr
- + testsuite/tests/th/T8987d7.stderr
- + testsuite/tests/th/T8987d8.stderr
- + testsuite/tests/th/T8987d9.stderr
- + testsuite/tests/th/TH_ReifyModuleFail.hs
- + testsuite/tests/th/TH_ReifyModuleFail.stderr
- testsuite/tests/th/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/55c57d76b2ed924606a6c9678f5a4d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/55c57d76b2ed924606a6c9678f5a4d…
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/romes/origin-global-break-action
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
29 Nov '26
Rodrigo Mesquita pushed new branch wip/romes/origin-global-break-action at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/romes/origin-global-break-act…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/romes/async-eval-resume] WIP: Start Async Eval/Resume
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
by Rodrigo Mesquita (@alt-romes) 29 Nov '26
29 Nov '26
Rodrigo Mesquita pushed to branch wip/romes/async-eval-resume at Glasgow Haskell Compiler / GHC
Commits:
a7f092c0 by Rodrigo Mesquita at 2026-11-29T10:13:06+00:00
WIP: Start Async Eval/Resume
TODO:
- Commit description
- Reference Note in commit description
- Explain "Interrupted" no longer in testsuite: GHCi's top level printed
that line because ghc's own ^C went uncaught; it's gone because ghc's
redirectInterrupts now catches the ^C and keeps waiting.
TODO: Add to changelog information about how to use the new
execStmt/resumeStmt, which return an action that when run blocks waiting
for the result.
Notes:
- The async eval/resume design requires an interpreter sandbox ThreadId
to be held by the host program. Therefore, we won't be able to detect
a deadlock in a sandboxed thread and won't send a BlockedIndefinitely,
so conc033 won't work on the ghci way. This is acceptable because
BlockedIndefinitely is a debug mechanism, and the RTS doesn't
guarantee that it is thrown.
WIP TICKET DESCRIPTION:
Title: Asynchronous evalStmt/resumeStmt interpreter interface
Description: After #28124 (global break action) and #27960 (asynchronous
ext interpreter RPC), we can adapt the interpreter `evalStmt` and
`resumeStmt` functions from `GHC.Runtime.Interpreter` to be more
asynchronous in the sense that we don't need to block immediately
waiting for the evaluation result, or for a resumed evaluation result.
- - - - -
13 changed files:
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter.hs
- ghc/GHCi/UI/Monad.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Run.hs
- libraries/ghci/GHCi/Server.hs
- libraries/ghci/GHCi/Signals.hs
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/ghc-api/T8628.hs
- testsuite/tests/ghc-api/T8639_api.hs
- testsuite/tests/ghc-api/apirecomp001/myghc.hs
- testsuite/tests/ghci.debugger/scripts/break050ext.stdout
Changes:
=====================================
compiler/GHC/Runtime/Eval.hs
=====================================
@@ -43,6 +43,7 @@ module GHC.Runtime.Eval (
) where
import GHC.Prelude
+import GHC.Conc
import GHC.Driver.Monad
import GHC.Driver.Main
@@ -186,12 +187,13 @@ execOptions = ExecOptions
, execWrap = EvalThis -- just run the statement, don't wrap it in anything
}
--- | Run a statement in the current interactive context.
+-- | Run a statement in the current interactive context, as a new thread in the interpreter.
+-- Returns an action which blocks waiting for the execution to finish and yield a result.
execStmt
:: GhcMonad m
=> String -- ^ a statement (bind or expression)
-> ExecOptions
- -> m ExecResult
+ -> m (m ExecResult)
execStmt input exec_opts@ExecOptions{..} = do
hsc_env <- getSession
@@ -202,13 +204,15 @@ execStmt input exec_opts@ExecOptions{..} = do
case mb_stmt of
-- empty statement / comment
- Nothing -> return (ExecComplete (Right []) 0)
+ Nothing -> return (return (ExecComplete (Right []) 0))
Just stmt -> execStmt' stmt input exec_opts
-- | Like `execStmt`, but takes a parsed statement as argument. Useful when
-- doing preprocessing on the AST before execution, e.g. in GHCi (see
-- GHCi.UI.runStmt).
-execStmt' :: GhcMonad m => GhciLStmt GhcPs -> String -> ExecOptions -> m ExecResult
+--
+-- Returns an action which blocks waiting for the execution to finish and yield a result.
+execStmt' :: GhcMonad m => GhciLStmt GhcPs -> String -> ExecOptions -> m (m ExecResult)
execStmt' stmt stmt_text ExecOptions{..} = do
hsc_env <- getSession
let interp = hscInterp hsc_env
@@ -224,20 +228,22 @@ execStmt' stmt stmt_text ExecOptions{..} = do
case r of
Nothing ->
-- empty statement / comment
- return (ExecComplete (Right []) 0)
+ return (return (ExecComplete (Right []) 0))
Just (ids, hval, fix_env) -> do
updateFixityEnv fix_env
let eval_opts = initEvalOpts idflags' (enableGhcStepMode execSingleStep)
- status <- liftIO $ evalStmt interp eval_opts (execWrap hval)
+ main_tid <- liftIO $ evalStmt interp eval_opts (execWrap hval)
let ic = hsc_IC hsc_env
bindings = (ic_tythings ic, ic_gre_cache ic)
size = ghciHistSize idflags'
- handleRunStatus execSingleStep eval_opts stmt_text bindings ids
- status (emptyHistory size)
+ pure $ do
+ status <- liftIO $ waitThreadResult interp main_tid eval_opts main_tid
+ handleRunStatus execSingleStep eval_opts stmt_text bindings ids
+ status (emptyHistory size) main_tid
runDecls :: GhcMonad m => String -> m [TyThing]
runDecls = runDeclsWithLocation "<interactive>" 1
@@ -300,8 +306,10 @@ handleRunStatus :: GhcMonad m
-> [Id]
-> EvalStatus [ForeignHValue]
-> BoundedList History
+ -> ForeignRef ThreadId
+ -- ^ The thread started by evalStmt to run this evaluation
-> m ExecResult
-handleRunStatus step eval_opts expr bindings final_ids status history0 = do
+handleRunStatus step eval_opts expr bindings final_ids status history0 main_tid = do
hsc_env <- getSession
let
interp = hscInterp hsc_env
@@ -342,6 +350,7 @@ handleRunStatus step eval_opts expr bindings final_ids status history0 = do
, resumeDecl = "<exception thrown>"
, resumeCCS = ccs
, resumeHistoryIx = 0
+ , resumeMainThread = main_tid
}
hsc_env2 = pushResume hsc_env1 resume
@@ -389,19 +398,22 @@ handleRunStatus step eval_opts expr bindings final_ids status history0 = do
, resumeDecl = decl
, resumeCCS = ccs
, resumeHistoryIx = 0
+ , resumeMainThread = main_tid
}
hsc_env2 = pushResume hsc_env1 resume
setSession hsc_env2
return (ExecBreak break_ids (Just ibi) resume)
else do
-- resume with the same step type
- status <- liftIO $ GHCi.resumeStmt interp eval_opts resume_ctxt_fhv
+ liftIO $ GHCi.resumeStmt interp eval_opts resume_ctxt_fhv
+ -- Redirect exceptions to the resumed thread, but await the main thread:
+ status <- liftIO $ waitThreadResult interp resume_ctxt_fhv eval_opts main_tid
history <- if not tracing then pure history0 else do
history1 <- liftIO $ mkHistory hug apStack_fhv ibi
let !history' = history1 `consBL` history0
-- history is strict, otherwise our BoundedList is pointless.
return history'
- handleRunStatus step eval_opts expr bindings final_ids status history
+ handleRunStatus step eval_opts expr bindings final_ids status history main_tid
where
tracing | RunAndLogSteps <- step = True
| otherwise = False
@@ -418,7 +430,10 @@ resumeExec :: GhcMonad m
=> SingleStep
-> Maybe Int
-> Resume
- -> m ExecResult
+ -> m (m ExecResult)
+ -- ^ Returns an action which blocks waiting for the execution of
+ -- this @'Resume'@'s @'resumeMainThread'@ to finish and yield another
+ -- breakpoint or result.
resumeExec step mbCnt r = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
@@ -447,7 +462,9 @@ resumeExec step mbCnt r = do
, resumeApStack = apStack
, resumeBreakpointId = mb_brkpt
, resumeSpan = span
- , resumeHistory = hist } ->
+ , resumeHistory = hist
+ , resumeMainThread = main_tid
+ } ->
do
-- When the user specified a break ignore count, set it
-- in the interpreter
@@ -456,17 +473,19 @@ resumeExec step mbCnt r = do
_ -> return ()
let eval_opts = initEvalOpts dflags (enableGhcStepMode step)
- status <- liftIO $ GHCi.resumeStmt interp eval_opts fhv
- let prevHistoryLst = fromListBL 50 hist
- hug = hsc_HUG hsc_env
- hist' = case mb_brkpt of
- Nothing -> pure prevHistoryLst
- Just bi
- | breakHere False step span -> do
- hist1 <- liftIO (mkHistory hug apStack bi)
- return $ hist1 `consBL` fromListBL 50 hist
- | otherwise -> pure prevHistoryLst
- handleRunStatus step eval_opts expr bindings final_ids status =<< hist'
+ liftIO $ GHCi.resumeStmt interp eval_opts fhv
+ pure $ do
+ status <- liftIO $ waitThreadResult interp fhv eval_opts main_tid
+ let prevHistoryLst = fromListBL 50 hist
+ hug = hsc_HUG hsc_env
+ hist_val <- case mb_brkpt of
+ Nothing -> pure prevHistoryLst
+ Just bi
+ | breakHere False step span -> do
+ hist1 <- liftIO (mkHistory hug apStack bi)
+ return $ hist1 `consBL` fromListBL 50 hist
+ | otherwise -> pure prevHistoryLst
+ handleRunStatus step eval_opts expr bindings final_ids status hist_val main_tid
setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157
setupBreakpoint interp ibi cnt = do
@@ -1278,7 +1297,8 @@ compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do
updateFixityEnv fix_env
-- Only this expression's result is expected, never another thread's break
let eval_opts = (initEvalOpts dflags EvalStepNone) { readAllBreaks = False }
- status <- liftIO $ evalStmt interp eval_opts (EvalThis hvals_io)
+ main_tid <- liftIO $ evalStmt interp eval_opts (EvalThis hvals_io)
+ status <- liftIO $ waitThreadResult interp main_tid eval_opts main_tid
case status of
EvalComplete _ (EvalSuccess [hval]) -> return hval
EvalComplete _ (EvalException e) ->
=====================================
compiler/GHC/Runtime/Eval/Types.hs
=====================================
@@ -198,6 +198,10 @@ data Resume = Resume
, resumeCCS :: RemotePtr CostCentreStack
, resumeHistory :: [History]
, resumeHistoryIx :: Int -- 0 <==> at the top of the history
+ , resumeMainThread :: ForeignRef ThreadId
+ -- ^ The corresponding main evaluation thread. A breakpoint may be on
+ -- a forked thread: we resume the stopped thread ('resumeContext'),
+ -- but await on the main evaluation one ('resumeMainThread')
}
type ResumeBindings = ([TyThing], IcGlobalRdrEnv)
=====================================
compiler/GHC/Runtime/Interpreter.hs
=====================================
@@ -10,6 +10,8 @@ module GHC.Runtime.Interpreter
-- * High-level interface to the interpreter
, evalStmt, EvalStatus(..), EvalResult(..), EvalExpr(..)
, resumeStmt
+ , waitThreadResult
+ , redirectInterrupts
, abandonStmt
, evalIO
, evalString
@@ -104,7 +106,7 @@ import GHC.Unit.Home.ModInfo
import GHC.Unit.Env
#if defined(HAVE_INTERNAL_INTERPRETER)
-import GHCi.Run
+import GHCi.Run hiding (redirectInterrupts)
#endif
import Control.Concurrent
@@ -322,11 +324,11 @@ evalStmt
:: SafeInterp
-> EvalOpts
-> EvalExpr ForeignHValue
- -> IO (EvalStatus [ForeignHValue])
+ -> IO (ForeignRef ThreadId)
evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do
- status <- withExpr foreign_expr $ \expr ->
+ rtid <- withExpr foreign_expr $ \expr ->
interpCmd interp (EvalStmt opts expr)
- handleEvalStatus interp status
+ mkFinalizedHValue interp rtid
where
withExpr :: EvalExpr ForeignHValue -> (EvalExpr HValueRef -> IO a) -> IO a
withExpr (EvalThis fhv) cont =
@@ -340,12 +342,48 @@ resumeStmt
:: SafeInterp
-> EvalOpts
-> ForeignRef ThreadId
- -> IO (EvalStatus [ForeignHValue])
+ -- ^ The thread to resume
+ -> IO ()
resumeStmt interp0 opts resume_tid = withInterp interp0 $ \interp -> do
- status <- withForeignRef resume_tid $ \rhv ->
+ withForeignRef resume_tid $ \rhv -> do
interpCmd interp (ResumeStmt opts rhv)
+
+-- | Await the result of an action of type @IO [a]@, running on the given
+-- interpreter thread, returning 'ForeignHValue's for each of the results.
+waitThreadResult
+ :: SafeInterp
+ -> ForeignRef ThreadId
+ -- ^ The thread on the interpreter on which asynchronous exceptions raised in
+ -- this host thread are thrown to. Typically this should be the same as the
+ -- thread whose result we're awaiting.
+ -> EvalOpts
+ -- ^ Use 'readAllBreaks' as: @True@ to read breakpoints on all non-isolated
+ -- interpreter threads (such as those forked off by the debuggee evaluation
+ -- statement); @False@ to only return the result or breakpoints in this
+ -- thread specifically.
+ -> ForeignRef ThreadId
+ -- ^ The main isolated evaluation thread whose status is awaited
+ -> IO (EvalStatus [ForeignHValue])
+waitThreadResult interp0 redirect_ftid opts wait_ftid = withInterp interp0 $ \interp -> do
+ status <- withForeignRef redirect_ftid $ \redirect_tid -> do
+ redirectInterrupts interp redirect_tid $
+ withForeignRef wait_ftid $ \wait_tid ->
+ interpCmd interp (WaitThreadResult (readAllBreaks opts) wait_tid)
handleEvalStatus interp status
+-- | While we're waiting for the possibly remote interpreter thread to yield a
+-- result, if the current host thread receives an asynchronous exception, we
+-- re-throw it at the target thread on the possibly remote interpreter and
+-- continue to wait. This allows e.g. a ^C on the host to interrupt an
+-- 'evalStmt' on the external interpreter.
+--
+-- Akin 'GHCi.Run.redirectInterrupts', but on the ghc side.
+redirectInterrupts :: Interp -> RemoteRef ThreadId -> IO a -> IO a
+redirectInterrupts interp rtid wait =
+ wait `catch` \(e::SomeAsyncException) -> do
+ interpCmd interp (ThrowToThread rtid (toSerializableException (toException e)))
+ wait
+
abandonStmt :: SafeInterp -> ForeignRef ThreadId -> IO ()
abandonStmt interp0 resume_tid = withInterp interp0 $ \ interp ->
withForeignRef resume_tid $ \rhv ->
@@ -452,7 +490,11 @@ whereFrom interp0 ref = withInterp interp0 $ \ interp ->
seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
- status <- interpCmd interp (Seq hval)
+ rtid <- interpCmd interp (Seq hval)
+ frtid <- mkFinalizedHValue interp rtid
+ status <- withForeignRef frtid $ \rtid ->
+ redirectInterrupts interp rtid $ do
+ interpCmd interp (WaitThreadResult False rtid)
handleSeqHValueStatus interp unit_env logger (clearEvalStatus status)
evalBreakpointToId :: EvalBreakpoint -> InternalBreakpointId
@@ -496,7 +538,12 @@ handleSeqHValueStatus interp unit_env logger eval_status =
-- resume the seq (:force) processing in the iserv process
withForeignRef resume_tid_fhv $ \rtid -> do
- status <- interpCmd interp (ResumeSeq rtid)
+ interpCmd interp (ResumeSeq rtid)
+ status <- redirectInterrupts interp rtid $ do
+ -- Resume the stopped thread. The stopped thread must be the main
+ -- `:seq` thread, since readAllBreaks=False on @Seq@ cmd implies an
+ -- EvalBreak on a :seq must be from from the seq main thread
+ interpCmd interp (WaitThreadResult False rtid)
handleSeqHValueStatus interp unit_env logger (clearEvalStatus status)
(EvalComplete _ r) -> return r
=====================================
ghc/GHCi/UI/Monad.hs
=====================================
@@ -380,7 +380,8 @@ runStmt stmt stmt_text step = do
, GHC.execSingleStep = step
, GHC.execWrap = \fhv -> EvalApp (EvalThis (evalWrapper st))
(EvalThis fhv) }
- Just <$> GHC.execStmt' stmt stmt_text opts
+ waitRes <- GHC.execStmt' stmt stmt_text opts
+ Just <$> waitRes
runDecls :: GhciMonad m => String -> m (Maybe [GHC.TyThing])
runDecls decls = do
@@ -418,7 +419,8 @@ resume step mbIgnoreCnt = do
throwGhcExceptionIO (GHC.ProgramError "not stopped at a breakpoint")
(r:rs) -> do
modifySession $ \env -> env{hsc_IC = (hsc_IC env){ ic_resume = rs }}
- GHC.resumeExec step mbIgnoreCnt r
+ waitRes <- GHC.resumeExec step mbIgnoreCnt r
+ waitRes
-- --------------------------------------------------------------------------
-- timing & statistics
=====================================
libraries/ghci/GHCi/Message.hs
=====================================
@@ -144,13 +144,14 @@ data Message a where
EvalStmt
:: EvalOpts
-> EvalExpr HValueRef {- IO [a] -}
- -> Message (EvalStatus [HValueRef]) {- [a] -}
+ -> Message (RemoteRef ThreadId)
+ -- ^ 'WaitThreadResult' of this thread id yields [a]
-- | Resume evaluation of a statement after a breakpoint
ResumeStmt
:: EvalOpts
-> RemoteRef ThreadId
- -> Message (EvalStatus [HValueRef])
+ -> Message ()
-- | Abandon evaluation of a statement after a breakpoint
AbandonStmt
@@ -254,13 +255,27 @@ data Message a where
-- | Evaluate something. This is used to support :force in GHCi.
Seq
:: HValueRef
- -> Message (EvalStatus [HValueRef])
+ -> Message (RemoteRef ThreadId)
-- | Resume forcing a free variable in a breakpoint (#2950)
ResumeSeq
:: RemoteRef ThreadId
+ -> Message ()
+
+ -- | Await the result or a breakpoint of a sandbox thread.
+ WaitThreadResult
+ :: Bool
+ -- ^ Whether to read all thread breaks on any forked threads (@True@) or
+ -- just this thread's breakpoints or its eval result (@False@)
+ -> RemoteRef ThreadId
-> Message (EvalStatus [HValueRef])
+ -- | Throw a serializable exception to the given thread
+ ThrowToThread
+ :: RemoteRef ThreadId
+ -> SerializableException
+ -> Message ()
+
-- | User-defined request encoded as a tag/payload pair. This is left
-- uninterpreted by GHC and is meant for GHC API applications to be able to supply
-- their own interpreter which understands additional commands.
@@ -295,20 +310,22 @@ resultRemoteResources msg res = case msg of
PrepFFI{} -> [RemoteFFI res]
LookupClosure{} -> map RemoteHValueRef $ toList res
CreateBCOs{} -> map RemoteHValueRef $ res
- EvalStmt{} -> map RemoteHValueRef $ evalStatus id res
- ResumeStmt{} -> map RemoteHValueRef $ evalStatus id res
NewBreakArray{} -> map RemoteHValueRef $ [castRemoteRef res]
GetBreakpointVar{} -> map RemoteHValueRef $ toList res
StartTH{} -> [RemoteHValueRef $ castRemoteRef res]
GetClosure{} -> map RemoteHValueRef $ toList res
- Seq{} -> map RemoteHValueRef $ evalStatus (const []) res
- ResumeSeq{} -> map RemoteHValueRef $ evalStatus (const []) res
AddLibrarySearchPath{} -> [RemoteLibrarySearchPath res]
+ WaitThreadResult{} -> map RemoteHValueRef $ evalStatus id res
+ EvalStmt{} -> [RemoteHValueRef $ castRemoteRef res]
+ Seq{} -> [RemoteHValueRef $ castRemoteRef res]
(CustomMessage _ _ CustomMessageMethods{..})
-> customResultRemoteResources res
(CustomMessage _ _ Deserialized)
-> error "resultRemoteRefs on deserialized CustomMessage"
+ -- resume returns ()
+ ResumeStmt{} -> []
+ ResumeSeq{} -> []
-- 'LoadDLLs' is idempotent.
LoadDLLs{} -> []
@@ -343,6 +360,7 @@ resultRemoteResources msg res = case msg of
RunModFinalizers{} -> []
WhereFrom{} -> []
FreeRemoteResources{} -> []
+ ThrowToThread{} -> []
where
evalStatus :: (b -> [HValueRef]) -> EvalStatus b -> [HValueRef]
evalStatus f = \case
@@ -694,6 +712,8 @@ getMessage = do
41 -> Msg <$> (AddHpcModule <$> get <*> get <*> get <*> get)
42 -> Msg <$> (CustomMessage <$> get <*> get <*> pure Deserialized)
43 -> Msg <$> (FreeRemoteResources <$> get)
+ 44 -> Msg <$> (WaitThreadResult <$> get <*> get)
+ 45 -> Msg <$> (ThrowToThread <$> get <*> get)
_ -> error $ "Unknown Message code " ++ (show b)
putMessage :: Message a -> Put
@@ -743,6 +763,8 @@ putMessage m = case m of
AddHpcModule m n h ticks -> putWord8 41 >> put m >> put n >> put h >> put ticks
CustomMessage tag payload _ -> putWord8 42 >> put tag >> put payload
FreeRemoteResources ps -> putWord8 43 >> put ps
+ WaitThreadResult b tid -> putWord8 44 >> put b >> put tid
+ ThrowToThread tid e -> putWord8 45 >> put tid >> put e
{-
Note [Parallelize CreateBCOs serialization]
=====================================
libraries/ghci/GHCi/Run.hs
=====================================
@@ -49,7 +49,6 @@ import GHC.Stack
import Foreign hiding (void)
import Foreign.C
import GHC.Conc.Sync
-import GHC.IO hiding ( bracket )
import System.Mem.Weak ( deRefWeak )
import Unsafe.Coerce
@@ -130,7 +129,10 @@ run m = case m of
InfoProv.whereFrom =<< localRef ref
Seq ref -> doSeq ref
ResumeSeq ref -> resumeSeq ref
-
+ WaitThreadResult b tid -> waitThreadResult b tid
+ ThrowToThread ref e -> do
+ tid <- localRef ref
+ throwTo tid (fromSerializableException e)
Shutdown -> unexpectedMessage m
RunTH {} -> unexpectedMessage m
RunModFinalizers {} -> unexpectedMessage m
@@ -214,7 +216,7 @@ tryEval io = do
--------------------------------------------------------------------------------
-evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (EvalStatus [HValueRef])
+evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (RemoteRef ThreadId)
evalStmt opts expr = do
io <- mkIO expr
sandboxIO opts $ do
@@ -256,7 +258,7 @@ evalStringToString r str = do
-- The UI process has more and therefore also can show more
-- information about the breakpoint than the current iserv
-- process.
-doSeq :: RemoteRef a -> IO (EvalStatus [HValueRef])
+doSeq :: RemoteRef a -> IO (RemoteRef ThreadId)
doSeq ref = do
sandboxIO evalOptsSeq $ do
_ <- (void $ evaluate =<< localRef ref)
@@ -264,7 +266,7 @@ doSeq ref = do
-- | Process a ResumeSeq message. Continue the :force processing #2950
-- after a breakpoint.
-resumeSeq :: RemoteRef ThreadId -> IO (EvalStatus [HValueRef])
+resumeSeq :: RemoteRef ThreadId -> IO ()
resumeSeq = resumeStmt evalOptsSeq
evalOptsSeq :: EvalOpts
@@ -287,20 +289,20 @@ evalOptsSeq = EvalOpts
-- only while we execute the user's code. We can't afford to lose the final
-- 'writeThreadEvalStatus', otherwise deadlock ensues. (#1583, #1922, #1946)
-sandboxIO :: EvalOpts -> IO [HValueRef] -> IO (EvalStatus [HValueRef])
+sandboxIO :: EvalOpts -> IO [HValueRef] -> IO (RemoteRef ThreadId)
sandboxIO opts io = do
-- Make sure the global breakpoint action is set; and that the interpreter
-- main thread doesn't stop at breakpoints in it.
-- See Note [Disable breakpoints in certain threads]
poke breakPointIOAction globalBreakStablePtr
- disableThreadBreakpoints =<< myThreadId
+ mytid <- myThreadId
+ disableThreadBreakpoints mytid
- -- We are running in uninterruptibleMask
let runIt = measureAlloc $ tryEval $ rethrow opts $ clearCCS io
if useSandboxThread opts
then do
- tid <- forkIO $ do
+ tid <- mask_ $ forkIOWithUnmask $ \restore -> do
tid <- myThreadId
setIsolatedThread tid -- main thread is always isolated
setBreakFlags opts tid -- set flags on the sandbox thread
@@ -308,13 +310,9 @@ sandboxIO opts io = do
-- We only write the thread status map in two places:
-- * When the "main" thread finishes (here)
-- * When any thread hits a breakpoint (global break action)
- unsafeUnmask runIt >>= writeThreadEvalStatus tid
-
- main <- mkMainThreadWithContext tid
- atomically $ modifyTVar evaluationMainThreadGlobalVar (main :)
- redirectInterrupts tid $ unsafeUnmask $
- atomically $ readEvalStatus opts main
- else
+ restore runIt >>= writeThreadEvalStatus tid
+ mkRemoteRef tid
+ else do
-- GLUT on OS X needs to run on the main thread. If you
-- try to use it from another thread then you just get a
-- white rectangle rendered. For this, or anything else
@@ -325,7 +323,12 @@ sandboxIO opts io = do
-- tracing, etc.) need the expression to be running in a
-- separate thread, so debugging is only enabled when
-- using the sandbox.
- runIt
+ ctx <- getThreadResumeContext mytid
+ mask $ \restore -> do
+ -- clear the result of a previous eval on the no-sandbox thread
+ atomically $ writeTVar (resumeEvalStatus ctx) ThreadStatusRunning
+ restore runIt >>= writeCtxEvalStatus ctx
+ mkRemoteRef mytid
-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
@@ -362,34 +365,6 @@ rethrow EvalOpts{..} io =
rethrowIO (ExceptionWithContext cx se)
---
--- While we're waiting for the sandbox thread to return a result, if
--- the current thread receives an asynchronous exception we re-throw
--- it at the sandbox thread and continue to wait.
---
--- This is for two reasons:
---
--- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
--- computation to run its exception handlers before returning the
--- exception result to the caller of runStmt.
---
--- * clients of the GHC API can terminate a runStmt in progress
--- without knowing the ThreadId of the sandbox thread (#1381)
---
--- NB. use a weak pointer to the thread, so that the thread can still
--- be considered deadlocked by the RTS and sent a BlockedIndefinitely
--- exception. A symptom of getting this wrong is that conc033(ghci)
--- will hang.
---
-redirectInterrupts :: ThreadId -> IO a -> IO a
-redirectInterrupts target wait = do
- wtid <- mkWeakThreadId target
- wait `catch` \e -> do
- m <- deRefWeak wtid
- case m of
- Nothing -> wait
- Just target -> do throwTo target (e :: SomeException); wait
-
measureAlloc :: IO (EvalResult a) -> IO (EvalStatus a)
measureAlloc io = do
setAllocationCounter 0 -- #16012
@@ -439,31 +414,128 @@ Likewise for other interactions between eval/resume/abandon.
TL;DR: always `setBreakFlags` when running/resuming a thread
-}
-resumeStmt :: EvalOpts -> RemoteRef ThreadId -> IO (EvalStatus [HValueRef])
+resumeStmt :: EvalOpts -> RemoteRef ThreadId -> IO ()
resumeStmt opts rtid = do
tid <- localRef rtid
ctx <- getThreadResumeContext tid
setBreakFlags opts tid
- main:_ <- readTVarIO evaluationMainThreadGlobalVar
- mask_ $ do
- resumeStoppedThread ctx -- this awakens the stopped thread...
- -- wait for the result of the main thread, not of the stopped one, but
- -- interrupt the thread which was resumed.
- redirectInterrupts tid $ unsafeUnmask $
- atomically $ readEvalStatus opts main
+ resumeStoppedThread ctx -- this awakens the stopped thread...
-- | Wait for the given main thread of an evaluation to complete or break or,
--- if 'readAllBreaks', for any other thread to break.
-readEvalStatus :: EvalOpts -> MainThreadWithCtx -> STM (EvalStatus [HValueRef])
-readEvalStatus opts main = do
- r <- readCtxEvalStatus (mainContext main)
- & if readAllBreaks opts
+-- if 'readAllBreaks :: Bool', for any other thread to break.
+readEvalStatus :: Bool -> ResumeContext -> STM (EvalStatus [HValueRef])
+readEvalStatus readAllBreaks ctx = do
+ readCtxEvalStatus ctx
+ & if readAllBreaks
then (`orElse` (EvalPaused <$> readAnyThreadEvalBreak))
else id
- case r of
- EvalComplete{} -> popMainThread main
- EvalPaused{} -> pure ()
- pure r
+
+-- | Await the result or breakpoint of a main evaluation thread (started with
+-- 'sandboxIO', unless -fno-ghci-sandbox). If the @readAllBreaks :: Bool@ is
+-- @True@, we may also return breakpoints hit by any other non-sandboxed
+-- threads in the interpreter.
+--
+-- If this function is used on a non-main-eval thread, such as one forked by
+-- the main debuggee that hit a breakpoint, we will only ever return its
+-- breakpoints, as that thread won't write ever an 'EvalComplete' result.
+-- @readAllBreaks@ works the same.
+--
+-- __WARNING__: You very likely want to wrap a call to this function in
+-- 'redirectInterrupts', as in
+-- @
+-- 'redirectInterrupts' tid $
+-- 'waitThreadResult' ... tid
+-- @
+-- Because if an asynchronous exception is thrown to the main interpreter
+-- thread, which is awaiting the evaluation result or a breakpoint on another
+-- thread, that exception should be re-throw to that thread to give it a chance
+-- to clean-up. See also Note [interpreter redirectInterrupts and signal handling]
+waitThreadResult :: Bool -> RemoteRef ThreadId -> IO (EvalStatus [HValueRef])
+waitThreadResult readAllBreaks r = do
+ tid <- localRef r
+ ctx <- getThreadResumeContext tid
+ atomically $ readEvalStatus readAllBreaks ctx
+
+{-
+Note [interpreter redirectInterrupts and signal handling]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+When evaluating a statement at the REPL, the interpreter will do something
+like:
+
+ evalStmt expr = forkIO (expr >>= writeThreadResult mytid)
+
+ tid <- evalStmt <user expr>
+ redirectInterrupts tid $
+ waitThreadResult tid
+
+The 'redirectInterrupts' call is responsible for re-throwing an asynchronous
+expression thrown to the main interpreter thread (which is blocked awaiting for
+the thread result) to the thread that the interpreter thread is blocked on, so
+it has a chance to clean-up properly.
+
+When using the internal interpreter, this is direct: a ^C goes directly to the
+main interpreter thread (GHC's 'withSignalHandlers' redirects signals to the
+ghc execution main thread, which, with the internal interpreter, is also
+running the interpreter commands and is currently blocked waiting for the
+evaluation result).
+
+With the external interpreter, which is a sub-process spawned by the main ghc
+process, if ^C interrupts the ghc process at the terminal, BOTH the main ghc
+process and the external interpreter get the ^C signal (^C at the terminal gets
+sent to all processes in the foreground process group).
+
+Therefore, we disable all signals on the external interpreter process (^C is
+fully ignored on the external interpreter) and, instead, let the main ghc process
+capture ^C and send a message to the external interpreter redirecting this
+interrupt to the thread we were waiting for. The program above, when using the
+external interpreter, under the hood works like:
+
+ tid <- remoteCall (EvalStmt <user expr>)
+ remoteCall (WaitThreadResult tid)
+ `onAsyncException` \e ->
+ remoteCall (ThrowToThread tid (serializeException e))
+ remoteCall (WaitThreadResult tid)
+
+where 'remoteCall' blocks waiting for the external interpreter to
+asynchronously deliver a reply to the given request, and cancels the pending
+request when an exception is thrown while waiting.
+
+This way, when there's a ^C on the main ghc process, we'll cancel the wait
+request (in `remoteCall`) and then send a request to interrupt the remote
+process thread with ^C (in `GHC.Runtime.Interpreter.redirectInterrupts`)
+
+Note: the `ghci` library still exposes a `redirectInterrupts`, in case you want
+to wrap calls to `waitThreadResult` using the ghci library directly; however,
+in ghc, we define `redirectInterrupts` as a function which captures host
+exceptions and sends a 'ThrowToThread' message which is interpreted by
+'throwTo'ing that exception on the interpreter process.
+-}
+
+-- | While we're waiting for the sandbox thread to return a result, if
+-- the current thread receives an asynchronous exception we re-throw
+-- it at the sandbox thread and continue to wait.
+--
+-- This is for two reasons:
+--
+-- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
+-- computation to run its exception handlers before returning the
+-- exception result to the caller of runStmt.
+--
+-- * clients of the GHC API can terminate a runStmt in progress
+-- without knowing the ThreadId of the sandbox thread (#1381)
+--
+-- NB. use a weak pointer to the thread, so that the thread can still
+-- be considered deadlocked by the RTS and sent a BlockedIndefinitely
+-- exception. A symptom of getting this wrong is that conc033(ghci)
+-- will hang.
+redirectInterrupts :: ThreadId -> IO a -> IO a
+redirectInterrupts target wait = do
+ wtid <- mkWeakThreadId target
+ wait `catch` \e -> do
+ m <- deRefWeak wtid
+ case m of
+ Nothing -> wait
+ Just target -> do throwTo target (e :: SomeException); wait
-- | When abandoning a computation we have to
-- (a) kill the stopped thread with an async exception, so that the
@@ -473,21 +545,15 @@ readEvalStatus opts main = do
-- evaluating a thunk when we stopped at the breakpoint, so the async
-- exception makes the thunk resumable from where we stopped instead of
-- updating it with an exception (tested in break010).
--- (c) wait for the main thread to terminate by waiting for its result.
--- This step is necessary to prevent race conditions with
--- -fbreak-on-exception (see #5975).
-- See test break010 and break034.
+--
+-- If the expression where we're stopped catches asynchronous exceptions it
+-- might catch the `AbandonException` instead of abandoning.
abandonStmt :: RemoteRef ThreadId -> IO ()
abandonStmt hvref = do
- main:_ <- readTVarIO evaluationMainThreadGlobalVar
tid <- localRef hvref
setBreakFlags evalOptsAbandon tid
- throwTo tid AbandonException -- kill stopped thread, then wait for main thread
- atomically $
- readCtxEvalStatus (mainContext main) >>= \case
- -- throwTo may return before the thread is marked as running
- EvalPaused{} -> retry
- EvalComplete{} -> popMainThread main
+ throwTo tid AbandonException -- kill the stopped thread
where
-- Don't stop anywhere on abandon
evalOptsAbandon = EvalOpts
@@ -504,34 +570,3 @@ data AbandonException = AbandonException deriving Show
instance Exception AbandonException where
toException = asyncExceptionToException
fromException = asyncExceptionFromException
-
---------------------------------------------------------------------------------
--- To remove completely when sandboxIO/resume becomes asynchronous:
---------------------------------------------------------------------------------
-
--- | The main threads of the exprs being currently evaluated, the most recent
--- first. Evaluating an expr while stopped at a breakpoint pushes its thread on
--- top of the stopped one, until it completes.
---
--- FIXME: Remove this global variable. It is only needed while `resumeStmt` is
--- synchronous, since `resumeStmt` currently tries to return the Eval result of
--- the main thread (which is a bit non-sensical for a resume operation to do).
--- It is only needed to preserve the previous behavior, but as soon as
--- `evalStmt` returns the sandboxIO thread id we can wait on that explicitly
--- instead of resuming having anything to do with waiting for the main
--- evaluation result.
-evaluationMainThreadGlobalVar :: TVar [MainThreadWithCtx]
-evaluationMainThreadGlobalVar = unsafePerformIO $ newTVarIO []
-{-# NOINLINE evaluationMainThreadGlobalVar #-}
-
--- | (Keep the ResumeContext to reduce allocations, triggered interpreter_steplocal regression)
-data MainThreadWithCtx = MainThreadWithCtx { mainKey :: !Word64, mainContext :: !ResumeContext }
-
-mkMainThreadWithContext :: ThreadId -> IO MainThreadWithCtx
-mkMainThreadWithContext tid = MainThreadWithCtx (fromThreadId tid) <$> getThreadResumeContext tid
-
--- | FIXME: Kill this function, just like 'evaluationMainThreadGlobalVar' will be killed.
-popMainThread :: MainThreadWithCtx -> STM ()
-popMainThread main =
- modifyTVar evaluationMainThreadGlobalVar (filter ((/= mainKey main) . mainKey))
-
=====================================
libraries/ghci/GHCi/Server.hs
=====================================
@@ -54,18 +54,17 @@ noCustomHandler _ _ = return Nothing
trace :: String -> IO ()
trace s = getProgName >>= \name -> hPrintf stderr "[%20s] %s\n" name s
-serv :: Bool -> MessageHook -> Pipe -> (forall a .IO a -> IO a) -> IO ()
-serv verbose hook pipe restore =
- servWithCustom verbose hook pipe restore noCustomHandler
+serv :: Bool -> MessageHook -> Pipe -> IO ()
+serv verbose hook pipe =
+ servWithCustom verbose hook pipe noCustomHandler
servWithCustom
:: Bool
-> MessageHook
-> Pipe
- -> (forall a. IO a -> IO a)
-> CustomMessageHandler
-> IO ()
-servWithCustom verbose hook pipe restore customHandler = do
+servWithCustom verbose hook pipe customHandler = do
ref <- newIORef False
withThreadManager $ \mngr -> handle @PipeClosedException (const $ pure ()) $ do
loop ref mngr `finally` closePipe pipe
@@ -75,7 +74,6 @@ servWithCustom verbose hook pipe restore customHandler = do
handleRemoteCall pipe hook $ \wr setCancel (msg :: Message a) ->
- discardCtrlC %>>= \_ ->
when verbose (trace ("msg: " ++ (show msg))) %>>= \_ ->
case msg of
@@ -83,12 +81,29 @@ servWithCustom verbose hook pipe restore customHandler = do
Shutdown -> writeIORef doneRef True >> closingPipe pipe >>
reply () %>>= \r ->
runWriteReply wr (Right r) ignorePipeClosedException
+
+ -- Run splices concurrently without blocking the server thread
RunTH ii st q ty loc -> handleAsync wr
- (restore $ wrapRunTH ii (runTH pipe ii st q ty loc))
+ (wrapRunTH ii (runTH pipe ii st q ty loc))
(setCancel . void . forkIO . killThread)
RunModFinalizers ii st qs -> handleAsync wr
- (restore $ wrapRunTH ii (runModFinalizerRefs pipe ii st qs))
+ (wrapRunTH ii (runModFinalizerRefs pipe ii st qs))
+ (setCancel . void . forkIO . killThread)
+
+ -- Wait off the main thread and reply asynchronously once ready. This
+ -- wait thread is killed if the wait request is cancelled, but a result
+ -- of the target thread can still be read e.g. with a follow-up wait.
+ -- If the target thread should be killed, see 'ThrowToThread'.
+ -- See Note [interpreter redirectInterrupts and signal handling] for both.
+ WaitThreadResult{} -> handleAsync wr
+ (run msg >>= reply)
+ (setCancel . void . forkIO . killThread)
+ -- Run throwTo off the main thread in case the user program behaves
+ -- "badly" wrt async exceptions.
+ ThrowToThread{} -> handleAsync wr
+ (run msg >>= reply)
(setCancel . void . forkIO . killThread)
+
_other -> run msg >>= reply %>>= writeReply wr
isDone <- readIORef doneRef
@@ -157,17 +172,6 @@ servWithCustom verbose hook pipe restore customHandler = do
Left e -> showException e
Right str -> return str
- -- throw away any pending ^C exceptions while we're not running
- -- interpreted code. GHC will also get the ^C, and either ignore it
- -- (if this is GHCi), or tell us to quit with a Shutdown message.
- discardCtrlC = do
- when verbose $ trace "discardCtrlC"
- r <- try $ restore $ return ()
- case r of
- Left UserInterrupt -> return () >> discardCtrlC
- Left e -> throwIO e
- _ -> return ()
-
-- | Default server
#if defined(wasm32_HOST_ARCH)
defaultServer :: Callback (JSVal -> IO ()) -> Callback (IO JSUint8Array) -> Callback (JSUint8Array -> IO ()) -> IO ()
@@ -212,12 +216,12 @@ defaultServerWithCustom customHandler = do
#if defined(wasm32_HOST_ARCH)
-- See Note [wasm ghci signal handlers] for details
- installSignalHandlers $ js_register_signal_handler cb_sig
+ ignoreInterrupts $ js_register_signal_handler cb_sig
pipe <- mkPipeFromContinuations (recv_buf cb_recv) (send_buf cb_send) (pure ()) (pure ())
#else
when verbose $
printf "GHC iserv starting (in: %s; out: %s)\n" (show inh) (show outh)
- installSignalHandlers
+ ignoreInterrupts
pipe <- mkPipeFromHandles inh outh
#endif
@@ -226,11 +230,9 @@ defaultServerWithCustom customHandler = do
putStrLn "Waiting 3s"
threadDelay 3000000
- uninterruptibleMask $ \restore -> servWithCustom verbose hook pipe restore customHandler
+ servWithCustom verbose hook pipe customHandler
where hook = return -- empty hook
- -- we cannot allow any async exceptions while communicating, because
- -- we will lose sync in the protocol, hence uninterruptibleMask.
dieWithUsage :: IO a
dieWithUsage = do
=====================================
libraries/ghci/GHCi/Signals.hs
=====================================
@@ -1,10 +1,7 @@
{-# LANGUAGE CPP #-}
-module GHCi.Signals (installSignalHandlers) where
+module GHCi.Signals (ignoreInterrupts) where
import Prelude -- See note [Why do we import Prelude here?]
-import Control.Concurrent
-import Control.Exception
-import System.Mem.Weak ( deRefWeak )
#if defined(wasm32_HOST_ARCH)
import GHC.Wasm.Prim
@@ -16,55 +13,34 @@ import System.Posix.Signals
import GHC.ConsoleHandler
#endif
--- | Install standard signal handlers for catching ^C, which just throw an
--- exception in the target thread. The current target thread is the
--- thread at the head of the list in the MVar passed to
--- installSignalHandlers.
+-- | Install standard signal handlers for catching ^C, which just ignore it.
+-- See Note [interpreter redirectInterrupts and signal handling].
#if defined(wasm32_HOST_ARCH)
-installSignalHandlers :: (JSVal -> IO ()) -> IO ()
-installSignalHandlers cb_sig = do
-#else
-installSignalHandlers :: IO ()
-installSignalHandlers = do
-#endif
- main_thread <- myThreadId
- wtid <- mkWeakThreadId main_thread
-
- let interrupt = do
- r <- deRefWeak wtid
- case r of
- Nothing -> return ()
- Just t -> throwTo t UserInterrupt
-
-#if defined(wasm32_HOST_ARCH)
- cb_sig =<< js_export_signal_handler interrupt
+ignoreInterrupts :: (JSVal -> IO ()) -> IO ()
+ignoreInterrupts cb_sig = do
+ -- See Note [wasm ghci signal handlers]
+ cb_sig =<< js_export_signal_handler (return ())
#elif !defined(mingw32_HOST_OS)
- _ <- installHandler sigQUIT (Catch interrupt) Nothing
- _ <- installHandler sigINT (Catch interrupt) Nothing
+ignoreInterrupts :: IO ()
+ignoreInterrupts = do
+ -- use `Catch (return ())` instead of `Ignore`, because `Ignore` gets
+ -- inherited by subprocesses the server may spawn.
+ _ <- installHandler sigQUIT (Catch (return ())) Nothing
+ _ <- installHandler sigINT (Catch (return ())) Nothing
+ return ()
#else
- -- GHC 6.3+ has support for console events on Windows
- -- NOTE: running GHCi under a bash shell for some reason requires
- -- you to press Ctrl-Break rather than Ctrl-C to provoke
- -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
- -- why --SDM 17/12/2004
- let sig_handler ControlC = interrupt
- sig_handler Break = interrupt
- sig_handler _ = return ()
-
- _ <- installHandler (Catch sig_handler)
-#endif
+ignoreInterrupts :: IO ()
+ignoreInterrupts = do
+ _ <- installHandler (Catch (\_ -> return ()))
return ()
+#endif
#if defined(wasm32_HOST_ARCH)
-
-- Note [wasm ghci signal handlers]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---
-- For native ghc with -fexternal-interpreter, when you press ^C,
--- SIGINT is delivered to both ghc/iserv. iserv SIGINT handler raises
--- an async UserInterrupt exception in the main thread, which might
--- handle it right away, or later since it's doing I/O under
--- uninterruptibleMask.
+-- SIGINT is delivered to both ghc/iserv. iserv SIGINT handler simply
+-- ignores the SIGINT (see Note [interpreter redirectInterrupts and signal handling]).
--
-- wasm is no different here. The node process needs to catch the same
-- signals. Instead of calling process.on('SIGINT', handler) in
@@ -73,15 +49,7 @@ installSignalHandlers = do
-- callback to register the handler. This allows iserv to be run in
-- non-nodejs environments as well, and the dyld script can pass a
-- handler register callback other than process.on().
---
--- IMPORTANT: THE SIGNAL HANDLER MUST BE EXPORTED AS ASYNC!!!!!!!
--- Otherwise, throwTo may block the handler thread, so the handler
--- thread is removed from the run queue. Since the main thread may
--- also be absent from the run queue (e.g. blocked on waiting for
--- input message), the run queue is empty and then the RTS scheduler
--- panics.
foreign import javascript "wrapper"
js_export_signal_handler :: IO () -> IO JSVal
-
#endif
=====================================
testsuite/tests/concurrent/should_run/all.T
=====================================
@@ -168,7 +168,11 @@ test('conc030', extra_run_opts('+RTS -K4M -RTS'), compile_and_run, [''])
test('conc031', exit_code(1), compile_and_run, [''])
test('conc032', normal, compile_and_run, [''])
-test('conc033', when(config.have_ext_interp, extra_ways(['ghci-ext'])), compile_and_run, [''])
+# You don't get any guarantee that the RTS ever throws a BlockedIndefinitely
+# exception, so it's fine if ghci doesn't throw one to the sandboxed thread.
+test('conc033', [when(config.have_ext_interp, extra_ways(['ghci-ext'])),
+ expect_fail_for(['ghci-ext'])],
+ compile_and_run, [''])
# Omit for GHCi, because it just sits there waiting for you to press ^C
test('conc034', [
=====================================
testsuite/tests/ghc-api/T8628.hs
=====================================
@@ -1,5 +1,6 @@
module Main where
+import Control.Monad (join)
import System.IO
import GHC.Driver.Session
import GHC
@@ -25,10 +26,10 @@ main
setContext [ IIDecl (simpleImportDecl pRELUDE_NAME)
, IIDecl (simpleImportDecl (mkModuleNameFS (fsLit "System.IO")))]
runDecls "data X = Y ()"
- execStmt "print True" execOptions
- MC.try $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult)
+ join $ execStmt "print True" execOptions
+ MC.try $ join $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult)
runDecls "data X = Y () deriving Show"
_ <- dynCompileExpr "'x'"
- execStmt "print (Y ())" execOptions
- execStmt "System.IO.hFlush System.IO.stdout" execOptions
+ join $ execStmt "print (Y ())" execOptions
+ join $ execStmt "System.IO.hFlush System.IO.stdout" execOptions
print "done"
=====================================
testsuite/tests/ghc-api/T8639_api.hs
=====================================
@@ -1,5 +1,6 @@
module Main where
+import Control.Monad (join)
import GHC
import GHC.Driver.Monad
import GHC.Driver.Ppr
@@ -20,8 +21,8 @@ main
-- With the next line, you get an "Not in scope" exception.
-- If you comment out this runStmt, it runs without error and prints the type.
- execStmt "putStrLn (show 3)" execOptions
- execStmt "hFlush stdout" execOptions
+ join $ execStmt "putStrLn (show 3)" execOptions
+ join $ execStmt "hFlush stdout" execOptions
ty <- exprType TM_Inst "T8639_api_a.it"
liftIO (putStrLn (showPpr flags ty))
=====================================
testsuite/tests/ghc-api/apirecomp001/myghc.hs
=====================================
@@ -50,7 +50,7 @@ main = do
setContext [IIModule mod]
liftIO $ hFlush stdout -- make sure things above are printed before
-- interactive output
- r <- execStmt "main" execOptions
+ r <- join $ execStmt "main" execOptions
case r of
ExecComplete { execResult = Right _ } -> prn "ok"
ExecComplete { execResult = Left _ } -> prn "exception"
=====================================
testsuite/tests/ghci.debugger/scripts/break050ext.stdout
=====================================
@@ -4,4 +4,3 @@ _result :: IO () = _
x :: Int = 0
forked thread: user interrupt
main was not interrupted
-Interrupted.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a7f092c07e2ba52870274afc1268b27…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a7f092c07e2ba52870274afc1268b27…
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/T28169] 3 commits: Add INLINE pragmas to tiny MCoercion functions
by Simon Peyton Jones (@simonpj) 29 Nov '26
by Simon Peyton Jones (@simonpj) 29 Nov '26
29 Nov '26
Simon Peyton Jones pushed to branch wip/T28169 at Glasgow Haskell Compiler / GHC
Commits:
36da5e74 by Simon Peyton Jones at 2026-11-28T23:47:01+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(a)anthropic.com>
- - - - -
e3d48dcf by Simon Peyton Jones at 2026-11-28T23:47:01+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. Fix: test `isLazyDataConRep`.
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.
New test T26548. T26615.stderr is regenerated (only its fEqList lines
are checked).
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
17559045 by Simon Peyton Jones at 2026-11-29T01:18:21+00:00
Make adjustFieldsIdInfo cheaper
Since the fix for #26548, adjustFieldsIdInfo takes its slow path for
every constructor with strict fields, which put T9233 (a record with
100 strict fields) up 2%. Make the slow path cheaper:
(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
Factor out fieldOccInfoStable, and replace adjustFieldOccInfo by the
simpler zapFieldOccInfo. The seq# case now uses the same `go` loop.
T9233 now allocates 0.6% less than master (it was 2.1% more), and
T9675 1.2% less.
T19641.stderr goes back to master's version (binder names only).
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
10 changed files:
- compiler/GHC/Core/Opt/Simplify/Inline.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Types/Demand.hs
- libraries/ghc-internal/src/GHC/Internal/IO.hs
- + testsuite/tests/simplCore/should_compile/T26548.hs
- + testsuite/tests/simplCore/should_compile/T26548.stderr
- testsuite/tests/simplCore/should_compile/T26615.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/Simplify/Inline.hs
=====================================
@@ -385,7 +385,7 @@ tryUnfolding env logger id lone_variable arg_infos
-- be *something* interesting about some argument, or the
-- result context, to make it worth inlining
calc_some_benefit :: Arity -> Bool -> Bool -- The Arity is the number of args
- -- expected by the unfolding
+ -- expected by the unfolding
calc_some_benefit uf_arity is_inline
| not saturated = interesting_args -- Under-saturated
-- Note [Unsaturated applications]
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -3557,7 +3557,8 @@ life" in one of two ways:
Thus, when we are simply reconstructing a case (the common case), and the
case binder is not dead, or the scrutinee is a variable, we zap the
-occurrence info on DataAlt field binders. See `adjustFieldOccInfo`.
+occurrence info on DataAlt field binders. See `fieldOccInfoStable`
+and `adjustFieldsIdInfo`.
Note [Improving seq]
~~~~~~~~~~~~~~~~~~~~
@@ -3765,70 +3766,81 @@ do it here). The right thing is to do some kind of binder-swap;
see #15226 for discussion.
-}
-adjustFieldsIdInfo :: Maybe OutExpr -> OutId -> BinderSwapDecision -> DataCon -> [Id] -> [Id]
+adjustFieldsIdInfo :: Maybe OutExpr -> OutId -> BinderSwapDecision
+ -> DataCon -> [InBndr] -> [InBndr]
-- See Note [Adding evaluatedness info to pattern-bound variables]
-- and Note [DataAlt occ info]
+--
+-- This can be a hot path in the compiler (e.g. T9233 which has a large strict record)
+-- Hence
+-- (a) we build the result list strictly: it is consumed in full right away,
+-- so thunks for the elements or the spine are pure waste
+-- (b) we update each field binder's IdInfo at most once
+-- (c) we leave alone a field binder that is dead and will stay dead
+-- (see `fieldOccInfoStable`); its evaluated-ness is irrelevant
adjustFieldsIdInfo scrut case_bndr bndr_swap con vs
+
-- Deal with seq# applications
+ -- See (SEQ3) in Note [seq# magic] in GHC.Types.Id.Make
+ -- case (seq# a b) of (# _, x' #) -> ....
+ -- we can mark x' as evaluated
| Just scr <- scrut
, isUnboxedTupleDataCon con
- , [s,x] <- vs
-- Use stripNArgs rather than collectArgsTicks to avoid building
-- a list of arguments only to throw it away immediately.
, Just (Var f) <- stripNArgs 4 scr
, f `hasKey` seqHashKey
- , let x' = setCaseBndrEvald MarkedStrict x
- = map (adjustFieldOccInfo case_bndr bndr_swap) [s, x']
-
- -- Deal with banged datacon fields
- -- This case is quite allocation sensitive to T9233 which has a large record
- -- with strict fields. Hence we try not to update vs twice!
-adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
- | Nothing <- dataConWrapId_maybe con
- -- A common fast path; no need to allocate the_strs when they are all lazy
- -- anyway! It shaves off 2% in T9675
- = map (adjustFieldOccInfo case_bndr bndr_swap) vs
+ = go vs [topDmd, evalDmd] -- seq# returns an evaluated x
+
+ -- General case
| otherwise
= go vs wkr_dmds
where
-- The demand signature of the worker has a strict demand for exactly the
- -- strict (banged) fields; one demand for each value argument, including
+ -- strict (banged) fields; one demand for each value argument, /including/
-- existential CoVars. See GHC.Types.Id.Make.mkDataConWorkId.
- -- NB: we do /not/ mark an unlifted field as evaluated: that gains nothing,
- -- and an OtherCon[] unfolding makes `interestingArg` say NonTrivArg,
- -- which changes inlining decisions (we saw this in compiler/perf/T19695).
+ -- NB: an unlifted field has a lazy demand, and hence won't be marked as
+ -- evaluated: doing so gains nothing. Not a big deal because `interestingArg`
+ -- says `TrivArg` for OtherCon[] unfoldings, but it's a bit delicate
+ -- (compiler/perf/T19695 is an example of this delicacy)
DmdSig (DmdType _ wkr_dmds) = idDmdSig (dataConWorkId con)
+ occ_stable = fieldOccInfoStable case_bndr bndr_swap
go [] [] = []
- go (v:vs') dmds | isTyVar v = v : go vs' dmds
- go (v:vs') (dmd:dmds) = adjustFieldOccInfo case_bndr bndr_swap (set_evald dmd v) : go vs' dmds
- go _ _ = pprPanic "Simplify.adjustFieldsIdInfo"
- (ppr con $$
- ppr vs $$
- ppr_with_length wkr_dmds $$
- ppr_with_length (dataConRepArgTys con))
- where
- ppr_with_length list
- = ppr list <+> parens (text "length =" <+> ppr (length list))
-
- set_evald dmd v | isStrDataConDmd dmd = setCaseBndrEvald MarkedStrict v
- | otherwise = v
-
-adjustFieldOccInfo :: OutId -> BinderSwapDecision -> CoreBndr -> CoreBndr
--- Kill occ info if we do binder swap and the case binder is alive;
--- see Note [DataAlt occ info]
-adjustFieldOccInfo case_bndr bndr_swap field_bndr
- | isTyVar field_bndr
- = field_bndr
-
- | not (isDeadBinder case_bndr) -- (1) in the Note: If the case binder is alive,
- = zapIdOccInfo field_bndr -- the field binders might come back alive
-
- | DoBinderSwap{} <- bndr_swap -- (2) in the Note: If binder swap might take place,
- = zapIdOccInfo field_bndr -- the case binder might come back alive
-
- | otherwise
- = field_bndr -- otherwise the field binders stay dead
+ go (v:vs') dmds@(dmd:dmds')
+ | isTyVar v = let !vs'' = go vs' dmds in v : vs''
+ | otherwise = let !v' = adjust dmd v
+ !vs'' = go vs' dmds'
+ in v' : vs''
+ go vs' ds = pprPanic "Simplify.adjustFieldsIdInfo" (ppr con $$ ppr vs $$ ppr vs' $$ ppr ds)
+
+ -- Set evaluated-ness (if dmd is strict) and zap occ-info
+ -- (if not occ_stable), with at most one IdInfo update
+ adjust :: Demand -> Id -> Id
+ adjust dmd v
+ = case isStrDataConDmd dmd of
+ True | occ_stable -> if isDeadBinder v then nop v else set_evald v
+ | otherwise -> set_evald_zap_occ v
+ False | occ_stable -> nop v
+ | otherwise -> zap_occ v
+
+ nop v = v
+ set_evald v = v `setIdUnfolding` evaldUnfolding
+ zap_occ v = zapIdOccInfo v
+ set_evald_zap_occ v = modifyIdInfo (\info -> info `setUnfoldingInfo` evaldUnfolding
+ `setOccInfo` noOccInfo) v
+
+fieldOccInfoStable :: OutId -> BinderSwapDecision -> Bool
+-- True <=> the occ-info on the field binders of a DataAlt remains valid;
+-- in particular a dead field binder will stay dead.
+-- False <=> we must zap the field binders' occ-info.
+-- See Note [DataAlt occ info]
+fieldOccInfoStable case_bndr bndr_swap
+ | not (isDeadBinder case_bndr) = False -- (1) in the Note: If the case binder is alive,
+ -- the field binders might come back alive
+ | DoBinderSwap{} <- bndr_swap = False -- (2) in the Note: If binder swap might take place,
+ -- the case binder might come back alive
+ | otherwise = True -- Otherwise the field binders stay dead
addDefaultUnfoldings :: SimplEnv -> OutId -> BinderSwapDecision -> [AltCon] -> SimplEnv
addDefaultUnfoldings env case_bndr bndr_swap imposs_deflt_cons
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -1123,7 +1123,7 @@ interestingCallContext env cont
-- in GHC.Core.Unfold
interesting (StrictArg { sc_fun = fun }) = strictArgContext fun
- interesting (StrictBind {}) = BoringCtxt
+ interesting (StrictBind {}) = RhsCtxt NonRecursive
interesting (Stop _ cci _) = cci
interesting (TickIt _ k) = interesting k
interesting (ApplyToTy { sc_cont = k }) = interesting k
@@ -1208,13 +1208,29 @@ Wrinkles:
(IA2) OtherCon.
interestingArg returns
- (a) NonTrivArg for an arg with an OtherCon [] unfolding
+ (a) TrivArg for an arg with an OtherCon [] unfolding
(b) ValueArg for an arg with an OtherCon [c1,c2..] unfolding.
- Reason for (a): I found (in the GHC.Internal.Bignum.Integer module) that I was
- inlining a pretty big function when all we knew was that its arguments
- were evaluated, nothing more. That in turn make the enclosing function
- too big to inline elsewhere.
+ Reason for (a): knowing only that an argument is evaluated, but not which
+ constructor it is, rarely makes inlining worthwhile. For example, in test
+ T18140 we have
+ data D = D !(Maybe Bool) ... !(Maybe Bool)
+ maMB :: Maybe Bool -> Maybe Bool -> Maybe Bool
+ maD (D x1 ... x18) (D y1 ... y18) = D (maMB x1 y1) ... (maMB x18 y18)
+ The xi and yi come from strict fields, so they have OtherCon [] unfoldings.
+ If that made them interesting we would inline maMB 18 times, to no benefit,
+ just bloating maD. (Similarly, in GHC.Internal.Bignum.Integer I found that
+ I was inlining a pretty big function when all we knew was that its
+ arguments were evaluated. That in turn made the enclosing function too big
+ to inline elsewhere.)
+
+ But this choice is delicate. Sometimes inlining a tiny function applied to
+ an evaluated argument /is/ very beneficial, because the /result/ is
+ scrutinised downstream; mkSymMCo in the type-family rewriter is an example.
+ Neither the argument nor the call context reveals this, so in those cases
+ we use an INLINE pragma: see Note [Inline tiny MCo functions] in
+ GHC.Core.TyCo.Make. (Without those INLINE pragmas, returning TrivArg here
+ makes the compiler itself slower: T9872{a,b,c,d} allocate ~2.5% more.)
Reason for (b): we want to inline integerCompare here
integerLt# :: Integer -> Integer -> Bool#
@@ -1247,6 +1263,25 @@ Wrinkles:
Conclusion: `interestingArg` should give some encouragement (NonTrivArg) to `f`
when the argument is expandable. Hence `uf_expandable` in the `Var` case.
+(IA5) We are keen to inline a higher-order function applied to lambda, e.g.
+ f (\x. blah)
+ where
+ f h = ...(h xs)...
+ Doing so specialises `f` to the particular argument which can make a
+ big difference. Note, however, that we don't want to be defeated if
+ the lambda is let-bound:
+ let h = (\x.blah)
+ in ...f h...
+ So we need to look through h's unfolding.
+
+ This makes parser combinators, which are usually applied to functions,
+ rather keen to inline, so whether they do so is mostly decided by their
+ size. Test T17516 is a delicate example: if `max` on positions inlines
+ into the combinators in T17516A, the combinators are too big to inline into
+ the client module T17516; if not (because max's arguments are merely
+ evaluated, see (IA2)), they are small and do inline, making T17516 itself
+ slower to compile. But inlining makes the code better too, with fewer
+ unknown calls.
-}
interestingArg :: SimplEnv -> StaticEnv -> CoreExpr -> ArgSummary
@@ -1275,7 +1310,7 @@ interestingArg env se e
go env n (Lam v e)
| isTyVar v = go env n e
| n>0 = NonTrivArg -- (\x.b) e is NonTriv
- | otherwise = ValueArg
+ | otherwise = ValueArg -- (\x.b) is Value: see (IA5)
go _ _ (Case {}) = NonTrivArg
go env n (Let b e) = case go env' n e of
ValueArg -> ValueArg
@@ -1285,17 +1320,16 @@ interestingArg env se e
go_var n v
| isConLikeId v = ValueArg -- Experimenting with 'conlike' rather that
- -- data constructors here
- -- DFuns are con-like;
+ -- data constructors here (includes DFuns)
-- see (IA1) in Note [Interesting arguments]
- | idArity v > n = ValueArg -- Catches (eg) primops with arity but no unfolding
+ | idArity v > n = ValueArg -- See (IA5) in Note [Interesting arguments]
| n > 0 = NonTrivArg -- Saturated or unknown call
| otherwise -- n==0, no value arguments; look for an interesting unfolding
= case idUnfolding v of
- OtherCon [] -> NonTrivArg -- It's evaluated, but that's all we know
+ OtherCon [] -> TrivArg -- It's evaluated, but that's all we know
OtherCon _ -> ValueArg -- Evaluated and we know it isn't these constructors
- -- See (IA2) in Note [Interesting arguments]
- DFunUnfolding {} -> ValueArg -- We konw that idArity=0
+ -- See (IA2) in Note [Interesting arguments]
+ DFunUnfolding {} -> ValueArg -- We know that idArity=0
CoreUnfolding{ uf_cache = cache }
| uf_is_conlike cache -> ValueArg -- Includes constructor applications
| uf_expandable cache -> NonTrivArg -- See (IA4)
=====================================
compiler/GHC/Core/TyCo/Make.hs
=====================================
@@ -1322,42 +1322,88 @@ mkGReflCo r ty mco
mkGReflMCo :: HasDebugCallStack => Role -> Type -> CoercionN -> Coercion
mkGReflMCo r ty co = mkGReflCo r ty (MCo co)
+{- Note [Inline tiny MCo functions]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The MCoercion functions (mkSymMCo, mkCastTyMCo, mkCoherenceRightMCo, etc.)
+are tiny wrappers whose whole purpose is the fast path for MRefl. We give
+them INLINE pragmas, rather than relying on the inliner's heuristics, because
+the benefit of inlining them is usually invisible at the call site.
+
+Example: homogeniseHetRedn (in GHC.Core.Reduction) is used in the type-family
+rewriter. After inlining it and mkCoherenceRightMRedn (both INLINE) we get
+something like
+ let kco' = mkSymMCo kco
+ in Reduction (mkCoherenceRightMCo r ty2 kco' co1)
+ (mkCastTyMCo ty2 kco')
+where `kco` is typically already evaluated (has an OtherCon [] unfolding),
+but its constructor is unknown. `kco'` is used twice, so it is not inlined
+at its use sites; and its RHS is a boring context for a non-INLINE function.
+So, judged by its argument and context alone, `mkSymMCo kco` has no
+discernible benefit, and does not inline. But if it does inline, case-of-case
+moves the (cheap) `case kco` outwards, and the two consumers become
+case-of-known-constructor:
+ case kco of
+ MRefl -> Reduction co1 ty2 -- No allocation at all
+ MCo co -> ...
+Kind coercions are usually reflexive, so this MRefl path is the hot one.
+The benefit comes entirely from the downstream consumers of the result.
+
+Why not just make interestingArg regard an evaluated (OtherCon []) argument as
+interesting? Because in exactly the same situation it causes useless
+inlining: see `maMB` in test T18140, where the arguments come from strict
+fields and the result goes into a constructor field. See (IA2) in
+Note [Interesting arguments] in GHC.Core.Opt.Simplify.Utils.
+
+Being tiny, these functions cost little to inline even when nothing is known
+about the argument. Without these pragmas, tests T9872{a,b,c,d} and
+TcPlugin_RewritePerf allocated around 2.5% more (Nov 2026), almost all of it
+due to out-of-line calls of mkSymMCo from GHC.Tc.Solver.Rewrite.
+-}
+
-- | Compose two MCoercions via transitivity
mkTransMCo :: MCoercion -> MCoercion -> MCoercion
mkTransMCo MRefl co2 = co2
mkTransMCo co1 MRefl = co1
mkTransMCo (MCo co1) (MCo co2) = MCo (mkTransCo co1 co2)
+{-# INLINE mkTransMCo #-} -- See Note [Inline tiny MCo functions]
mkTransMCoL :: MCoercion -> Coercion -> MCoercion
mkTransMCoL MRefl co2 = coToMCo co2
mkTransMCoL (MCo co1) co2 = MCo (mkTransCo co1 co2)
+{-# INLINE mkTransMCoL #-} -- See Note [Inline tiny MCo functions]
mkTransMCoR :: Coercion -> MCoercion -> MCoercion
mkTransMCoR co1 MRefl = coToMCo co1
mkTransMCoR co1 (MCo co2) = MCo (mkTransCo co1 co2)
+{-# INLINE mkTransMCoR #-} -- See Note [Inline tiny MCo functions]
-- | Get the reverse of an 'MCoercion'
mkSymMCo :: MCoercion -> MCoercion
mkSymMCo MRefl = MRefl
mkSymMCo (MCo co) = MCo (mkSymCo co)
+{-# INLINE mkSymMCo #-} -- See Note [Inline tiny MCo functions]
-- | Cast a type by an 'MCoercion'
mkCastTyMCo :: Type -> MCoercion -> Type
mkCastTyMCo ty MRefl = ty
mkCastTyMCo ty (MCo co) = ty `mkCastTy` co
+{-# INLINE mkCastTyMCo #-} -- See Note [Inline tiny MCo functions]
mkGReflLeftMCo :: Role -> Type -> MCoercionN -> Coercion
mkGReflLeftMCo r ty MRefl = mkReflCo r ty
mkGReflLeftMCo r ty (MCo co) = mkGReflLeftCo r ty co
+{-# INLINE mkGReflLeftMCo #-} -- See Note [Inline tiny MCo functions]
mkGReflRightMCo :: Role -> Type -> MCoercionN -> Coercion
mkGReflRightMCo r ty MRefl = mkReflCo r ty
mkGReflRightMCo r ty (MCo co) = mkGReflRightCo r ty co
+{-# INLINE mkGReflRightMCo #-} -- See Note [Inline tiny MCo functions]
-- | Like 'mkCoherenceRightCo', but with an 'MCoercion'
mkCoherenceRightMCo :: Role -> Type -> MCoercionN -> Coercion -> Coercion
mkCoherenceRightMCo _ _ MRefl co2 = co2
mkCoherenceRightMCo r ty (MCo co) co2 = mkCoherenceRightCo r ty co co2
+{-# INLINE mkCoherenceRightMCo #-} -- See Note [Inline tiny MCo functions]
isReflMCo :: MCoercion -> Bool
isReflMCo MRefl = True
=====================================
compiler/GHC/Types/Demand.hs
=====================================
@@ -1003,9 +1003,10 @@ isStrUsedDmd :: Demand -> Bool
isStrUsedDmd (n :* _) = isStrict n && not (isAbs n)
-- | Is this demand, taken from the demand signature of a data constructor
--- /worker/, the demand for a strict field? The demands in a worker's
--- signature are never absent (see GHC.Types.Id.Make.mkDataConWorkId), so
--- unlike 'isStrUsedDmd' we don't need to check for absence.
+-- /worker/, the demand for a strict field? It would be more obviously correct
+-- to use isStrUsedDmd, in case the dmd is Absent. But data constructor workers
+-- never have absent arguments, and isStrictDmd is more efficient.
+-- See GHC.Types.Id.Make.mkDataConWorkId.
isStrDataConDmd :: Demand -> Bool
isStrDataConDmd = isStrictDmd
=====================================
libraries/ghc-internal/src/GHC/Internal/IO.hs
=====================================
@@ -483,7 +483,7 @@ a `finally` sequel =
-- | The primitive used to implement 'GHC.IO.evaluate'.
-- Prefer to use 'GHC.IO.evaluate' whenever possible!
seq# :: forall a s. a -> State# s -> (# State# s, a #)
--- See Note [seq# magic] in GHC.Types.Id.Make
+-- See Note [seq# magic] in GHC.Builtin.WiredIn.Ids
{-# NOINLINE seq# #-} -- seq# is inlined manually in CorePrep
seq# a s = let !a' = lazy a in (# s, a' #)
=====================================
testsuite/tests/simplCore/should_compile/T26548.hs
=====================================
@@ -0,0 +1,7 @@
+module T26548 where
+
+newtype N a = MkN (Maybe a)
+data T = MkT !(N Int) !(N Bool)
+
+f x = case x of { MkT a b ->
+ case x of { MkT c d -> MkT a d } }
=====================================
testsuite/tests/simplCore/should_compile/T26548.stderr
=====================================
@@ -0,0 +1,19 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 3, types: 3, coercions: 0, joins: 0/0}
+
+-- RHS size: {terms: 2, types: 1, coercions: 0, joins: 0/0}
+f :: T -> T
+[GblId,
+ Arity=1,
+ Str=<1!P(L,L)>,
+ Cpr=1,
+ Unf=Unf{Src=StableSystem, TopLvl=True,
+ Value=True, ConLike=True, WorkFree=True, Expandable=True,
+ Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=True)
+ Tmpl= \ (x [Occ=Once1] :: T) -> x}]
+f = \ (x :: T) -> x
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/T26615.stderr
=====================================
@@ -2,7 +2,7 @@
==================== Tidy Core ====================
Result size of Tidy Core
- = {terms: 1,229, types: 1,163, coercions: 18, joins: 17/29}
+ = {terms: 1,220, types: 1,160, coercions: 18, joins: 17/29}
-- RHS size: {terms: 6, types: 8, coercions: 0, joins: 0/0}
unArray :: forall a. Array a -> SmallArray# a
@@ -107,7 +107,7 @@ T26615a.$tcLeaf
T26615a.$trModule
$tcLeaf2
0#
- GHC.Internal.Types.krep$*->*->*
+ krepStarArrStarArr
-- RHS size: {terms: 3, types: 2, coercions: 0, joins: 0/0}
$krep7 :: [GHC.Internal.Types.KindRep]
@@ -181,7 +181,7 @@ T26615a.$tcArray
T26615a.$trModule
$tcArray2
0#
- GHC.Internal.Types.krep$*Arr*
+ krepStarArr
-- RHS size: {terms: 3, types: 0, coercions: 0, joins: 0/0}
$krep12 :: GHC.Internal.Types.KindRep
@@ -251,7 +251,7 @@ T26615a.$tcHashMap
T26615a.$trModule
$tcHashMap2
0#
- GHC.Internal.Types.krep$*->*->*
+ krepStarArrStarArr
-- RHS size: {terms: 3, types: 0, coercions: 0, joins: 0/0}
$krep16 :: GHC.Internal.Types.KindRep
@@ -612,7 +612,7 @@ lvl1
= GHC.Internal.Control.Exception.Base.patError @LiftedRep @() lvl
Rec {
--- RHS size: {terms: 136, types: 130, coercions: 0, joins: 1/2}
+-- RHS size: {terms: 133, types: 129, coercions: 0, joins: 1/2}
T26615a.disjointSubtrees_$s$wdisjointSubtrees [InlPrag=INLINABLE[2],
Occ=LoopBreaker]
:: forall k a b.
@@ -635,7 +635,6 @@ T26615a.disjointSubtrees_$s$wdisjointSubtrees
Empty -> GHC.Internal.Types.True;
Leaf bx ds ->
case ds of { L kB ds1 ->
- case kB of k0 { __DEFAULT ->
case eqWord# bx sc2 of {
__DEFAULT -> GHC.Internal.Types.True;
1# ->
@@ -668,8 +667,7 @@ T26615a.disjointSubtrees_$s$wdisjointSubtrees
}
}; } in
jump $wlookupInArrayCont_
- sc k0 sc3 0# (sizeofSmallArray# @Lifted @(Leaf k a) sc3)
- }
+ sc kB sc3 0# (sizeofSmallArray# @Lifted @(Leaf k a) sc3)
}
};
Collision bx bx1 ->
@@ -710,7 +708,7 @@ T26615a.disjointSubtrees_$s$wdisjointSubtrees
end Rec }
Rec {
--- RHS size: {terms: 719, types: 748, coercions: 18, joins: 13/23}
+-- RHS size: {terms: 713, types: 746, coercions: 18, joins: 13/23}
T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
:: forall k a b. Eq k => Int# -> HashMap k a -> HashMap k b -> Bool
[GblId[StrictWorker([~, ~, !])],
@@ -740,7 +738,6 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
Empty -> GHC.Internal.Types.True;
Leaf bx [Occ=Once1] ds2 [Occ=Once1!] ->
case ds2 of { L kB [Occ=Once1] _ [Occ=Dead] ->
- case kB of k0 [Occ=Once1] { __DEFAULT ->
joinrec {
lookupCont_ [Occ=LoopBreakerT[5]]
:: Eq k => Word -> k -> Int -> HashMap k a -> Bool
@@ -868,8 +865,7 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
}
}; } in
jump lookupCont_
- $dEq (GHC.Internal.Types.W# bx) k0 (GHC.Internal.Types.I# ww) ds
- }
+ $dEq (GHC.Internal.Types.W# bx) kB (GHC.Internal.Types.I# ww) ds
};
Collision _ [Occ=Dead] _ [Occ=Dead] ->
T26615a.$wdisjointSubtrees @k @b @a $dEq ww wild ds
@@ -880,7 +876,6 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
case ds1 of { L kA [Occ=Once2] _ [Occ=Dead] ->
case _b of wild2 [Occ=Once1] {
__DEFAULT ->
- case kA of k0 [Occ=Once1] { __DEFAULT ->
joinrec {
lookupCont_ [Occ=LoopBreakerT[5]]
:: Eq k => Word -> k -> Int -> HashMap k b -> Bool
@@ -1004,8 +999,11 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
}
}; } in
jump lookupCont_
- $dEq (GHC.Internal.Types.W# bx) k0 (GHC.Internal.Types.I# ww) wild2
- };
+ $dEq
+ (GHC.Internal.Types.W# bx)
+ kA
+ (GHC.Internal.Types.I# ww)
+ wild2;
Leaf bx1 [Occ=Once1] ds3 [Occ=Once1!] ->
case ds3 of { L kB [Occ=Once1] _ [Occ=Dead] ->
case GHC.Internal.Classes.neWord
@@ -1091,13 +1089,14 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<L>, Unf=OtherCon []]
go (ds1 [Occ=Once1!] :: Word)
= case ds1 of { W# ds2 [Occ=Once1!] ->
- case ds2 of ds3 {
+ case ds2 of wild5 {
__DEFAULT ->
let {
m :: Word#
[LclId]
m = and#
- ds3 (int2Word# (negateInt# (word2Int# ds3))) } in
+ wild5
+ (int2Word# (negateInt# (word2Int# wild5))) } in
case indexSmallArray#
@Lifted
@(HashMap k a)
@@ -1118,7 +1117,7 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
of {
False -> GHC.Internal.Types.False;
True ->
- jump go (GHC.Internal.Types.W# (and# ds3 (not# m)))
+ jump go (GHC.Internal.Types.W# (and# wild5 (not# m)))
}
}
};
@@ -1137,12 +1136,12 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<L>, Unf=OtherCon []]
go (ds1 [Occ=Once1!] :: Word)
= case ds1 of { W# ds2 [Occ=Once1!] ->
- case ds2 of ds3 {
+ case ds2 of wild3 {
__DEFAULT ->
let {
m :: Word#
[LclId]
- m = and# ds3 (int2Word# (negateInt# (word2Int# ds3))) } in
+ m = and# wild3 (int2Word# (negateInt# (word2Int# wild3))) } in
case indexSmallArray#
@Lifted
@(HashMap k a)
@@ -1161,7 +1160,7 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
case T26615a.$wdisjointSubtrees @k @a @b $dEq (+# ww 5#) ipv ipv1
of {
False -> GHC.Internal.Types.False;
- True -> jump go (GHC.Internal.Types.W# (and# ds3 (not# m)))
+ True -> jump go (GHC.Internal.Types.W# (and# wild3 (not# m)))
}
}
};
@@ -1179,12 +1178,12 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<L>, Unf=OtherCon []]
go (ds1 [Occ=Once1!] :: Word)
= case ds1 of { W# ds2 [Occ=Once1!] ->
- case ds2 of ds3 {
+ case ds2 of wild3 {
__DEFAULT ->
let {
m :: Word#
[LclId]
- m = and# ds3 (int2Word# (negateInt# (word2Int# ds3))) } in
+ m = and# wild3 (int2Word# (negateInt# (word2Int# wild3))) } in
case indexSmallArray#
@Lifted
@(HashMap k a)
@@ -1203,7 +1202,7 @@ T26615a.$wdisjointSubtrees [InlPrag=INLINABLE[2], Occ=LoopBreaker]
case T26615a.$wdisjointSubtrees @k @a @b $dEq (+# ww 5#) ipv ipv1
of {
False -> GHC.Internal.Types.False;
- True -> jump go (GHC.Internal.Types.W# (and# ds3 (not# m)))
+ True -> jump go (GHC.Internal.Types.W# (and# wild3 (not# m)))
}
}
};
@@ -1277,7 +1276,6 @@ T26615a.$wdisjointSubtrees
Empty -> GHC.Internal.Types.True;
Leaf bx ds2 ->
case ds2 of { L kB ds3 ->
- case kB of k0 { __DEFAULT ->
join {
exit [Dmd=LC(S,C(1,C(1,C(1,L))))]
:: Word# -> k -> Word# -> Leaf k a -> Bool
@@ -1392,8 +1390,7 @@ T26615a.$wdisjointSubtrees
}
}
}; } in
- jump $wlookupCont_ $dEq bx k0 ww ds
- }
+ jump $wlookupCont_ $dEq bx kB ww ds
};
Collision bx bx1 ->
T26615a.disjointSubtrees_$s$wdisjointSubtrees
@@ -1405,7 +1402,6 @@ T26615a.$wdisjointSubtrees
case ds1 of { L kA ds2 ->
case _b of wild2 {
__DEFAULT ->
- case kA of k0 { __DEFAULT ->
join {
exit [Dmd=LC(S,C(1,C(1,C(1,L))))]
:: Word# -> k -> Word# -> Leaf k b -> Bool
@@ -1519,8 +1515,7 @@ T26615a.$wdisjointSubtrees
}
}
}; } in
- jump $wlookupCont_ $dEq bx k0 ww wild2
- };
+ jump $wlookupCont_ $dEq bx kA ww wild2;
Leaf bx1 ds3 ->
case ds3 of { L kB ds4 ->
case neWord# bx bx1 of {
@@ -1604,12 +1599,12 @@ T26615a.$wdisjointSubtrees
$wgo [InlPrag=[2], Occ=LoopBreaker, Dmd=SC(S,L)] :: Word# -> Bool
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<1L>, Unf=OtherCon []]
$wgo (ww1 :: Word#)
- = case ww1 of ds1 {
+ = case ww1 of wild4 {
__DEFAULT ->
let {
m :: Word#
[LclId]
- m = and# ds1 (int2Word# (negateInt# (word2Int# ds1))) } in
+ m = and# wild4 (int2Word# (negateInt# (word2Int# wild4))) } in
case indexSmallArray#
@Lifted
@(HashMap k a)
@@ -1626,7 +1621,7 @@ T26615a.$wdisjointSubtrees
{ (# ipv1 #) ->
case T26615a.$wdisjointSubtrees @k @a @b $dEq lvl2 ipv ipv1 of {
False -> GHC.Internal.Types.False;
- True -> jump $wgo (and# ds1 (not# m))
+ True -> jump $wgo (and# wild4 (not# m))
}
}
};
@@ -1647,12 +1642,12 @@ T26615a.$wdisjointSubtrees
$wgo [InlPrag=[2], Occ=LoopBreaker, Dmd=SC(S,L)] :: Word# -> Bool
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<1L>, Unf=OtherCon []]
$wgo (ww1 :: Word#)
- = case ww1 of ds1 {
+ = case ww1 of wild2 {
__DEFAULT ->
let {
m :: Word#
[LclId]
- m = and# ds1 (int2Word# (negateInt# (word2Int# ds1))) } in
+ m = and# wild2 (int2Word# (negateInt# (word2Int# wild2))) } in
case indexSmallArray#
@Lifted
@(HashMap k a)
@@ -1669,7 +1664,7 @@ T26615a.$wdisjointSubtrees
{ (# ipv1 #) ->
case T26615a.$wdisjointSubtrees @k @a @b $dEq lvl2 ipv ipv1 of {
False -> GHC.Internal.Types.False;
- True -> jump $wgo (and# ds1 (not# m))
+ True -> jump $wgo (and# wild2 (not# m))
}
}
};
@@ -1689,12 +1684,12 @@ T26615a.$wdisjointSubtrees
$wgo [InlPrag=[2], Occ=LoopBreaker, Dmd=SC(S,L)] :: Word# -> Bool
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<1L>, Unf=OtherCon []]
$wgo (ww1 :: Word#)
- = case ww1 of ds1 {
+ = case ww1 of wild2 {
__DEFAULT ->
let {
m :: Word#
[LclId]
- m = and# ds1 (int2Word# (negateInt# (word2Int# ds1))) } in
+ m = and# wild2 (int2Word# (negateInt# (word2Int# wild2))) } in
case indexSmallArray#
@Lifted
@(HashMap k a)
@@ -1711,7 +1706,7 @@ T26615a.$wdisjointSubtrees
{ (# ipv1 #) ->
case T26615a.$wdisjointSubtrees @k @a @b $dEq lvl2 ipv ipv1 of {
False -> GHC.Internal.Types.False;
- True -> jump $wgo (and# ds1 (not# m))
+ True -> jump $wgo (and# wild2 (not# m))
}
}
};
@@ -1845,32 +1840,7 @@ disjointSubtrees
==================== Tidy Core ====================
Result size of Tidy Core
- = {terms: 622, types: 674, coercions: 18, joins: 8/14}
-
--- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
-$trModule1 :: GHC.Internal.Prim.Addr#
-[GblId, Unf=OtherCon []]
-$trModule1 = "T26615"#
-
--- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
-$trModule2 :: GHC.Internal.Types.TrName
-[GblId, Unf=OtherCon []]
-$trModule2 = GHC.Internal.Types.TrNameS $trModule1
-
--- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
-$trModule3 :: GHC.Internal.Prim.Addr#
-[GblId, Unf=OtherCon []]
-$trModule3 = "main"#
-
--- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
-$trModule4 :: GHC.Internal.Types.TrName
-[GblId, Unf=OtherCon []]
-$trModule4 = GHC.Internal.Types.TrNameS $trModule3
-
--- RHS size: {terms: 3, types: 0, coercions: 0, joins: 0/0}
-T26615.$trModule [InlPrag=[~]] :: GHC.Internal.Types.Module
-[GblId, Unf=OtherCon []]
-T26615.$trModule = GHC.Internal.Types.Module $trModule4 $trModule2
+ = {terms: 603, types: 666, coercions: 18, joins: 8/14}
-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
lvl :: GHC.Internal.Prim.Addr#
@@ -2029,7 +1999,7 @@ $wpoly_lookupCont_
end Rec }
Rec {
--- RHS size: {terms: 450, types: 507, coercions: 18, joins: 8/13}
+-- RHS size: {terms: 445, types: 504, coercions: 18, joins: 8/13}
T26615.$s$wdisjointSubtrees [InlPrag=[~], Occ=LoopBreaker]
:: forall a b.
GHC.Internal.Prim.Int#
@@ -2067,11 +2037,7 @@ T26615.$s$wdisjointSubtrees
T26615a.Leaf bx1 ds3 ->
case ds3 of { T26615a.L kB ds4 ->
case GHC.Internal.Prim.neWord# bx bx1 of {
- __DEFAULT ->
- case GHC.Internal.Classes.$fEqList_$s$c==1 kA kB of {
- False -> GHC.Internal.Types.True;
- True -> GHC.Internal.Types.False
- };
+ __DEFAULT -> GHC.Internal.Classes.$fEqList_$s$c/=1 kA kB;
1# -> GHC.Internal.Types.True
}
}
@@ -2094,14 +2060,14 @@ T26615.$s$wdisjointSubtrees
$s$wfoldr_ [InlPrag=[2],
Occ=LoopBreaker,
Dmd=SC(S,C(1,C(1,C(1,L))))]
- :: GHC.Internal.Prim.SmallArray# (T26615a.Leaf [Char] a)
+ :: GHC.Internal.Prim.SmallArray# (T26615a.Leaf String a)
-> GHC.Internal.Prim.Int# -> GHC.Internal.Prim.Int# -> Bool -> Bool
[LclId[JoinId(4)(Nothing)],
Arity=4,
Str=<L><L><L><L>,
Unf=OtherCon []]
$s$wfoldr_ (sc
- :: GHC.Internal.Prim.SmallArray# (T26615a.Leaf [Char] a))
+ :: GHC.Internal.Prim.SmallArray# (T26615a.Leaf String a))
(sc1 :: GHC.Internal.Prim.Int#)
(sc2 :: GHC.Internal.Prim.Int#)
(sc3 :: Bool)
@@ -2243,16 +2209,16 @@ T26615.$s$wdisjointSubtrees
:: GHC.Internal.Prim.Word# -> Bool
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<1L>, Unf=OtherCon []]
$wgo (ww1 :: GHC.Internal.Prim.Word#)
- = case ww1 of ds3 {
+ = case ww1 of wild5 {
__DEFAULT ->
let {
m :: GHC.Internal.Prim.Word#
[LclId]
m = GHC.Internal.Prim.and#
- ds3
+ wild5
(GHC.Internal.Prim.int2Word#
(GHC.Internal.Prim.negateInt#
- (GHC.Internal.Prim.word2Int# ds3))) } in
+ (GHC.Internal.Prim.word2Int# wild5))) } in
case GHC.Internal.Prim.indexSmallArray#
@GHC.Internal.Types.Lifted
@(HashMap String a)
@@ -2279,7 +2245,7 @@ T26615.$s$wdisjointSubtrees
False -> GHC.Internal.Types.False;
True ->
jump $wgo
- (GHC.Internal.Prim.and# ds3 (GHC.Internal.Prim.not# m))
+ (GHC.Internal.Prim.and# wild5 (GHC.Internal.Prim.not# m))
}
}
};
@@ -2297,16 +2263,16 @@ T26615.$s$wdisjointSubtrees
:: GHC.Internal.Prim.Word# -> Bool
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<1L>, Unf=OtherCon []]
$wgo (ww1 :: GHC.Internal.Prim.Word#)
- = case ww1 of ds3 {
+ = case ww1 of wild3 {
__DEFAULT ->
let {
m :: GHC.Internal.Prim.Word#
[LclId]
m = GHC.Internal.Prim.and#
- ds3
+ wild3
(GHC.Internal.Prim.int2Word#
(GHC.Internal.Prim.negateInt#
- (GHC.Internal.Prim.word2Int# ds3))) } in
+ (GHC.Internal.Prim.word2Int# wild3))) } in
case GHC.Internal.Prim.indexSmallArray#
@GHC.Internal.Types.Lifted
@(HashMap String a)
@@ -2332,7 +2298,7 @@ T26615.$s$wdisjointSubtrees
of {
False -> GHC.Internal.Types.False;
True ->
- jump $wgo (GHC.Internal.Prim.and# ds3 (GHC.Internal.Prim.not# m))
+ jump $wgo (GHC.Internal.Prim.and# wild3 (GHC.Internal.Prim.not# m))
}
}
};
@@ -2349,16 +2315,16 @@ T26615.$s$wdisjointSubtrees
:: GHC.Internal.Prim.Word# -> Bool
[LclId[JoinId(1)(Nothing)], Arity=1, Str=<1L>, Unf=OtherCon []]
$wgo (ww1 :: GHC.Internal.Prim.Word#)
- = case ww1 of ds3 {
+ = case ww1 of wild3 {
__DEFAULT ->
let {
m :: GHC.Internal.Prim.Word#
[LclId]
m = GHC.Internal.Prim.and#
- ds3
+ wild3
(GHC.Internal.Prim.int2Word#
(GHC.Internal.Prim.negateInt#
- (GHC.Internal.Prim.word2Int# ds3))) } in
+ (GHC.Internal.Prim.word2Int# wild3))) } in
case GHC.Internal.Prim.indexSmallArray#
@GHC.Internal.Types.Lifted
@(HashMap String a)
@@ -2384,7 +2350,7 @@ T26615.$s$wdisjointSubtrees
of {
False -> GHC.Internal.Types.False;
True ->
- jump $wgo (GHC.Internal.Prim.and# ds3 (GHC.Internal.Prim.not# m))
+ jump $wgo (GHC.Internal.Prim.and# wild3 (GHC.Internal.Prim.not# m))
}
}
};
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -602,6 +602,7 @@ test('T26615', [grep_errmsg(r'fEqList')], multimod_compile, ['T26615', '-O -fsp
# T26722: there should be no reboxing in $wg
test('T26722', [grep_errmsg(r'SPEC')], compile, ['-O -dno-typeable-binds'])
+test('T26548', normal, compile, ['-O -ddump-simpl -dsuppress-uniques -dno-typeable-binds'])
test('T26805', [grep_errmsg(r'fromInteger')], compile, ['-O -dno-typeable-binds -ddump-simpl -dsuppress-uniques'])
test('T26826', normal, compile, ['-O'])
test('T26903', [grep_errmsg(r'reverse')], compile, ['-O -dno-typeable-binds -ddump-simpl -dsuppress-uniques -dsuppress-all'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ea77df4174d336ee1d04fee371a4d7…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ea77df4174d336ee1d04fee371a4d7…
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] 42 commits: Move idle GC tracking to its own file, step 1 of 2
by Marge Bot (@marge-bot) 28 Nov '26
by Marge Bot (@marge-bot) 28 Nov '26
28 Nov '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
59cd0c9b by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
469e750d by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
e9601ff6 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
a13e31c6 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
38ed5896 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
197543a6 by Duncan Coutts at 2026-11-28T17:06:41-05:00
Remove variable n_haskell_handlers which has become write-only
The previous commit removed the last read of this variable.
- - - - -
fb028cfd by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
6134b823 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
f0070c0c by Duncan Coutts at 2026-11-28T17:06:41-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
- - - - -
232907db by Duncan Coutts at 2026-11-28T17:06:41-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
- - - - -
a23f09a9 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
f0d8e605 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
402a1cb9 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
8e4fce07 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
2d61d9ae by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
fb6fa834 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
72ba6da1 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
aba09e28 by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
b364dd2e by Duncan Coutts at 2026-11-28T17:06:41-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.
- - - - -
55f8f115 by Duncan Coutts at 2026-11-28T17:06:42-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.
- - - - -
3d11b728 by Duncan Coutts at 2026-11-28T17:06:42-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.
- - - - -
46e80d3e by Duncan Coutts at 2026-11-28T17:06:42-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.
- - - - -
59f89a87 by Duncan Coutts at 2026-11-28T17:06:42-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.
- - - - -
18f10e31 by Duncan Coutts at 2026-11-28T17:06:42-05:00
Add and use USED_IF_PREEMPTION to avoid warnings
- - - - -
833c84e3 by Duncan Coutts at 2026-11-28T17:06:42-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.
- - - - -
72070a01 by Duncan Coutts at 2026-11-28T17:06:42-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
- - - - -
f62a057a by Duncan Coutts at 2026-11-28T17:06:42-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.
- - - - -
6ae22d34 by Simon Peyton Jones at 2026-11-28T17:06:43-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(a)anthropic.com>
- - - - -
4a0dfb55 by Simon Peyton Jones at 2026-11-28T17:06:43-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(a)anthropic.com>
- - - - -
cac131ec by Simon Peyton Jones at 2026-11-28T17:06:43-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(a)anthropic.com>
- - - - -
08fc1afe by Simon Peyton Jones at 2026-11-28T17:06:43-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(a)anthropic.com>
- - - - -
7d3e1349 by Simon Peyton Jones at 2026-11-28T17:06:43-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.
- - - - -
4beaa4ad by sheaf at 2026-11-28T17:06:51-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.
- - - - -
89eb3448 by sheaf at 2026-11-28T17:06:51-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
- - - - -
35099246 by Rodrigo Mesquita at 2026-11-28T17:06:52-05:00
test: make T3171 not fragile and add version for ext interp too
- actually test the sleep of the user-given expression gets interrupted
- the ext interp version tests two things:
- Requests can be cancelled without terminating the ext interp (#18852)
- The stmt being evaluated gets interrupted in the ext interp (that
is, ^C gets sent to the thread running the user-given expression
and doesn't affect the ext interp main thread)
- testing ext interp requires sending ^C to whole process group
Fixes #15383
- - - - -
173ce280 by Rodrigo Mesquita at 2026-11-28T17:06:52-05:00
Global break action which uses a per-thread context map
Previously, everytime an expression was run in the interpreter (`sandboxIO`):
1) the RTS global variable `rts_breakpoint_io_action`, which is run
anytime any thread hits a breakpoint, got set to a new action that:
a) Wrote the breakpoint hit by the thread to the `statusMVar`
b) Blocked waiting on a newly created MVar `breakMVar` for a `resumeStmt` to
signal it.
2) Start the expression evaluation on a new "sandbox" thread
3) Block waiting on `statusMVar` for a breakpoint to be hit, and we'd
return the read `EvalBreak`
4) Set the `rts_breakpoint_io_action` to a no-op which prints "Ignored breakpoint..."
At some later point, we could `resumeStmt` with the `EvalBreak` context
by signaling the `breakMVar` on which the thread that hit the breakpoint
is blocked.
However, if you consider an expression which forks off threads which hit
breakpoints, surprising things may happen:
main = do
-- the `worker` code has a breakpoint
mapM (forkIO . worker) [1..10]
forever $ threadDelay 10000000
Interpreting this program, we'll do (1,2,3), and all workers will hit
their breakpoint and run `rts_breakpoint_io_action`. Here's a first
issue:
1. The first worker succeeds in `putMVar statusMVar`
2. The interpreter will read `takeMVar statusMVar` (3) and then (4)
3. The remaining workers are hitting the breakpoint concurrently:
- Some may block trying to `putMVar statusMVar`
- Some may run the no-op action which discards the breakpoint
Depending on whether the remaining workers hit the breakpoint or (4)
happens first, some workers will skip their breakpoint.
Now, let's pretend all workers can block on `putMVar statusMVar`. Since
the interpreter will take the breakpoints one by one, and resume them
one by one, it seemingly works. However, that's only fine when we assume
only one expression is evaluated at once. As soon as multiple
expressions can be evaluated at once (a desireable property of a
debugger, as well as something that can already happen today in some
scenarios (see `break049`)), it becomes madness:
The second issue comes the global break action being swapped by a second
evaluation and threads from the first evaluation running the "wrong" action.
Consider:
1. eval `expr_A` installs a break action that puts on `statusMVar_A`
2. `expr_A` forks off a few threads, they're running in the background
3. eval `expr_B` sets the break action to put on `statusMVar_B`
4. the `expr_A` forked threads hit a breakpoint and put `statusMVar_B`
5. `expr_B` returns with a breakpoint of `expr_A`, `resume expr_B` would
resume `expr_A`, etc...
A third issue with having a single MVar for all threads of an execution
is that there is no way to have fine-grained control over which threads
are resumed and which are stopped. This is often necessary to debug
multi-threaded programs too.
Therefore, it is imperative that the global break action does not
capture a global single MVar when many expressions with many
corresponding threads can be running in the interpreter/debugger at
once, if we want to support debugging multi-threaded programs at all.
---
This commit fixes these foundational issues by making the global break
action truly global (i.e. never modified and never capturing any locals).
The global break action is installed once in `sandboxIO` and never
removed (`withBreakAciton` and `noBreakAction` were killed). Subsequent
runs of `sandboxIO` re-rewrite the same break action (a no-op).
When any thread hits the global break action, it looks its `ThreadId` up
in the global per-thread context mapping, returning a `ResumeContext`
which contains that thread's `breakMVar` (now `resumeBreakVar`) and
`statusMVar` (now `resumeEvalStatus`). Each thread blocks on its own
MVar and replies on its own TVar. There is no longer one global status
nor break MVar.
To resume a thread by its `ThreadId`, we can simply fetch its
`ResumeContext` and signal the corresponding `resumeBreakMVar`
To wait for a result or for a breakpoint in a specific thread, we do
`readThreadEvalStatus`. To wait for any breakpoint hit in any thread at
all, we have `readAnyThreadEvalBreak`.
Some evaluations will only care to look at their own result and breaks
(so they run with `readAllBreaks` `= False`); and the main thread of an
evaluation should not be read by other evaluations. In short, only
threads forked off by the main thread of evaluations get read with
`readAnyThreadEvalBreak`. If two evaluations fork off threads in the
background, `readAnyThreadEvalBreak` may return threads from any of
them. There is no just way to distinguish their "parents" at runtime.
For instance, `compileParsedExprRemote` should run an expression until
completion without any existing threads interfering with its execution,
so it runs with `readAllBreaks = False`. Otherwise, by default, running
`main` on the REPL, we'll want to stop at any break any forked thread
hits, just like we did before.
P.S. Currently, we need to keep track of the "main expression thread"
being currently evaluated to fetch its result, but, when `evalStmt`
becomes asynchronous by returning the `ThreadId` of the "sandbox"
thread, the whole `evaluationMainThreadGlobalVar` hack can be deleted.
---
New tests observing behavior that we don't want to break (which I broke
at some point while developing this patch):
- break032: we don't stop at breakpoints in TH
- break033: :continue after -fbreak-on-exception doesn't hit exception breakpoint
- break034: test :abandon doesn't hang with -fbreak-on-error
- conc033: also run with the external interpreter
- ForceInterrupt(Ext): ^C during :force interrupts the forced expression
- break043: :continue of a forked thread reads main thread breaks/results too
- break046: evaluating expr while stopped doesn't change what :continue resumes
- break048: evaluating expr while forked thread is stopped doesn't hit again current breakpoint
New tests that failed before this commit:
- T3171(ext)nosandbox: T3171 with -fno-ghci-sandbox (T3171extnosandbox still fails)
- break050(ext): ^C during :continue of a forked thread interrupts that thread
Fixed ext-interp bc. resumeStmt now does unsafeUnmask, just like
sandboxIO, so the UserInterrupt reaches the resume.
- break049: breakpoints in forked threads don't get mixed up with other evaluations
This test demonstrates one way multi-threaded debugging can go wrong
bc the global break action used to capture a break MVar for a
specific thread that is shared by all threads (described above as
"the second issue"). Here is the annotated execution of the test
*before this commit*:
```haskell
ghci> main
Stopped in Main.inMain, break049.hs:30:12-18
_result :: IO () = _
[break049.hs:30:12-18] ghci> :force slow
-- ANN: the breakpoint we're ignoring on :force is the worker's
-- breakpoint, and it's just discarded
*** Ignoring breakpoint [break049.hs:27:14-20]
slow = 5
[break049.hs:30:12-18] ghci> :cmd return ""
-- ANN: we :continue `main`, but the worker should still be blocked
-- so `main` should block.
[break049.hs:30:12-18] ghci> :continue
-- ANN: however, it completes; recall the worker break was ignored
-- instead of stopping there
main done
-- ANN: after this commit, the worker break wouldn't have been read
-- by `:force`, and we'd see it when resuming `:main`, and
-- `:continue` here would resume the worker and only then main would
-- complete.
ghci> :continue
-- ANN: bc this is ghci before the commit, we see:
not stopped at a breakpoint
ghci>
```
- break042: main forks workers and all workers hit a breakpoint
This test witnesses "the first issue" described above, where the
workers hit breaks after the global break action was already removed
and so are lost.
Fixes #28124
- - - - -
5cc59f4b by Rodrigo Mesquita at 2026-11-28T17:06:52-05:00
ci: unset CI_COMMIT_MESSAGE to avoid Windows environment length limits
The previous commit consistently made the Windows runner fail with:
> find: The environment is too large for exec().
GitLab sets these environment variables by default, but we never read
them. Just unset them at the start.
- - - - -
8f0ce127 by Sylvain Henry at 2026-11-28T17:06:58-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(a)anthropic.com>
- - - - -
dd10d0e7 by David Eichmann at 2026-11-28T17:06:59-05:00
testsuite: fix framework failure on window for tests using all_available_io_managers_except()
- - - - -
092ba893 by David Eichmann at 2026-11-28T17:07:00-05:00
testsuite: use `all_available_io_managers` for various tests
Affected tests:
* T10590
* T21969
* T21969a
* T21969b
* T21969c
* T21969d
* T21969e
* T21969f
- - - - -
fb98e45b by Sylvain Henry at 2026-11-28T17:07:05-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(a)anthropic.com>
- - - - -
dd3d2d34 by Alan Zimmerman at 2026-11-28T17:07:07-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.
- - - - -
163 changed files:
- .gitlab/ci.sh
- + changelog.d/28105
- + changelog.d/28124
- + changelog.d/T27962
- + changelog.d/T27963
- + changelog.d/T28082
- + changelog.d/idle-gc-and-deadlock-detection
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/Core.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Make/Box.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/Driver/Config.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/GHC/Tc/Instance/FunDeps.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Id.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Utils/Monad.hs
- 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
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Run.hs
- + libraries/ghci/GHCi/Run/Breakpoints.hs
- libraries/ghci/ghci.cabal.in
- rts/Capability.c
- rts/IOManager.c
- rts/IOManager.h
- + rts/IdleGC.c
- + rts/IdleGC.h
- rts/Interpreter.c
- rts/Linker.c
- rts/RtsFlags.c
- rts/RtsSignals.h
- rts/RtsStartup.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/js/environment.js
- 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/Signals.h
- rts/posix/Timeout.c
- rts/posix/Timeout.h
- rts/rts.cabal
- rts/win32/AsyncMIO.c
- rts/win32/AsyncMIO.h
- rts/win32/AsyncWinIO.c
- rts/win32/AsyncWinIO.h
- rts/win32/AwaitEvent.c
- rts/win32/ConsoleHandler.c
- rts/win32/ConsoleHandler.h
- testsuite/driver/testutil.py
- + testsuite/tests/codeGen/should_compile/T28105.cmm
- + testsuite/tests/codeGen/should_compile/T28105b.hs
- testsuite/tests/codeGen/should_compile/all.T
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/ghci.debugger/scripts/Makefile
- testsuite/tests/ghci.debugger/scripts/T14690.stdout
- testsuite/tests/ghci.debugger/scripts/all.T
- testsuite/tests/ghci.debugger/scripts/break024.stdout
- + testsuite/tests/ghci.debugger/scripts/break032.hs
- + testsuite/tests/ghci.debugger/scripts/break032.script
- + testsuite/tests/ghci.debugger/scripts/break032.stdout
- + testsuite/tests/ghci.debugger/scripts/break033.hs
- + testsuite/tests/ghci.debugger/scripts/break033.script
- + testsuite/tests/ghci.debugger/scripts/break033.stdout
- + testsuite/tests/ghci.debugger/scripts/break034.hs
- + testsuite/tests/ghci.debugger/scripts/break034.script
- + testsuite/tests/ghci.debugger/scripts/break034.stdout
- + testsuite/tests/ghci.debugger/scripts/break042.hs
- + testsuite/tests/ghci.debugger/scripts/break042.script
- + testsuite/tests/ghci.debugger/scripts/break042.stderr
- + testsuite/tests/ghci.debugger/scripts/break042.stdout
- + testsuite/tests/ghci.debugger/scripts/break043.hs
- + testsuite/tests/ghci.debugger/scripts/break043.script
- + testsuite/tests/ghci.debugger/scripts/break043.stdout
- + testsuite/tests/ghci.debugger/scripts/break046.hs
- + testsuite/tests/ghci.debugger/scripts/break046.script
- + testsuite/tests/ghci.debugger/scripts/break046.stdout
- + testsuite/tests/ghci.debugger/scripts/break048.hs
- + testsuite/tests/ghci.debugger/scripts/break048.script
- + testsuite/tests/ghci.debugger/scripts/break048.stdout
- + testsuite/tests/ghci.debugger/scripts/break049.hs
- + testsuite/tests/ghci.debugger/scripts/break049.script
- + testsuite/tests/ghci.debugger/scripts/break049.stdout
- + testsuite/tests/ghci.debugger/scripts/break050.hs
- + testsuite/tests/ghci.debugger/scripts/break050.script
- + testsuite/tests/ghci.debugger/scripts/break050.stdout
- + testsuite/tests/ghci.debugger/scripts/break050ext.stdout
- testsuite/tests/ghci/prog-mhu005/Makefile
- testsuite/tests/ghci/prog-mhu006/Makefile
- testsuite/tests/ghci/prog-mhu007/Makefile
- testsuite/tests/ghci/prog020/Makefile
- testsuite/tests/ghci/prog022/Makefile
- testsuite/tests/ghci/prog025/Makefile
- + testsuite/tests/ghci/should_run/ForceInterrupt.script
- + testsuite/tests/ghci/should_run/ForceInterrupt.stdout
- + testsuite/tests/ghci/should_run/ForceInterruptExt.stdout
- testsuite/tests/ghci/should_run/Makefile
- testsuite/tests/ghci/should_run/T3171.stdout
- + testsuite/tests/ghci/should_run/T3171ext.stdout
- + testsuite/tests/ghci/should_run/T3171extnosandbox.stdout
- + testsuite/tests/ghci/should_run/T3171nosandbox.stdout
- testsuite/tests/ghci/should_run/all.T
- + testsuite/tests/indexed-types/should_compile/T28082.hs
- testsuite/tests/indexed-types/should_compile/all.T
- 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/T26408e.hs
- + testsuite/tests/rts/T26408e.stderr
- + testsuite/tests/rts/T26408f.hs
- + testsuite/tests/rts/T26408f.stderr
- testsuite/tests/rts/all.T
- testsuite/tests/rts/symbols/rts-check-symbols.stdout
- 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/T27965b.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/774c721ac80b81670875cfb97435dc…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/774c721ac80b81670875cfb97435dc…
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
28 Nov '26
Andreas Klebinger pushed new branch wip/apk/fast-make at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/apk/fast-make
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/supersven/riscv-ncg-mul2] RISC-V NCG: Implement 64-bit MO_S_Mul2 and MO_U_Mul2 (#27733)
by Sven Tennie (@supersven) 28 Nov '26
by Sven Tennie (@supersven) 28 Nov '26
28 Nov '26
Sven Tennie pushed to branch wip/supersven/riscv-ncg-mul2 at Glasgow Haskell Compiler / GHC
Commits:
671c1a6d by Sven Tennie at 2026-11-28T19:20:27+01:00
RISC-V NCG: Implement 64-bit MO_S_Mul2 and MO_U_Mul2 (#27733)
Lower the 64-bit signed and unsigned double-word multiply Cmm
operations to native instructions: %mul2_64 (MO_S_Mul2 W64) now emits
MUL followed by MULH, and %mul2u_64 (MO_U_Mul2 W64) emits MUL followed
by MULHU.
Sub-word widths remain unsupported. StgToCmm only emits word-width
Mul2 operations, so these can only be requested from hand-written Cmm.
Enabling the 64-bit operations also makes timesInt2# and timesWord2#
use the native instructions rather than the generic half-word multiply
expansion.
Tests: T9430 extended; T27046 extended for unsigned aliasing and now
passes on RISC-V NCG
- - - - -
8 changed files:
- + changelog.d/T27733
- compiler/GHC/CmmToAsm/RV64/CodeGen.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/RV64/Ppr.hs
- compiler/GHC/Driver/Config/StgToCmm.hs
- testsuite/tests/codeGen/should_run/T27046.hs
- testsuite/tests/codeGen/should_run/T27046_cmm.cmm
- testsuite/tests/primops/should_run/T9430.hs
Changes:
=====================================
changelog.d/T27733
=====================================
@@ -0,0 +1,13 @@
+section: codegen
+synopsis: RISC-V NCG: support 64-bit MO_S_Mul2 and MO_U_Mul2
+issues: #27733
+mrs: !17067
+
+description: {
+ The RISC-V NCG now lowers the 64-bit Cmm operations ``MO_S_Mul2 W64``
+ (``%mul2_64``) and ``MO_U_Mul2 W64`` (``%mul2u_64``) to ``MUL``/``MULH`` and
+ ``MUL``/``MULHU``, respectively. Sub-word widths remain unsupported as they
+ aren't emitted for Haskell code.
+
+ ``timesInt2#`` and ``timesWord2#`` now use these native instructions.
+}
=====================================
compiler/GHC/CmmToAsm/RV64/CodeGen.hs
=====================================
@@ -1781,7 +1781,37 @@ genCCall (PrimTarget mop) dest_regs arg_regs = do
MO_UF_Conv w -> mkCCall (word2FloatLabel w)
-- Optional MachOps
-- These are enabled/disabled by backend flags: GHC.StgToCmm.Config
- MO_S_Mul2 _w -> unsupported mop
+ MO_S_Mul2 w
+ | w == W64
+ , [src_a, src_b] <- arg_regs
+ , [dst_needed, dst_hi, dst_lo] <- dest_regs
+ -> do
+ platform <- getPlatform
+ (reg_a, _format_x, code_x) <- getSomeReg src_a
+ (reg_b, _format_y, code_y) <- getSomeReg src_b
+
+ let lo = getRegisterReg platform (CmmLocal dst_lo)
+ hi = getRegisterReg platform (CmmLocal dst_hi)
+ nd = getRegisterReg platform (CmmLocal dst_needed)
+
+ -- Use a fresh register for the low half. If dst_lo coincided with
+ -- one of the sources, computing it first would clobber that source
+ -- before MULH has read it.
+ tmp_lo <- getNewRegNat II64
+
+ pure $
+ code_x `appOL` code_y
+ `snocOL` MUL (OpReg W64 tmp_lo) (OpReg W64 reg_a) (OpReg W64 reg_b)
+ `snocOL` MULH (OpReg W64 hi) (OpReg W64 reg_a) (OpReg W64 reg_b)
+ `snocOL` MOV (OpReg W64 lo) (OpReg W64 tmp_lo)
+ -- The product fits in W64 iff the high half hi is the sign
+ -- extension of the low half lo, i.e.
+ -- hi == asr(lo, widthInBits W64 - 1).
+ -- nd = (hi /= asr(lo, widthInBits W64 - 1)) ? 1 : 0.
+ `snocOL` SRA (OpReg W64 tmp_lo) (OpReg W64 tmp_lo)
+ (OpImm (ImmInt (widthInBits W64 - 1)))
+ `snocOL` CSET (OpReg W64 nd) (OpReg W64 hi) (OpReg W64 tmp_lo) NE
+ MO_S_Mul2 _ -> unsupportedMul2
MO_S_QuotRem _w -> unsupported mop
MO_U_QuotRem _w -> unsupported mop
MO_U_QuotRem2 _w -> unsupported mop
@@ -1790,7 +1820,29 @@ genCCall (PrimTarget mop) dest_regs arg_regs = do
MO_SubWordC _w -> unsupported mop
MO_AddIntC _w -> unsupported mop
MO_SubIntC _w -> unsupported mop
- MO_U_Mul2 _w -> unsupported mop
+ MO_U_Mul2 w
+ | w == W64
+ , [src_a, src_b] <- arg_regs
+ , [dst_hi, dst_lo] <- dest_regs
+ -> do
+ platform <- getPlatform
+ (reg_a, _format_x, code_x) <- getSomeReg src_a
+ (reg_b, _format_y, code_y) <- getSomeReg src_b
+
+ let lo = getRegisterReg platform (CmmLocal dst_lo)
+ hi = getRegisterReg platform (CmmLocal dst_hi)
+
+ -- Use a fresh register for the low half. If dst_lo coincided with
+ -- one of the sources, computing it first would clobber that source
+ -- before MULHU has read it.
+ tmp_lo <- getNewRegNat II64
+
+ pure $
+ code_x `appOL` code_y
+ `snocOL` MUL (OpReg W64 tmp_lo) (OpReg W64 reg_a) (OpReg W64 reg_b)
+ `snocOL` MULHU (OpReg W64 hi) (OpReg W64 reg_a) (OpReg W64 reg_b)
+ `snocOL` MOV (OpReg W64 lo) (OpReg W64 tmp_lo)
+ MO_U_Mul2 _ -> unsupportedMul2
MO_VS_Quot {} -> unsupported mop
MO_VS_Rem {} -> unsupported mop
MO_VU_Quot {} -> unsupported mop
@@ -1900,6 +1952,15 @@ genCCall (PrimTarget mop) dest_regs arg_regs = do
++ show mop
++ " not supported here"
)
+
+ unsupportedMul2 :: b
+ unsupportedMul2 =
+ panic
+ ( "outOfLineCmmOp: " ++ show mop
+ ++ " with " ++ show (length arg_regs) ++ " arguments and "
+ ++ show (length dest_regs) ++ " results is not supported on RISC-V"
+ )
+
mkCCall :: FastString -> NatM InstrBlock
mkCCall name = do
config <- getConfig
@@ -2119,6 +2180,7 @@ makeFarBranches {- only used when debugging -} _platform statics basic_blocks =
ADD {} -> 1
MUL {} -> 1
MULH {} -> 1
+ MULHU {} -> 1
NEG {} -> 1
DIV {} -> 1
REM {} -> 1
=====================================
compiler/GHC/CmmToAsm/RV64/Instr.hs
=====================================
@@ -81,6 +81,7 @@ regUsageOfInstr platform instr = runUsage platform $ case instr of
MUL dst src1 src2 -> readOp src1 <.> readOp src2 <.> writeOp dst
NEG dst src -> readOp src <.> writeOp dst
MULH dst src1 src2 -> readOp src1 <.> readOp src2 <.> writeOp dst
+ MULHU dst src1 src2 -> readOp src1 <.> readOp src2 <.> writeOp dst
DIV dst src1 src2 -> readOp src1 <.> readOp src2 <.> writeOp dst
REM dst src1 src2 -> readOp src1 <.> readOp src2 <.> writeOp dst
REMU dst src1 src2 -> readOp src1 <.> readOp src2 <.> writeOp dst
@@ -194,6 +195,7 @@ patchRegsOfInstr instr env = case instr of
MUL o1 o2 o3 -> MUL (patchOp o1) (patchOp o2) (patchOp o3)
NEG o1 o2 -> NEG (patchOp o1) (patchOp o2)
MULH o1 o2 o3 -> MULH (patchOp o1) (patchOp o2) (patchOp o3)
+ MULHU o1 o2 o3 -> MULHU (patchOp o1) (patchOp o2) (patchOp o3)
DIV o1 o2 o3 -> DIV (patchOp o1) (patchOp o2) (patchOp o3)
REM o1 o2 o3 -> REM (patchOp o1) (patchOp o2) (patchOp o3)
REMU o1 o2 o3 -> REMU (patchOp o1) (patchOp o2) (patchOp o3)
@@ -587,6 +589,10 @@ data Instr
--
-- E.g. for a multiplication with 64bits width: @rd = (rs1 * rs2) >> 64@.
MULH Operand Operand Operand
+ | -- | High part of an unsigned multiplication that doesn't fit into 64bits (integer only)
+ --
+ -- E.g. for a multiplication with 64bits width: @rd = (rs1 * rs2) >> 64@.
+ MULHU Operand Operand Operand
| -- | Unsigned division (integer only)
--
-- @rd = |rn ÷ rm|@
@@ -685,6 +691,7 @@ instrCon i =
REM {} -> "REM"
REMU {} -> "REMU"
MULH {} -> "MULH"
+ MULHU {} -> "MULHU"
SUB {} -> "SUB"
DIVU {} -> "DIVU"
AND {} -> "AND"
=====================================
compiler/GHC/CmmToAsm/RV64/Ppr.hs
=====================================
@@ -491,6 +491,7 @@ pprInstr platform instr = case instr of
| isFloatOp o1 && isFloatOp o2 && isFloatOp o3 -> op3 (text "\tfmul." <> if isSingleOp o1 then text "s" else text "d") o1 o2 o3
| otherwise -> op3 (text "\tmul") o1 o2 o3
MULH o1 o2 o3 -> op3 (text "\tmulh") o1 o2 o3
+ MULHU o1 o2 o3 -> op3 (text "\tmulhu") o1 o2 o3
NEG o1 o2 | isFloatOp o1 && isFloatOp o2 && isSingleOp o2 -> op2 (text "\tfneg.s") o1 o2
NEG o1 o2 | isFloatOp o1 && isFloatOp o2 && isDoubleOp o2 -> op2 (text "\tfneg.d") o1 o2
NEG o1 o2 -> op2 (text "\tneg") o1 o2
=====================================
compiler/GHC/Driver/Config/StgToCmm.hs
=====================================
@@ -80,8 +80,8 @@ initStgToCmmConfig dflags mod = StgToCmmConfig
| otherwise
-> const True
- , stgToCmmAllowIntMul2Instr = (ncg && (x86ish || aarch64)) || llvm
- , stgToCmmAllowWordMul2Instr = (ncg && (x86ish || ppc || aarch64)) || llvm
+ , stgToCmmAllowIntMul2Instr = (ncg && (x86ish || aarch64 || riscv64)) || llvm
+ , stgToCmmAllowWordMul2Instr = (ncg && (x86ish || ppc || aarch64 || riscv64)) || llvm
, stgToCmmAllowIntWord64X2MinMax = (ncg && (sse4_2 || aarch64)) || llvm
-- SIMD flags
, stgToCmmVecInstrsErr = vec_err
@@ -102,6 +102,9 @@ initStgToCmmConfig dflags mod = StgToCmmConfig
aarch64 = case platformArch platform of
ArchAArch64 -> True
_ -> False
+ riscv64 = case platformArch platform of
+ ArchRISCV64 -> True
+ _ -> False
x86ish = case platformArch platform of
ArchX86 -> True
ArchX86_64 -> True
=====================================
testsuite/tests/codeGen/should_run/T27046.hs
=====================================
@@ -8,18 +8,25 @@ import Control.Monad
import Data.Bits
( shiftL )
import GHC.Exts
- ( Int64# )
+ ( Int64#, Word64# )
import GHC.Int
( Int64(..) )
+import GHC.Word
+ ( Word64(..) )
foreign import prim "test_mul2_clobber"
test_mul2_clobber :: Int64# -> Int64# -> Int64#
+foreign import prim "test_mul2u_clobber"
+ test_mul2u_clobber :: Word64# -> Word64# -> Word64#
+
main :: IO ()
main = do
let
I64# x = 1 `shiftL` 32
+ W64# xw = 1 `shiftL` 32
hi = I64# $ test_mul2_clobber x x
+ hiw = W64# $ test_mul2u_clobber xw xw
unless ( hi == 1 ) $
error $ unlines
@@ -27,3 +34,10 @@ main = do
, "Expected high word: 1"
, " Actual high word: " ++ show hi
]
+
+ unless ( hiw == 1 ) $
+ error $ unlines
+ [ "Incorrect result for unsigned Mul2 operation."
+ , "Expected high word: 1"
+ , " Actual high word: " ++ show hiw
+ ]
=====================================
testsuite/tests/codeGen/should_run/T27046_cmm.cmm
=====================================
@@ -11,3 +11,14 @@ test_mul2_clobber (bits64 x, bits64 y)
return (hi);
}
+
+test_mul2u_clobber (bits64 x, bits64 y)
+{
+ bits64 hi;
+
+ // Deliberately alias the destination 'lo' with the source 'x'
+ // This forces the NCG to use the same virtual register for both.
+ (hi, x) = prim %mul2u_64(x, y);
+
+ return (hi);
+}
=====================================
testsuite/tests/primops/should_run/T9430.hs
=====================================
@@ -23,6 +23,21 @@ checkI (expX, expY) op (I# a) (I# b) =
Just $
"Expected " ++ show expX ++ " and " ++ show expY
++ " but got " ++ show (I# x) ++ " and " ++ show (I# y)
+checkI2
+ :: (Int, Int, Int) -- ^ expected results
+ -> (Int# -> Int# -> (# Int#, Int#, Int# #)) -- ^ primop
+ -> Int -- ^ first argument
+ -> Int -- ^ second argument
+ -> Maybe String -- ^ maybe error
+checkI2 (expN, expH, expL) op (I# a) (I# b) =
+ case op a b of
+ (# n, h, l #)
+ | I# n == expN && I# h == expH && I# l == expL -> Nothing
+ | otherwise ->
+ Just $
+ "Expected " ++ show (expN, expH, expL)
+ ++ " but got " ++ show (I# n, I# h, I# l)
+
checkW
:: (Word, Word) -- ^ expected results
-> (Word# -> Word# -> (# Word#, Word# #)) -- ^ primop
@@ -59,6 +74,18 @@ check :: String -> Maybe String -> IO ()
check s (Just err) = error $ "Error for " ++ s ++ ": " ++ err
check _ Nothing = return ()
+expectedTimesInt2 :: Int -> Int -> (Int, Int, Int)
+expectedTimesInt2 x y =
+ let p = toInteger x * toInteger y
+ radix = (2 :: Integer) ^ wordWidth
+ hi = p `div` radix
+ lo = p - hi * radix
+ needed
+ | p < toInteger (minBound :: Int) = 1
+ | p > toInteger (maxBound :: Int) = 1
+ | otherwise = 0
+ in (needed, fromInteger hi, fromInteger lo)
+
main :: IO ()
main = do
-- First something trivial
@@ -112,6 +139,33 @@ main = do
checkW (2, maxBound - 2) timesWord2# maxBound 3
check "timesWord2# 3 maxBound" $
checkW (2, maxBound - 2) timesWord2# 3 maxBound
+ check "timesWord2# maxBound maxBound" $
+ checkW (maxBound - 1, 1) timesWord2# maxBound maxBound
+ check "timesWord2# (2^(N-1)) (2^(N-1))" $
+ checkW (2 ^ (wordWidth-2), 0) timesWord2# (2 ^ (wordWidth-1)) (2 ^ (wordWidth-1))
+
+ -- timesInt2#
+ let checkMul2 x y =
+ check ("timesInt2# " ++ show x ++ " " ++ show y) $
+ checkI2 (expectedTimesInt2 x y) timesInt2# x y
+ checkMul2 0 0
+ checkMul2 0 maxBound
+ checkMul2 1 (-1)
+ checkMul2 (-1) 1
+ checkMul2 (-1) (-1)
+ checkMul2 3 5
+ checkMul2 (-3) 5
+ checkMul2 3 (-5)
+ checkMul2 (-3) (-5)
+ checkMul2 minBound 1
+ checkMul2 1 minBound
+ checkMul2 minBound (-1)
+ checkMul2 (-1) minBound
+ checkMul2 maxBound 1
+ checkMul2 maxBound (-1)
+ checkMul2 (-1) maxBound
+ checkMul2 maxBound maxBound
+ checkMul2 minBound minBound
check "quotRemWord2# 0 0 1" $ checkW2 (0, 0) quotRemWord2# 0 0 1
check "quotRemWord2# 0 4 2" $ checkW2 (2, 0) quotRemWord2# 0 4 2
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/671c1a6df87c3e7122b40747dc9905a…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/671c1a6df87c3e7122b40747dc9905a…
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