-
54cf3c1e
by sheaf at 2026-11-03T07:00:23-05:00
Consolidate all CPU feature handling
This commit introduces GHC.Platform.CpuFeatures which consolidates all
of the logic for implications between CPU feature flags (mainly X86):
- DynFlags now only records the set of -m<feature> flags that were
passed, as an EnumSet CpuFeature. That keeps it a simple record of
the flags the user passed, with no post-processing.
- GHC.Platform.CpuFeatures.initCpuFeatures turns this set into a
CpuFeatures value, applying all implications and the per-architecture
baseline. This is the single home for all of the feature implication
logic.
Some datatypes were reworked to better reflect the implication
structure in the types, e.g. SseAvxVersion has a strategically
placed 'FMA' boolean.
- The NCG, LLVM backend, StgToCmm, CPP defines and LLVM -mattr
flags all consult CpuFeatures, via targetCpuFeatures.
See Note [CPU features], which replaces
Note [Implications between X86 CPU feature flags].
Behaviour changes:
- x86 feature flags (-msse3, -mavx, -mavx512*, -mgfni, ...) passed
when targeting a non-x86 architecture no longer cause x86 CPP
macros (__SSE3__, __AVX512BW__, __GFNI__, ...) to be defined, nor
x86 attributes to be passed to LLVM.
- Error messages reported when required CPU features are not enabled
now print out the minimal set of flags required
(e.g. "-mavx512vl" rather than "-mavx512f -mavx512vl").
-
9af64305
by Luite Stegeman at 2026-11-03T07:01:23-05:00
rts: move stack check to the start of the stg_unpack_cstring thunks
fixes a deadlock
see #27272
-
a2208b21
by Simon Jakobi at 2026-11-03T07:02:05-05:00
Cmm: exclude the entry block from common block elimination
a1d8139054c had fixed #27722 only partially, because it didn't prevent
elimination of the entry block in later rounds, where the entry block is
no longer guaranteed to come first.
To close this loophole, we exclude the entry block from the CBE merge
logic. See Note [Retain entry block during common block elimination] for
details.
This also deletes a misleading comment regarding unreachable blocks: the
control-flow optimiser doesn't actually guarantee that no unreachable
blocks reach CBE.
Fixes #27722.
Assisted-by: Claude Fable 5.1
-
37ad4710
by Alan Zimmerman at 2026-11-03T07:02:46-05:00
EPA: Use AnnList for GADT declarations
Continuing the process of using AnnList to capture parser layout
-
56757900
by Sebastian Graf at 2026-11-04T20:36:47+01:00
Documentation for the Core data constructors
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
9f57c265
by Sylvain Henry at 2026-11-06T06:46:15-05:00
ghc-internal: avoid unnecessary allocations in bignum division (#27231)
Avoid unnecessary allocations in bignum division in the Haskell (native)
backend. The long-division loop used to allocate a fresh BigNat for the
partial product on every iteration, plus one more per quotient-digit
correction; it now subtracts the partial product in place and
materializes nothing.
The quotient-digit estimate is also refined against the second-highest
divisor word, so the add-back correction runs at most once per
iteration.
bignat_quotrem_normalized now requires a divisor of at least 2 words, so
bignat_quotrem dispatches 1-word divisors to bignat_quotrem_word.
See Note [Knuth division loop] and Note [Fused multiply-subtract for
long division] in GHC.Internal.Bignum.Backend.Native.
Measured on the new T27231 perf test (10000 native-backend 8192/2048-bit
Integer quotRem calls): bytes allocated drops from 305 MB to 52 MB (-83%).
Improvement on CI (x86-64-linux-deb13-int_native):
space_leak_001(normal) run/alloc 12,492,185,536 9,073,055,928 -27.4% GOOD
Metric Decrease:
space_leak_001
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
c5b80f4e
by mangoiv at 2026-11-06T06:46:57-05:00
ci: build and test stage
Split up CI in a build and test stage:
1. in the build stage, just produce a bindist as well as running the
stage1 tests
2. in the test stage, install the bindist, then run the testsuite with
out of tree args
-
e4b1c892
by mangoiv at 2026-11-06T06:46:57-05:00
ci: reorder packaging and testing stages
-
19901b41
by mangoiv at 2026-11-06T06:46:57-05:00
ci: out of tree compiler does not imply no hadrian being available
-
83a860a7
by mangoiv at 2026-11-06T06:46:57-05:00
ci: don't do msys deps check on stage1 compiler
-
abf5b3af
by mangoiv at 2026-11-06T06:46:57-05:00
testsuite: allow metric decreases on windows
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13253-spj
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
-
9185f1ab
by mangoiv at 2026-11-06T06:46:57-05:00
ci: stop using ellipses in testsuite output and output env before invoking hadrian
-
bf9ece2b
by Simon Jakobi at 2026-11-06T06:47:42-05:00
testsuite: Skip the changelog-d test in CI
Full-build validate jobs run the whole testsuite and thus repeated the
changelog validation that the dedicated lint-changelog job had already
reported in the early tool-lint stage.
Skip the test when GITLAB_CI is set, making lint-changelog the only CI
check of changelog.d while keeping the test available in local
testsuite runs.
Fixes #27325.
Assisted-by: Claude Fable 5
-
ef6adb30
by ARATA Mizuki at 2026-11-06T06:48:31-05:00
testsuite: Mark T367_letnoescape fragile for the optllvm way
It was marked broken, but it is now unexpectedly passing on aarch64-linux-deb13-validate+llvm.
Marking it fragile for now.
See #7292
-
1db5f9d7
by Rodrigo Mesquita at 2026-11-06T06:49:13-05:00
interp: Make resumeExec and ExecBreak use `Resume` directly
Previously, `Resume` contexts were just put directly in the global
interactive environment state, so they were only accessible through it.
However, in the context of multi-threaded debugging, in that many
threads may hit breakpoints, it no longer suffices to have a global
linear list of breakpoints hit. We need a per-breakpoint Resume context
and need to be able to wield it directly rather than going through a
global context.
The driving changes of this commit are:
- Put the Resume data in ExecBreak
- Make resumeExec receive a Resume as an argument
This also simplifies the interpreter in that we no longer necessarily
rely on the global interactive state to resume a thread. We can do it
directly from the ExecBreak.
The interactive context still maintains a stack of resumes, but
`resumeExec` can no longer pop the resume it resumes off of the
breakpoints stack, since it is no longer guaranteed to be resuming the
first in that list. Hence, callers of `resumeExec` must update ic_resume
on their own.
Fixes #28058
-
fd00a88c
by Rodrigo Mesquita at 2026-11-06T06:49:54-05:00
Per-thread break-on exception (TSO_STOP_ON_EXCEPTION)
The `-fbreak-on-exception` flag allows the interactive interpreter to stop
when a synchronous exception is raised.
However, this is a global toggle backed by a global variable in the RTS
(rts_stop_on_exception) which is not compatible with a multi-threaded
debugger where we may want to stop if some threads raise a synchronous
exception but not other.
This commit makes -break-on-exception similar to step-next and step-out
where there is a per-thread toggle on each TSO (TSO_STOP_ON_EXCEPTION),
and that break-on-exception set in EvalOpts when resuming a statement
only affect the thread being resumed.
Fixes #28068
-
d735b507
by Andrea Vezzosi at 2026-11-06T06:50:35-05:00
driver: Don't let -dynamic unset -fsplit-sections
`addWay' WayDyn` used to unset Opt_SplitSections, so -fsplit-sections was
ignored if it came before -dynamic, but worked if it came after.
The -fsplit-sections -dynamic combination has legitimate uses, e.g. an
executable can be linked dynamically against libraries and still have dead code
from its own sources to eliminate. Or the same objects could be used for both
static archives and shared objects.
The removal of Opt_SplitSections was also motivated by problems on Darwin.
It is now done in `makeDynFlagsConsistent` instead, see Note [Split sections are not
supported on Mach-O].
For consistency, we also keep Opt_SplitSections when `dynamicNow` is activated.
There is a cost of larger .dyn_o (but not .so) files and slower link times (esp.
with ld.bfd), but does not seem significant enough to warrant special casing.
Fixes #28061
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
10e36bd2
by Alan Zimmerman at 2026-11-06T06:51:18-05:00
EPA: Use AnnList in AnnClassDecl
Capture parser layout
-
20334e1d
by sheaf at 2026-11-06T06:52:06-05:00
Avoid panic in 'solveImplicationsUsingUnsatGiven'
Commit 52a4d1da refactored this code to use 'setWantedDict' which panics
for equality constraints. This commit fixes that by explicitly handling
HoleDest.
Fixes #28081
-
0423f413
by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: add tests for the IO manager lock-up of #21969
T21969a 'closeFdWith' takes every 'EventManager''s 'callbackTableVar'
inside 'uninterruptibleMask_' and only puts them back on the paths
that do not throw, so a throw from 'closeFd_' leaves those MVars
empty for good. Afterwards every 'threadWaitRead' and
'closeFdWith' on an fd in the same bucket blocks forever.
T21969b 'closeFdWith' runs the fd's callbacks while asynchronous exceptions
are uninterruptibly masked, so a callback that blocks makes the
thread calling it permanently unkillable.
T21969c 'closeFd_' drops the registrations before telling the backend to
forget the fd, so when the backend throws the fd is never closed
and the threads waiting on it are never woken.
T21969d the cleanup handler of 'threadWait' calls 'unregisterFd_', which
throws on backend errors. It runs inside the handler for the
asynchronous exception being delivered, so its exception replaces
that one: 'killThread' returns but 'ThreadKilled' never arrives.
T21969e an exception from re-arming an fd escapes the poll loop, and 'loop'
turns it into 'cleanup mgr': the 'EventManager' of that capability
is shut down and every thread using it is left blocked. This is
the lock-up of #21969 itself.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
5c197e2e
by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Make the IO manager cope with errors from the polling backend (#21969)
Three changes in 'GHC.Internal.Event.Thread': 'closeFdWith' puts every
'callbackTableVar' back on the paths that throw too and no longer skips the
callbacks when 'close' fails, those callbacks now run under the 'mask_' of
'close_loop' rather than uninterruptibly masked, and the cleanup of
'threadWait' ignores a failure from 'unregisterFd_'.
This fixes T21969a, T21969b and T21969d, and clears their expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
cb765ded
by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let backend errors abandon the close of a file descriptor (#21969)
'closeFd_' and 'closeFd' now ignore errors from telling the backend to forget
the fd: the registration is being torn down and the error says it is already
gone. 'registerFd_' still reports them (!10643), where the caller has to
learn that the registration did not happen. Both also test
'I.elEvent oldEls /= mempty' rather than 'oldEls /= mempty'.
This fixes T21969c, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
9073bc43
by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let a backend error take down a capability's IO manager (#21969)
A failure to re-arm an fd in 'selectCallbacks' is now handled the way
'registerFd_' handles one (!10643): the registrations are taken back out of
the callback table and returned, so their callbacks run and the waiting
threads find out for themselves instead of hanging. Checked on aarch64 Linux
(epoll) and aarch64 macOS (kqueue), 10 runs each way.
This fixes T21969e, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
cdff4e76
by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let the deregistration of threadWaitSTM throw either (#21969)
'threadWaitReadSTM' and 'threadWaitWriteSTM' return the action that gives up
interest in the fd as the second component of their pair, and it was
return (waitAction, unregisterFd_ mgr reg >> return ())
'unregisterFd_' talks to the polling backend, which throws on errors such as
ENOENT and EBADF -- which is how a backend reports an fd it no longer knows,
once that fd has been closed without going through 'closeFdWith'.
That is the same shape as the cleanup of 'threadWait', which the rest of this
series made quiet, and it is the same on both counts. There is nothing to
decide: the registration is being abandoned, and "the backend does not know
this fd" is the state the action is trying to reach. And it does harm: the
action is what a caller uses from the cleanup of a 'bracket', where an
exception out of it replaces whatever was being propagated.
It now goes through 'quietUnregisterFd', as the cleanup of 'threadWait' does,
and that function's comment covers both callers.
T21969f covers it, and is deterministic on both backends: dropping the only
registration changes the event set, so 'unregisterFd_' always reaches the
backend.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
a7ed305b
by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: let T21969 run on FreeBSD, and unmark it (#21969, #25512)
T21969 now carries the descriptor from 'createPipe' instead of recovering it
with 'handleToFd', which rejects the 'DuplexHandle' that FreeBSD's
bidirectional pipes become and killed the test in setup there (#25512). The
expect_broken goes with it: with the descriptor problem out of the way the
test times out on master, so it can only be unmarked on top of this series.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
3074ae61
by Sylvain Henry at 2026-11-08T10:21:50-05:00
rts: heap census counts every small pinned object
Blocks of small pinned objects carry BF_LARGE as well as BF_PINNED but
hold many objects. heapCensusChain treated every BF_LARGE block whose
first object is an ARR_WORDS as holding that single object, a workaround
for the slop left by shrinkMutableByteArray# (#11627). So every heap
profile mode under-reported pinned byte arrays, i.e. ByteString payloads.
Shrinking now writes a slop marker that skipSlop understands (#19048,
#27585), so the block walk is safe for large and pinned blocks alike.
The block that a capability fills with small pinned objects stays
attached to the capability until it is full (see allocatePinned), so it
is on no generation list and the census never saw its objects. heapCensus
now walks cap->pinned_object_block too.
A pinned block is kept or freed as a whole (#28005), so dead pinned
objects are counted until their block is freed. T7275 gains one sample in
which its dead small arrays still show. The user guide and changelog
document this.
T7257 retains most of its pinned blocks and takes a census at every GC
(+RTS -i0 -hT), so walking every pinned object made it 7x slower and it
hit the CI timeout. It now runs 1000000 iterations instead of 5000000.
Metric Decrease:
T7257
Fixes #28000
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
16fd075a
by Sylvain Henry at 2026-11-08T10:22:39-05:00
rts: fix GC CPU time accounting with idle GC threads (#26169)
stat_endGC summed gc_end_cpu - gc_start_cpu over every GC thread, but
only the threads that take part in a collection set these fields, and
new_gc_thread did not initialise them. With -qn below the capability
count, the first collection after setNumCapabilities added garbage to
the GC CPU time.
Let each participating thread add its own CPU time to an accumulator
in stat_endGCWorker, and let stat_endGC take the total. This removes
the loop over gc_threads, the reset from #21082 and the gc_end_cpu
field. Also drop the unused gc_end_elapsed field.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
0ef732e2
by Sylvain Henry at 2026-11-08T10:23:30-05:00
Serialized: encode numbers with LEB128
serializeWithData used the Binary instances of Data.Binary for the
numbers in a ConstrRep. They have a fixed width: 8 bytes for the
constructor index (an Int) and 5 bytes for a small Integer. Each
element of a [Int] cost 15 bytes.
Now the constructor representation is one unsigned LEB128 number that
also contains the index of an algebraic constructor, and the payloads
(Integer, Rational, Char) are LEB128 encoded. Most constructors take
one byte, and small numbers two. See Note [Serialized encoding].
Sizes measured by the T16841 test:
[1..100] :: [Int] 1509 -> 338 bytes
"helloworld" 119 -> 31 bytes
2^100 :: Integer 24 -> 16 bytes
Just True 18 -> 2 bytes
3.25 :: Double 11 -> 3 bytes
42 :: Int 6 -> 2 bytes
A new test, SerializedRoundTrip, round-trips values at the boundaries
of the encoding (negative numbers, big Integers, Rationals, Chars).
Follow-up to !16841 (#28002).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
22344fbc
by Sylvain Henry at 2026-11-08T10:24:21-05:00
docs: fix duplicate label in qualified_strings.rst
The file started with the label "multiline-strings", copied from
multiline_strings.rst. Sphinx warned about the duplicate label on every
build. Use the label "qualified-strings" instead.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
b7022624
by Alan Zimmerman at 2026-11-08T10:25:02-05:00
EPA: Use LHsLocalBinds instead of HsLocalBinds
This reverses an earlier change, and brings processing of local binds
into alignement with the exact printing principle that the LocatedA
contents provide the location and extent of the enclosed item,
together with any comments or context-specific trailing items like
commas or semi colons.
The internal TTG extension points only carry exact print annotations
related to printing the item within its bounds.
This change brings back the problem of EmptyLocalBinds, which by
definition cannot have a location. These get a noSrcSpan location,
which is ignored in the exact printing process.
-
bc2fae45
by Rodrigo Mesquita at 2026-11-08T18:37:40-05:00
Build EvalOpts once per exec rather than per breakpoint stop
We were unnecessarily constructing `eval_opts` in `handleRunStatus`
(which is run many times in a loop until we hit a breakpoint we care
about, e.g. when :steplocal), despite the `eval_opts` being constant
across all these runs.
So, construct `eval_opts` outside `handleRunStatus` and share the value
in all loop calls. The loop always uses the same eval_opts, so no point
in constructing them inside `handleRunStatus` from scratch every time.
I found out about the significance of this re-construction of `EvalOpts`
when I added a record update of `eval_opts` *after* the construction
from scratch inside `handleRunStatus` that regressed allocations
significantly.
This improves the performance of `interpreter_steplocal` on my machine:
Baseline
Test Metric value New value Change
-------------------------------------------------------------------------
interpreter_steplocal(ghci) ghc/alloc 459,845,696 449,843,480 -2.2%
Fixes #28068
-
ba579288
by Rodrigo Mesquita at 2026-11-08T18:38:21-05:00
refactor: move and order helper functions in GHCi.Run
A small refactor to the order of top-level functions in GHCi.Run
-
24927752
by Luite Stegeman at 2026-11-09T09:21:24-05:00
rts: add missing nonmoving write barrier in out-of-line array copies
The out-of-line entries stg_copyArrayzh/stg_copyMutableArrayzh (taken
whenever the element count of copyArray#/copyMutableArray# is not a
compile-time constant) didn't push the overwritten elements to the
nonmoving collector's remembered set.
Fixes #27376
-
6dbcca65
by Rodrigo Mesquita at 2026-11-09T09:22:06-05:00
interp: Set per-thread break flags consistently on eval/resume
Currently, the per-thread flags are:
- Single-step: Stop at the immediate next breakpoint in this thread
- Step-out: Stop at the next continuation with a breakpoint this thread
returns to.
- Break-on-exception: Stop the next time a synchronous exception is
raised in this thread.
Originally, these flags were all set globally across all threads. More
recently, these flags are set per-thread when `resume`ing that thread,
but globally when starting the evaluation of a new expression
(`evalStmt`).
With this commit, we now use per-TSO flags in both scenarios evaluating
expressions in the interpreter (`evalStmt` and `resumeStmt`).
- In `resumeStmt` we set the `EvalOpts` specifically in the `ThreadId`
being resumed.
- In `evalStmt`, we set the `EvalOpts` exclusively on the sandbox thread
we fork to evaluate the given expression
- When not using the sandbox thread (i.e. -fno-ghci-sandbox), we
don't support the debugger anyway, so the break flags are
irrelevant.
We do this by consistently calling `setBreakFlags` when starting,
resuming, or killing the evaluation.
See Note [Always setBreakFlags on running thread].
This slightly changes the behavior of evaluating a new expression in
the debugger (resuming a thread behaves the same as before). Namely,
`:step <expr>`, where <expr> forks a thread, will stop at the immediate
next breakpoint in the <expr> main thread, not on a breakpoint of any
forked thread.
NB: the forked thread may still stop at breakpoint, if it is enabled by
index specifically, and then :step-ing from that thread's breakpoint
will toggle per-thread stepping for that forked thread.
We will want to control stepping in "all threads, regardless of whether
we control them or if they were spawned by the debuggee" separately from
the commands which trigger evaluation of just an expression. Namely,
we'll likely want a "break at the next immediate breakpoint hit on ANY
thread" command that the user can execute before launching a debuggee
which is multi-threaded. This may even be the default for GHCi.
Towards #26064
Fixes #28080
-
19ff36f2
by Simon Jakobi at 2026-11-09T09:22:47-05:00
testsuite: Mark T8209 fragile for the ghci ways on FreeBSD and darwin
A shutdown race in the I/O manager intermittently fails T8209(ghci) on
x86_64-freebsd14-validate and aarch64-darwin-validate, recently killing
several Marge batches. Mark it fragile there until the race is fixed.
See #27948.
Assisted-by: Claude Opus 5.5
-
212c292f
by Rajkumar Natarajan at 2026-11-11T13:54:08-05:00
document what ->>> stands for in heap profile
updates the profiling section of the user's guide to explain how types
are approximated when using -hy. Also adds haddocks to getTyDescription
with the same information.
Fixes #26754
-
c64fc319
by Jonathan at 2026-11-11T13:54:55-05:00
Fix AArch64 veneer target for relocations with an addend
Fixes #27807
The RTS linker would construct invalid relocation veneers on AArch64 if
the addend was non-zero, which typically caused SIGILL crashes. This
could be triggered by evaluating Template Haskell in a package with a
large number of dependencies using a static build of GHC.
-
cd4dce19
by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
testsuite: add a test for registerFd_ trusting the callback table (#27821)
registerFd001 shows a 'threadWaitRead' that never finishes after an fd is
closed with 'closeFd' rather than 'closeFdWith'. Darwin is the only platform
this reaches -- one-shot registrations are implemented but not used there
(#7651) -- so the test is expect_broken on Darwin only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
5ab442ee
by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
registerFd_: always tell the polling backend (#27821)
Where the backend has no one-shot registrations, 'registerFd_' now tells it
about every registration, rather than only when the events differ from the
ones the callback table records: the table alone cannot say whether the
backend still knows the fd. The 'modify' it returns is unchanged. See Note
[Do not trust the callback table].
This fixes registerFd001 and clears its expect_broken.
Changelog wording from Duncan Coutts in review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
-
ab8b5b06
by Vladislav Zavialov at 2026-11-11T13:56:27-05:00
Curried contexts in prefix GADT constructors (#27424)
Prefix GADT constructor declarations now accept multiple consecutive
contexts, equivalent to a single conjoined context:
data G a where
MkCurried :: C a => (D a, E a) => G a
MkConjoined :: (C a, D a, E a) => G a
This is a step towards GHC Proposal #402 "Stable GADT constructor syntax".
To represent multiple contexts, the `con_mb_cxt` field of `ConDeclGADT` has
been replaced by `con_cxts`, which stores a list instead of a Maybe:
- con_mb_cxt :: Maybe (LHsContext pass)
+ con_cxts :: [LHsContext pass]
The rest of this patch follows from this change.
Note that in ConDeclH98, the optional context is still stored as a Maybe.
To accommodate this difference, a few helper functions were generalised over
a Foldable container `t`:
hsConDeclTheta :: Foldable t => t (LHsContext ...) -> [LHsType ...]
pprLHsContext :: (Foldable t, ...) => t (LHsContext ...) -> SDoc
repContexts :: Foldable t => t (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))
tcHsContext :: Foldable t => t (LHsContext GhcRn) -> TcM [PredType]
In practice, the instantiations of `t` are either `Maybe` or `[]`.
Record-style GADT constructors continue to accept at most one context.
`splitLHsGadtTy` accounts for this by splitting off only the first context
if it detects record syntax, leaving the offending part of the type in the
body for the renamer to reject later on.
Test cases: T12087a T27424a T27424b T27424c T27424d GadtConSigs_th_dump1
-
d2f135ff
by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: cache register usage in liveness annotations
regUsageOfInstr allocates fresh register lists on every call, and on the
linear allocator path it was called three times per instruction: in the
backward liveness pass, in the forward liveness pass and in the allocator
itself. Store the usage computed by the backward pass in the Liveness
annotation and reuse it in the other passes (and in the graph allocator's
spill passes). patchRegsLiveInstr recomputes it for the patched
instruction.
See Note [Cached register usage in liveness annotations].
Part of #28008.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
ff0a5d32
by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: describe register usage with a small DSL
This new register usage DSL (see Note [Register usage DSL] in
GHC.CmmToAsm.RegUsage) reduces allocation compared to the previous
list-based approach.
Fixes #28008.
Metric Decrease:
ManyAlternatives
T12707
T13035
T13379
T13960
T18698b
T19695
T21839c
T3064
T3294
T4801
T5321FD
T5321Fun
T783
T9198
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
51f38f3a
by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock-library: fix the build of the spec and fixtures test suites
The documentation pipeline moved from String to Text (commit 202ed264141)
but the two test suites of haddock-library were left behind and no
longer compiled. They are not run by GHC's CI (see #16206), so this went
unnoticed.
The fixtures suite still has four pre-existing failures (list-blocks1,
table1, table4, table5) that are not addressed here.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
-
394d9d6d
by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: parse backtick spans as monospaced text
A backtick span whose content is not a valid Haskell identifier, such as
`foo bar`, was rendered as plain text with literal backticks. It is now
parsed as monospaced text, like @foo bar@. A closed backtick span whose
whole content is one identifier keeps its meaning as a hyperlinked
identifier. A span such as `foldl' f z xs` is code: it is no longer read
as the identifier foldl between a backtick and a single quote. The
TeX-style form `foo' stays an identifier when no backtick closes the
span on the same line.
Code spans follow the CommonMark rules: a span opened by a run of N
backticks ends at the next run of exactly N backticks on the same line,
so ``x `plus` y`` is code "x `plus` y". One space is removed at each end
when both are present, and an unclosed opening run is plain text. The
content is literal: no markup is parsed and backslashes are kept, so
`\x -> x` renders as written.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Fixes #28090
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
7ae41c37
by Sylvain Henry at 2026-11-11T13:58:14-05:00
Use 'T' instead of `T' in Haddock comments next to backtick spans
With backtick code spans, a TeX-style quote `T' followed by a backtick on
the same line opens a code span up to that backtick. Use the 'T' form in
the Haddock comments where this happens.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
ce96f0b6
by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: do not parse backtick spans inside @...@
Text between @...@ is already code, so backtick code spans are no longer
parsed there. Thus in
@x <- f -- of type `M Bool`@
the backticks stay as text. Inline markup inside @...@, such as /.../,
passes this context down.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
744b3036
by Sylvain Henry at 2026-11-11T13:58:15-05:00
haddock: keep the backticks of infix identifiers inside @...@
A backticked identifier inside @...@ was always rendered without its
backticks, so @f `elem` xs@ rendered as "f elem xs". Now an identifier
in an infix application or an operator section, such as @f `elem` xs@
or @(`elem` xs)@, is parsed in infix form, as if written ``elem``, and
renders with its backticks and with elem linked. Elsewhere, as in
@`foldlM` :: ...@, the backticks still only mark the link.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
0d8e1f8d
by Sylvain Henry at 2026-11-11T13:59:05-05:00
PPC NCG: print non-standard NaN literals in target byte order
The PowerPC NCG printed a non-standard NaN literal byte by byte with
floatToBytes/doubleToBytes, which use the byte order of the host. This
is wrong when the host and the target have a different endianness (e.g.
from x86_64 to big-endian PowerPC). Print the bits with `.long`/`.quad`
instead, so that the assembler uses the target byte order.
Also make `ppr_item` print its argument: some clauses printed the
literal of `pprDataItem` instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
5a9db1ed
by Sylvain Henry at 2026-11-11T13:59:05-05:00
Print all NaN literals as integer bits (#28101)
The x86 and PowerPC NCGs printed the quiet NaNs 0x7fc00000 and
0x7ff8000000000000 as `.float NaN`/`.double NaN`. GNU as and clang
encode these with all mantissa bits set, so constant-folded bit casts
of these values gave 0x7fffffff/0x7fffffffffffffff. The C backend
printed every NaN as `NAN`, losing its sign and payload.
Now the NCGs print all NaNs with `.long`/`.quad` and the C backend with
hs_bitcastword2float/hs_bitcastword642double.
See Note [Printing NaN literals].
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
b4ceb6a9
by mangoiv at 2026-11-11T13:59:47-05:00
ci: fix ghcup nightly script misbehaviour
- download all jobs instead of just the first 100
- stop using a canary job to detect whether it's a nightly or release
pipeline
-
aefa0c1b
by Alan Zimmerman at 2026-11-11T14:00:28-05:00
EPA: Use AnnList in HsMultiIf
It introduces layout, capture it
-
f88c455f
by Duncan Coutts at 2026-11-12T15:31:22+00: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.
-
7b6cae3a
by Duncan Coutts at 2026-11-12T15:31:23+00: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.
-
840009f1
by Duncan Coutts at 2026-11-12T15:31:23+00: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.
-
efd97cfa
by Duncan Coutts at 2026-11-12T15:31:23+00: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.
-
3d866a67
by Duncan Coutts at 2026-11-12T15:31:23+00: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.
-
2fb4f52d
by Duncan Coutts at 2026-11-12T15:31:23+00: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.
-
9b217d9a
by Duncan Coutts at 2026-11-12T15:31:23+00:00
In the scheduler, move I/O blocking after deadlock detection
To make deadlock detection effective in the non-threaded RTS when there
are deadlocked threads and other unrelated threads waiting on I/O, we
need to arrange to do deadlock detection before we block in scheduler
to wait on I/O.
The solution is to:
1. adjust scheduleFindWork, which runs before deadlock detection, to
only poll for I/O and not block; and
2. add a step after deadlock detection to wait on I/O if there are
still no threads to run (and there's any I/O or timeouts outstanding)
The scheduleCheckBlockedThreads is now so simple that it made more sense
to inline it into scheduleFindWork.
-
408e976b
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Remove bogus anyPendingTimeoutsOrIO guard from scheduleDetectDeadlock
The deadlock detection was only invoked if both of these conditions
hold:
1. the run queue is empty
2. there is no pending I/O or timeouts
The second condition is unnecessary. The deadlock detection mechanism
can find deadlocks even if there are other threads waiting on I/O or
timers. Having this extra condition means that we fail to detect
blocked threads if there are any threads waiting on I/O or timers.
Part of fixing issue #26408
-
860040a9
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Don't consider pending I/O for early context switch optimisation
Context switches are normally initiated by the timer signal. If however
the user specifies "context switch as often as possible", with +RTS -C0
then the scheduler arranges for an early context switch (when it's just
about to run a Haskell thread).
Context switching very often is expensive, so as an optimisation there
cases where we do not arrange an early context switch:
1. if there's no other threads to run
2. if there is no pending I/O or timers
This patch eliminates case 2, leaving only case 1.
The rationale is as follows. The use of this was inconsistent across
platforms and threaded/non-threaded RTS ways. It only worked on the
non-threaded RTS and on Windows only worked for the win32-legacy I/O
manager. On all other combinations anyPendingTimeoutsOrIO would always
return false. The fact that nobody noticed and complained about this
inconsistency suggests that the feature is not relied upon.
If however it turns out that applications do rely on this, then the
proper thing to do is not to restore this check, but to add a new I/O
manager hint function that returns if there is any pending events that
are likely to happen *soon*: for example timeouts expiring within one
timeslice, or I/O waits on things likely to complete soon like disk I/O,
but not for example socket/pipe I/O.
The motivation to avoid this use of anyPendingTimeoutsOrIO is to
allow us to eliminate anyPendingTimeoutsOrIO entirely. All other uses
of this are just guards on {await,poll}CompletedTimeoutsOrIO and
the guards can safely be folded into those functions. This will better
cope with some I/O managers having no proper implementation of
anyPendingTimeoutsOrIO.
Ultimately this will let us simplify the scheduler which currently has
to have special #ifdef mingw32_HOST_OS cases to cope with the lack of a
working anyPendingTimeoutsOrIO for some Windows I/O managers
-
4659213b
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Remove anyPendingTimeoutsOrIO guarding {poll,await}CompletedTimeoutsOrIO
Previously the API of the I/O manager used a two step process: check
anyPendingTimeoutsOrIO and then call {poll,await}CompletedTimeoutsOrIO.
This was primarily there as a performance thing, to cheaply check if we
need to do anything.
And then because anyPendingTimeoutsOrIO existed, it was used for other
things too. We have now eliminated the other uses, and are just left
with the performance pattern.
But this was problematic because not all I/O managers correctly
implement anyPendingTimeoutsOrIO (specifically the win32 ones), and now
that we also make I/O managers responsible for signals then we need to
poll/await even if there is no pending I/O or timeouts. If there is no
pending I/O or timeouts then await needs to degenerate to just waiting
forever for any signals.
-
1bce3e3e
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Remove anyPendingTimeoutsOrIO, it is no longer used
And this avoids the problems arising from the win32 I/O managers having
had a bogus implementation.
-
cc31f72d
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Remove second scheduler call to awaitCompletedTimeoutsOrIO
Previously awaitCompletedTimeoutsOrIO was called both before and after
deadlock detection in the scheduler. The reason for that was that the
win32 I/O managers had a bogus implementation of anyPendingTimeoutsOrIO
and this was used to guard the call of awaitCompletedTimeoutsOrIO prior
to deadlock detection. This meant the first call site was never actually
called when using the win32 I/O managers. This was the reason for the
second call: the first one was never used. What a mess.
So now we have a simple design in the scheduler:
1. poll for completed I/O, timers or signals
2. if no runnable threads: do deadlock detection
3. if still no runnable threads: block waiting for I/O, timers or
signals.
-
8dd874f9
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Lift emptyRunQueue guard out of scheduleDetectDeadlock
this improved the clarity of the logic when reading the scheduler code.
And improve the comment about scheduleDoGC that was rather unclear.
-
68a85bd1
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Make interruptIOManager work for WinIO (non-threaded)
Fixes #27403
The idle GC scheme now fundamentally relies on interruptIOManager
working, so it's no longer acceptable for it to be missing for WinIO.
Not having it would cause lock ups.
-
63530f21
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Make non-threaded deadlock detection also rely on idle GC
Only do deadlock detection GC when idle GC kicks in. This also relies on
using wakeUpRts, so now do this unconditionally. Previously wakeUpRts
was for the threaded rts only.
-
00689edc
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Enable idle GC by default on non-threaded RTS
The behaviour is now uniform between the threaded and non-threaded RTS
ways. The deadlock detection now relies on idle GC for both threaded
and non-threaded ways. Previously deadlock detection did not rely on
idle GC for the non-threaded way.
Also tweak test T7275 to account for idle GC. This test's output is
sensitive to the number of major GCs run. Since this commit enables idle
GC for the non-threaded RTS, for this test that increases the number of
major GCs, since the test program is frequently idle for more than 300ms.
-
4a79f1c5
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Fix state of idle GC control vars with +RTS -V0
Currently when the user uses +RTS -I0, then doIdleGC is set to false.
But if the master tick interval -V is set to 0 then the idleGCDelayTime
was being set to 0 but doIdleGC was not being set to false, which is
inconsistent, and almost certainly buggy.
-
9c5947a1
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Add a long Note [Deadlock detection]
It describes the historical and modern designs and their trade-offs.
The point is we've now unified the code for deadlock detection between
the threaded and non-threaded ways, by changing the non-threaded to
follow the same design as the threaded.
-
c920f8fa
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Refactor the utils providing the I/O timeout for different system APIs
We have to provide a timeout in three different time formats (int
milliseconds, struct timeval *, and struct timespec *). These are for
platform APIs including poll, select, ppoll, pselect, epoll_wait,
epoll_wait2 and in future kevent and io_uring.
Previously we had one util for each format that both worked out what
the timeout should be and converted it into the particular format. This
duplicates some logic and it also makes it awkward to modify the timeout
value (since there's no common format).
Modifying the timeout value is exactly what we want to do, in a
subsequent commit, where we want to adjust the timeout to take account
of idle GC.
-
9eee7a66
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Update the old select I/O manager to use the new timeout utils
This will make it much easier to adjust the timeout to take account of
idle GC.
-
f4d806eb
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Add opportunistic deadlock detection without idle GC
Our general design is now that comprehensive deadlock detection relies
on idle GC. This allows us to detect partial deadlocks that are not
system deadlocks. But it's not prompt.
It's a nice to have feature to be able to promptly detect the cases that
are system deadlocks. There's no hope to do this in the threaded RTS
with -N > 1, but it can be done for the non-threaded RTS and _could_ be
done for the threaded RTS with -N1.
We can integrate this feature into the general design without too many
contortions. We just need the I/O managers to check before sleeping if
they would be about to sleep indefinately with no I/O and no registered
signal handlers. If so, they can notify the idle GC that we're
deadlocked and we schedule and idle GC.
-
218cb793
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Add idle GC mode for !HAVE_PREEMPTION
We have to do idle GC (and thus deadlock detection) differently when we
do not have the ticker and the ability to interrupt the I/O manager
when it's blocking.
-
4b0679f2
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Add and use USED_IF_PREEMPTION to avoid warnings
-
8b64caf5
by Duncan Coutts at 2026-11-12T15:31:23+00:00
Add performDeadlockDetection and export via ghc-experimental
When documenting the idle GC and deadlock detection behaviour in the
user guide, it becomes obiovus that in some cases one would want manual
control over deadlock detection.
In particular, for applications that disable idle GC, for debugging or
robustness, they may want to invoke deadlock detecting GC manually.
Bind it in ghc-internal GHC.Internal.System.Mem and re-export via
ghc-experimental in System.Mem.Experimental. It is clearly
implementation specific behaviour, especially since in GHC the deadlock
detection is tied to doing a major GC.
-
003e3198
by Duncan Coutts at 2026-11-12T15:31:57+00:00
Add tests for deadlock detection, issue #26408
We have three tests:
T26408a: make sure that we can detect a /partial deadlock/ that is not
also a /system deadlock/
T26408b: make sure that we can detect a /system deadlock/ promptly
without relying on idle GC
T26408c: make sure that we do not falsely detect a deadlock when there is
nothing to do except wait on signals
T26408d: make sure that we can detect a system deadlock with idle GC
disabled, after the idle GC timeout has elapsed.
-
18b9b068
by Duncan Coutts at 2026-11-12T15:31:59+00:00
Update the user guide with the revised idle GC behaviour
It's now not just for the threaded RTS, but general.
Add a new section in the RTS chapter: Idle GC and deadlock detection.
Provide general documentation on both topics. In particular, document
the behaviour of deadlock detection and how it depends on idle GC.
Move the existing entries for -I and -Iw to this section.
Add a changelog entry.
-
14635367
by Duncan Coutts at 2026-11-12T15:31:59+00:00
Remove variable n_haskell_handlers which has become write-only
-
5d0ceaaf
by Duncan Coutts at 2026-11-13T20:56:01+00:00
Remove use of (un)blockUserSignals in GC
Once upon a time, prior to 7ed3f7556f46b957f7efb97ed7ebdc92db2f8ab7 in
2009, the signal handlers were stored within the RTS as a table of
StablePtrs. This meant that the table could be accessed concurrently by
the C signal handler (picking out a Haskell signal handler when the
signal was delivered) and by the GC when it looks at the stable
pointers. To avoid problems, the relevant signals were masked around
this critical section in the GC.
The use of blockUserSignals/unblockUserSignals in the GC was missed
when the scheme was rewritten. We can safely remove it now. The GC no
longer has anything to do with the data structures within the RTS used
for signals.
This probably fixes #10686, by avoiding using blockUserSignals in the
GC, but the proper fix is later.
-
1492cb4b
by Duncan Coutts at 2026-11-13T20:56:01+00:00
Change sigprocmask to pthread_sigmask in a couple places in the rts
This is part of a series of changes to fix or remove uses of
sigprocmask. See issue #27968.
According to Posix:
> The use of the sigprocmask() function is unspecified in a
> multi-threaded process.
and indeed it does different things on different platforms. In
particular on macOS the behaviour is to change the signal mask for every
thread in the process (there is no per-process mask, it changes the
per-thread mask for every thread). This obviously does not mix well with
other concurrent changes to signal masks in other threads.
The use of sigprocmask in exitBySignal just needs to unmask a signal in
the current OS thread so that it can send a signal to itself. This
purpose only requires changing the signal mask of the calling thread,
which is exactly what pthread_sigmask is specified to do.
In resetTerminalSettings, sigprocmask (now pthread_sigmask) is used in
an attempt to mask a signal. It is unclear if this is effective. It
depends on whether there are any remaining threads running by the time
the function is called during shutdown.
Add a Note [pthread_sigmask and the ineffectiveness of masking signals]
and refer to it.
-
ebed5701
by Duncan Coutts at 2026-11-13T20:56:01+00:00
Change (un)blockUserSignals to use pthread_sigmask, not sigprocmask
These functions are exported from the RTS (on posix platforms). They are
used in the process library to temporarily mask signals during a fork().
This is only needed to ensure the new process has the signals masked
initially. So in particular for this use case we want it to only affect
the signal mask of the calling thread. Thus pthread_sigmask is
appropriate.
This probably fixes #10686. It should mean that there's no interaction
between threads that create new processes (which manipulate the signal
mask) and GC (which no longer uses blockUserSignals), or multiple
OS threads that create processes concurrently, because now they only
manipulate their local thread's signal mask.
-
0faff7e5
by Duncan Coutts at 2026-11-13T20:56:01+00:00
Make (un)blockUserSignals local functions in win32 console handling
These functions were defined for all platforms in the RTS public
headers but only exported from the RTS on non-win32 platforms. They are
only used externally (by the process library) on posix platforms.
So for win32, break the link with the exported names and use local only
C static functions. They do serve a local purpose, but are now unrelated
to the posix ones.
-
dace08ad
by Duncan Coutts at 2026-11-13T20:56:02+00:00
In System.Posix.Internals, change import of sigprocmask to pthread_sigmask
and refer to the Note. It's still pretty dubious!
-
c5b1a472
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Drop use of sigprocmask in stg_sig_install
It is somewhat unclear what the signal masking was trying to protect in
stg_sig_install. The comment said
// Block the signal until we figure out what to do
There are no shared data structured between stg_sig_install and the
generic_handler that it installs.
In any case, masking signals does not in general work, so whatever it
was doing was a false sense of security.
-
3d02e08e
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Make startPendingSignalHandlers a per-platform, not common, API
The direction of travel is that user-signal handling should be managed
by the I/O manager(s). This is because signals (& win32 console events)
are (a funny kind of) I/O, and also because they have to be involved in
noticing signals and starting signal handlers.
And how we communicate between the low level signal handler and starting
the Haskell signal handler threads is also speific to the I/O manager
implementation.
There is no need for a common API here. These are just utilities shared
between some I/O manager implementations.
-
91ee7c9e
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Unify freeSignalHandlers and finiUserSignals in RTS shutdown
They were called at different stages of shutdown. Historically this
might have made sense when the handler mechanism used stable pointers.
Now there appears to be no good reason.
On win32, freeSignalHandlers did nothing. On posix, finiUserSignals did
nothing. There appears to be no dependency on the stage of shutdown. It
is all local resources.
-
bdd40ccd
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Push checks on install_signal_handlers flag into signal functions
Also, change the logic slightly. The docs for --install-signal-handlers
say that it installs handlers for ctl-c etc. It does _not_ say that it
disables the API for Haskell code to install signal handerls. Previously
however the RTS startup code would guard initUserSignals behind the flag
install_signal_handlers. All that code does is initalise variables
properly. This meant that when user code installs a handler, it would be
working with ill-defined userSignals value and an un-initialised mutex!
Similarly, in the win32 console handling, it would skip initialising the
hConsoleEvent, which certainly cannot lead to good outcomes.
So now we only guard initDefaultHandlers and resetDefaultHandlers behind
the install_signal_handlers flag.
-
20cffb19
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Fix user guide reference to --install-signal-handlers
While reviewing --install-signal-handlers docs, noticed a typo in the
--generate-crash-dumps docs that referred to --install-signal-handlers
when it means --install-seh-handlers. Yes I double-checked the code.
-
99f1a974
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Split user signal functions out of posix/Signals into new file
The direction of travel is that user-signal handling should be managed
by the I/O manager(s).
The user signal functions (i.e. to allow Haskell code to set signal
handlers) should stop being first class functions called by the rest of
the RTS and become utilities used by the I/O managers.
Start here by splitting them out.
-
d79e31f4
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Make stg_sig_install part of the IOManager API
This is the external entry point for user code to install signal
handlers. So it becomes part of the I/O manager API. Eventually it will
dispatch to the I/O manager implementations (which will do different
things), but for now it dispatches to the same old implementation, under
a new name.
-
85a5f907
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Document that nocldstop is a totally mad implicit parameter
and it's part of our public API!
-
f62c8cf6
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Move user signal init and fini into the I/O manager
Initially just moved into start/stopIOManager, but a later step will be
to make that be part of the initialisation of each I/O manager.
Why? Because they cannot have a common init if they have different data
structures that need initialisation. In fact they already do have
different code and data (threaded/non-threaded, windows/other), but
this is fudged using CPP.
-
e0421f12
by Duncan Coutts at 2026-11-13T20:56:02+00:00
Push {init,fini}{UserSignals,ConsoleEvents} down into I/O managers
So they become part of individual I/O managers, which will allow us to
start specialising them more sanely.
Rename the Win32 ones to {init,fini}ConsoleEvents.
-
d843a737
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Push installUserSignalHandler down into individual I/O managers
This will allow us to specialise them.
Initally they all use the same (existing) generic_handler.
-
3c2f11b5
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Specialise MIO's installing of signals
It already used a separate implementation, but using cpp via the
signal "generic_handler". Now it is much more direct and local.
MIO writes signals into a pipe and reads and dispatches them at the
other end (in Haskell).
-
df8585b9
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Introduce an I/O manager data structure shared between all caps
Accessed via iomgr->shared, but it points to the same struct for all
capabilities.
We initialise and free this with cap 0. We will use it initially for
signal handling, since only one capability needs to dispatch signals.
This is a fairly general mechanism, so I/O managers may be able to make
use of it for other purposes, especially once in-RTS ones are adapted
to work in the threaded RTS with multiple capabilities.
-
4edfba2e
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Use the shared I/O manager data structure for MIO for signals
Move the MIO I/O manager's timer manager control fd from a global
variable into the shared I/O manager struct.
Soon we will use the same mechanism for the same purpose of signal
handling for the other posix I/O managers.
-
9af3913a
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Extract and add more utility functions for the signal self-pipe trick
Extract a utility function writeSignalInfoToPipe from the MIO I/O
manager so we can use it in other I/O managers too.
Also add related utility functions readSignalInfoFromPipe,
newNonBlockingPipe and startSignalHandler.
We will use these in the poll and selectbis I/O managers.
-
3400b8e8
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Redo the scheme for special fds in the poll and selectbis I/O managers
At the moment we only have one special fd for these I/O managers: the
pipe (or eventfd) for interrupting them when they're sleeping. We're
about to gain a second for signal handling.
The existing scheme was rather ad-hoc and hard to extend. It was
already complicated by the fact that the interrupt fd is optional. The
signal fd will also be optional in the sense that cap 0 will have it but
cap >0 will not.
So the new scheme is that we add special aiop entries into the
aiop_table, and for the most part we can treat these uniformly with
other aiops. But the action we take for them if/when they are ready is
handled specially.
This seems much cleaner and will be easy to extend for signals.
-
c51fcae9
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Use the signal self-pipe trick for the poll and selectbis I/O managers
So now the low level signal handler delivers signals into a pipe that is
monitored by the I/O manager (on cap 0). The I/O manager then dispatches
the handler (starting a Haskell thread).
There are two important reasons for this change:
1. This method does not have any windows of time where signals can be
missed for arbitrary periods of time. The previous method has a race
where a signal delivered just before the I/O manager calls
poll/select will not notice the signal until some unrelated event
causes poll/select to return. See issue #27540. The new method
ensures that a fd is ready and so poll/select will notice
immediately (if the signal was delivered prior to the call to
poll/select) or later.
2. The existing method relies on temporarily masking signals for
concurrency safety which cannot work reliably in a multi-threaded
process. Fixing this is a necessary pre-requisite to enable these
in-RTS I/O managers to work in the threaded RTS. The issue is that
startPendingSignalHandlers and the low level signal handler share the
pending_handler_buf data structure, and so startPendingSignalHandlers
has to mask delivery of signals to avoid the shared data being
mutated concurrently. But masking signals in a multi-threaded process
is not generally effective because the signal can still be delivered
in any thread
Document the self-pipe trick in a Note.
This fixes issue #27540.
-
c5db765d
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Move the legacy user signal handler into legacy select I/O manager
We do not convert the legacy select I/O manager to use the self-pipe
trick. It keeps the existing code, but since it is now the only user of
it, then that code can move from being a shared utility to live with the
select I/O manager.
There are some minor modifications to the code moved so that it is not
entangled with other remaining shared signal utils.
-
5f4db120
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Deprecate (un)blockUserSignals for external RTS users
Encourage external users to stop using these actions.
-
d994f5ab
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Split interruptStgRts and remove wakeUpRtsViaTicker.
Split the two uses of interruptStgRts into their posix and win32 cases,
and move them to their use sites.
Make the posix case not rely on wakeUpRts or wakeUpRtsViaTicker. The use
of wakeUpRtsViaTicker while it seemed to cleverly solve overly-close
coupling in one area, causes overly-close coupling in another area:
ticker(s). And we want to start improving the ticker(s) but the
existence of wakeUpRtsViaTicker holds that back.
Delete wakeUpRtsViaTicker and its related implementation pieces.
In the posix case, we add interruptIOManagerFromSignal, which is
specific for the circumstance of use within a signal handler. The
implementation of this for the in-RTS I/O managers is just
interruptIOManager but for MIO it has to wake up the timer manager
thread.
All of this seems pretty unnecessary since it is all to support a ctl-c
handler that is almost never used since it is duplicated and overridden
by a ctl-c handler installed by runMainIO. See issue #28066.
-
4b5c2c2c
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Simplify execution of signal handlers
We make a few related changes:
1. Don't use malloc/free for passing siginfo_t from C to Haskell, use
heap allocated byte arrays indead. The Haskell side already uses
ForeignPtr which can use byte array directly.
2. Don't redundantly fork IO threads for signal handlers, when invoked
from in-RTS I/O managers. The I/O manager already creates a new IO
thread, but the existing runHandlers would then redundantly forkIO
again. This is a waste of resources but also means signal handlers
end up getting scheduled last.
3. Schedule signal handler threads first.
This should fix #28067
Introduce new runHandler/runHandlerPtr to replace the existing
runHandlers/runHandlersPtr. Conveniently the old ones have a weird name
(they only invoke one handler!) so we can use a sensible name, and leave
the old ones (which are exported via base!) alone. Add deprecation
warnings though, since nobody should be using them via base.
Update the caller in ghc-internal: the MIO timer manager. This one does
need to use forkIO, but it's clearer if that forkIO is done there.
-
1389a163
by Duncan Coutts at 2026-11-13T21:24:07+00:00
Stop using signal-unsafe functions in signal handlers
Fixes #19205
Unfortunately this does mean that the SIGQUIT functionality of dumping a
stack trace has to be disabled for now. There's no short term practical
way to allow that to work. The stack trace functions all use dynamic
memory allocation using malloc/free, which is verboten in signal
handlers.
See #28071 about re-enabling the stack trace info.
-
ecc9b051
by Duncan Coutts at 2026-11-13T21:24:08+00:00
Add a changelog entry for the signals changes