[Git][ghc/ghc][wip/jeltsch/portable-bco-byte-array-serialization] Switch from boolean to definedness test for `LITTLE_ENDIAN_64_BITS`
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
26 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC
Commits:
773f0fda by Wolfgang Jeltsch at 2026-11-26T17:28:30+02:00
Switch from boolean to definedness test for `LITTLE_ENDIAN_64_BITS`
- - - - -
1 changed file:
- libraries/ghci/GHCi/ResolvedBCO.hs
Changes:
=====================================
libraries/ghci/GHCi/ResolvedBCO.hs
=====================================
@@ -20,7 +20,9 @@ module GHCi.ResolvedBCO
#error Bytecode serialization works only on 32- and 64-bit platforms.
#endif
-#define LITTLE_ENDIAN_64_BITS (!defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8)
+#if !defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8
+#define LITTLE_ENDIAN_64_BITS
+#endif
import Prelude -- See note [Why do we import Prelude here?]
@@ -41,7 +43,7 @@ import Foreign.Storable (Storable, sizeOf)
import GHC.Data.SmallArray (SmallArray)
import GHC.Generics (Generic)
-#if !LITTLE_ENDIAN_64_BITS
+#ifndef LITTLE_ENDIAN_64_BITS
import Control.Monad (replicateM)
#endif
@@ -100,7 +102,7 @@ data BCOByteArray a
getBCOByteArray :: !ByteArray#
}
-#if !LITTLE_ENDIAN_64_BITS
+#ifndef LITTLE_ENDIAN_64_BITS
fromBCOByteArray :: Storable a => BCOByteArray a -> UArray Int a
fromBCOByteArray @a (BCOByteArray ba#) = UArray 0 (n - 1) n ba#
@@ -148,7 +150,7 @@ instance Binary ResolvedBCO where
1 -> ResolvedStaticCon <$> get <*> get <*> get <*> get <*> get <*> get
_ -> error "Binary ResolvedBCO: invalid byte"
-#if !LITTLE_ENDIAN_64_BITS
+#ifndef LITTLE_ENDIAN_64_BITS
-- | Serialize a 'BCOByteArray', not writing the payload verbatim but
-- serializing the individual elements. This can be used with any host
@@ -225,7 +227,7 @@ instance Binary (BCOByteArray Word16) where
-- See Note [BCOByteArray serialization].
instance Binary (BCOByteArray Word) where
-#if LITTLE_ENDIAN_64_BITS
+#ifdef LITTLE_ENDIAN_64_BITS
put = putBCOByteArrayDirectly
get = getBCOByteArrayDirectly
#else
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/773f0fdac74241a9f96b5598eb26d76…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/773f0fdac74241a9f96b5598eb26d76…
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/jeltsch/portable-bco-byte-array-serialization] Switch to using `#ifdef` and `#ifndef`
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
26 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC
Commits:
fce533d8 by Wolfgang Jeltsch at 2026-11-26T17:26:05+02:00
Switch to using `#ifdef` and `#ifndef`
- - - - -
1 changed file:
- libraries/ghci/GHCi/ResolvedBCO.hs
Changes:
=====================================
libraries/ghci/GHCi/ResolvedBCO.hs
=====================================
@@ -46,7 +46,7 @@ import Control.Monad (replicateM)
#endif
isLittleEndian :: Bool
-#if defined(WORDS_BIGENDIAN)
+#ifdef WORDS_BIGENDIAN
isLittleEndian = False
#else
isLittleEndian = True
@@ -183,7 +183,7 @@ getBCOByteArrayPortably getElement = do
#endif
-#if !defined(WORDS_BIGENDIAN)
+#ifndef WORDS_BIGENDIAN
-- | Serialize a 'BCOByteArray', writing the payload verbatim instead of
-- serializing the individual elements. This must only be used when the host
@@ -214,7 +214,7 @@ getBCOByteArrayDirectly @a = do
-- See Note [BCOByteArray serialization].
instance Binary (BCOByteArray Word16) where
-#if defined(WORDS_BIGENDIAN)
+#ifdef WORDS_BIGENDIAN
put = putBCOByteArrayPortably putWord16le
get = getBCOByteArrayPortably getWord16le
#else
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fce533d895359134b292f0f31a0918c…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fce533d895359134b292f0f31a0918c…
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/jeltsch/portable-bco-byte-array-serialization] Introduce and use a macro `LITTLE_ENDIAN_64_BITS`
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
26 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC
Commits:
4a46820f by Wolfgang Jeltsch at 2026-11-26T17:20:30+02:00
Introduce and use a macro `LITTLE_ENDIAN_64_BITS`
- - - - -
1 changed file:
- libraries/ghci/GHCi/ResolvedBCO.hs
Changes:
=====================================
libraries/ghci/GHCi/ResolvedBCO.hs
=====================================
@@ -20,6 +20,8 @@ module GHCi.ResolvedBCO
#error Bytecode serialization works only on 32- and 64-bit platforms.
#endif
+#define LITTLE_ENDIAN_64_BITS (!defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8)
+
import Prelude -- See note [Why do we import Prelude here?]
import GHCi.RemoteTypes
@@ -39,7 +41,7 @@ import Foreign.Storable (Storable, sizeOf)
import GHC.Data.SmallArray (SmallArray)
import GHC.Generics (Generic)
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
+#if !LITTLE_ENDIAN_64_BITS
import Control.Monad (replicateM)
#endif
@@ -98,7 +100,7 @@ data BCOByteArray a
getBCOByteArray :: !ByteArray#
}
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
+#if !LITTLE_ENDIAN_64_BITS
fromBCOByteArray :: Storable a => BCOByteArray a -> UArray Int a
fromBCOByteArray @a (BCOByteArray ba#) = UArray 0 (n - 1) n ba#
@@ -146,7 +148,7 @@ instance Binary ResolvedBCO where
1 -> ResolvedStaticCon <$> get <*> get <*> get <*> get <*> get <*> get
_ -> error "Binary ResolvedBCO: invalid byte"
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
+#if !LITTLE_ENDIAN_64_BITS
-- | Serialize a 'BCOByteArray', not writing the payload verbatim but
-- serializing the individual elements. This can be used with any host
@@ -223,12 +225,12 @@ instance Binary (BCOByteArray Word16) where
-- See Note [BCOByteArray serialization].
instance Binary (BCOByteArray Word) where
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
- put = putBCOByteArrayPortably (putWord64le . fromIntegral)
- get = getBCOByteArrayPortably (fromIntegral <$> getWord64le)
-#else
+#if LITTLE_ENDIAN_64_BITS
put = putBCOByteArrayDirectly
get = getBCOByteArrayDirectly
+#else
+ put = putBCOByteArrayPortably (putWord64le . fromIntegral)
+ get = getBCOByteArrayPortably (fromIntegral <$> getWord64le)
#endif
-- Note [BCOByteArray serialization]
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/4a46820fb7cea7a57869a071729b605…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/4a46820fb7cea7a57869a071729b605…
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] Simplifier: treat unlifted data-con fields as strict (#28169)
by Simon Peyton Jones (@simonpj) 26 Nov '26
by Simon Peyton Jones (@simonpj) 26 Nov '26
26 Nov '26
Simon Peyton Jones pushed to branch wip/T28169 at Glasgow Haskell Compiler / GHC
Commits:
750032e3 by Simon Peyton Jones at 2026-11-26T14:52:56+00:00
Simplifier: treat unlifted data-con fields as strict (#28169)
The Simplifier's fast path for "lazy" data constructors (no bangs) also
caught constructors with /unlifted/ fields, such as I# or (#,#). So
I# (case x of (a,b) -> a#)
did not get the StrictArg treatment, and the case was not floated out
to give (case x of (a,b) -> I# a#). This patch fixes that, and tidies
up quite a bit along the way.
* GHC.Core.DataCon
- `dcStricts` now always lines up 1-1 with `dataConRepArgTys`
(it used to be [] for an all-lazy constructor).
- New field `dcArgCbvInfos :: [ArgCbvInfo]`, one per /value/ argument of
the worker, /including/ existential coercion variables:
data ArgCbvInfo = ArgCbv | ArgCbn | ArgRepPoly
ArgCbv means "certainly evaluated" (a bang, or an unlifted type).
See Note [ArgCbvInfo], which explains why consumers treat ArgRepPoly
conservatively, but in opposite directions.
- Including the existential CoVars fixes a latent misalignment between
the strictness marks and the worker's value arguments; see (EXCO1) in
Note [Existential coercion variables].
- New field `dcIsLazy`: all arguments are ArgCbn.
The consumers (the worker's demand signature, dmdTransformDataConSig,
exprIsHNF, exprOkForSpeculation, SpecConstr, adjustFieldsIdInfo,
mkDupableAlt) now use `dataConRepArgCbvInfos`, or `dataConRepStrictness`
where the CoVars have already been dropped.
* Unary classes (#28183). (MkC e) is just `e`, so it is a value, or
ok-for-speculation, only if `e` is. exprIsHNF had a special case for
this, but app_ok did not, and so claimed that (MkC e) was always
ok-for-speculation. Now both have a special case. We do /not/ achieve
this by giving MkC a strict field: that leaks into DmdAnal, StrictArg
and the field seqs of Note [Strict fields in Core], and made T5321FD
allocate 10% more. See (UCM3b) in Note [Unary class magic].
* Simplifier: see Note [Simplifying data constructor applications]
- (SDC1) A completely lazy constructor still zooms straight to `rebuild`.
- (SDC2) Any other constructor goes straight to `rebuildCall`, skipping
simplOutId, with a new, much smaller, form of ArgInfo:
DataConArgInfo { ai_dc_app :: OutExpr, ai_dc_args :: [ArgCbvInfo] }
which has its own, much simpler, equation in `rebuildCall`. It needs
no rules, discounts, bottoming check or ArgSpec list. It is never
duplicated by Plan A of Note [Duplicating StrictArg]; see (DJ4).
* Making rebuildCall cheaper (it handles every function application, so
this benefits all programs):
- The general case of `rebuildCall` takes the ArgInfo apart once and
loops over the pieces that change, rather than allocating a fresh
ArgInfo for every argument.
- `ai_dmds` is now a `DmdType` rather than an infinite list of demands;
use the new `GHC.Types.Demand.splitArgDmd`. So we never build
(demands ++ repeat topDmd); and for a data constructor we can use the
worker's demand signature directly.
- `simplArg` no longer takes a `Maybe ArgInfo`; the one caller that
wanted an informative Stop continuation (rebuildCall) does it itself.
- The CallCtxt and SubDemand fields of `Stop` are strict.
- Rename `ai_fun` to `ai_fun_id`.
* Add `GHC.Utils.Misc.mapConst`, and use it for the many (map (const x) xs).
Compile-time allocation, relative to master, measured locally with stage-1
compilers (before the Simplifier improvements, CI showed T5321FD +10.5%,
T9961 +4.7%, T9020 +2.4%, T15164 +2.4%):
T5321FD -0.1%
T9961 -0.3%
T9020 +0.6%
T15164 -0.6%
Test: simplCore/should_compile/T28169
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
23 changed files:
- compiler/GHC/Builtin/WiredIn/Types.hs
- compiler/GHC/Core/DataCon.hs
- compiler/GHC/Core/FamInstEnv.hs
- compiler/GHC/Core/Opt/DmdAnal.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/Utils.hs
- compiler/GHC/Core/SimpleOpt.hs
- compiler/GHC/Core/TyCon.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Pat.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Build.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/TyCl/Utils.hs
- compiler/GHC/Types/Demand.hs
- compiler/GHC/Types/Id/Make.hs
- compiler/GHC/Utils/Misc.hs
- + testsuite/tests/simplCore/should_compile/T28169.hs
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Builtin/WiredIn/Types.hs
=====================================
@@ -626,7 +626,7 @@ typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol")
pcTyCon :: Name -> Maybe (CType GhcTc) -> [TyVar] -> [DataCon] -> TyCon
pcTyCon name cType tyvars cons
= mkAlgTyCon name (mkTyConKind bndrs res_kind) bndrs 0 res_kind
- (map (const Representational) tyvars)
+ (mapConst Representational tyvars)
cType
[] -- No stupid theta
(mkDataTyConRhs cons)
@@ -717,9 +717,10 @@ pcDataConWithFixity' declared_infix dc_name wrk_key rri
-- we call pcDataConWithFixity' with static TyCons in the same module.
-- See Note [Constructor tag allocation] and #14657
data_con = mkDataCon dc_name declared_infix prom_info
- (map (const no_bang) arg_tys)
- (map (const HsLazy) arg_tys)
- (map (const NotMarkedStrict) arg_tys)
+ (mapConst no_bang arg_tys)
+ (mapConst HsLazy arg_tys)
+ (mapConst NotMarkedStrict theta ++
+ mapConst NotMarkedStrict arg_tys)
[] -- No labelled fields
tyvars ex_tyvars
conc_tyvars
=====================================
compiler/GHC/Core/DataCon.hs
=====================================
@@ -44,14 +44,15 @@ module GHC.Core.DataCon (
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
- dataConRepStrictness,
+ dataConRepStrictness, dataConRepArgCbvInfos,
+ ArgCbvInfo(..), argCbvInfoStrictnessMark,
dataConImplBangs, dataConBoxer,
+ dataConRepIsLazy,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon,
- isLazyDataConRep,
isTupleDataCon, isBoxedTupleDataCon, isUnboxedTupleDataCon,
isUnboxedSumDataCon, isCovertGadtDataCon, isUnaryClassDataCon,
isVanillaDataCon, isNewDataCon, isTypeDataCon, isBoxingDataCon,
@@ -523,17 +524,37 @@ data DataCon
-- See Note [Bangs on data constructor arguments]
dcStricts :: [StrictnessMark],
- -- One mark for every field of the DataCon worker;
- -- if it's empty, then all fields are lazy,
- -- otherwise 1-1 with dataConRepArgTys.
+ -- One mark for every field of the DataCon /worker/
+ -- INVARIANT: length dcStricts = length dataConRepArgTys
+ -- Relates only to user-specified strictness annotations,
+ -- not to liftedness or otherwise
+ -- E.g. data T a = MkT {-# UNPACK #-} !(S a) Int# !a
+ -- data S a = MkS a !a
+ -- Then the worker for MkT has four fields, the first two arising from
+ -- unpacking S. The corresponding strictness marks are [-,!,-,!]; again
+ -- the first two come from MkS
-- See also Note [Strict fields in Core] in GHC.Core
- -- for the effect on the strictness signature
+ -- for the effect on the strictness signature
+
+ dcArgCbvInfos :: [ArgCbvInfo],
+ -- One entry for each /value/ argument of the worker,
+ -- /including/ each CoVar in dcExTyCoVars
+ -- Unlike dcStricts, takes account of liftedness
+ -- INVARIANT: length dcArgCbvInfos = dataConRepArity
+ -- See (EXCO1) Note [Existential coercion variables]
+ -- and Note [ArgCbvInfo]
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
+ dcIsLazy :: Bool,
+ -- True <=> all of dcArgCbvInfos are ArgCbn; that is
+ -- (a) all fields of the data con /worker/ are definitely lifted
+ -- (b) no field has a `StrictnessMark` that forces evaluation
+ -- So if `dcIsLazy` is True then all fields of the worker are lazy thunks
+
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
@@ -582,18 +603,30 @@ we can in Core. Consider having:
data T :: forall k. k -> k -> Constraint where
MkT :: forall k (a::k) (b::k).
- forall k' (c::k') (co::k'~k).
- (b ~# (c|>co)) => T k a b
+ forall k' (c::k') (co::k'~#k).
+ (b ~# (c|>co)) => !a -> T k a b
dcUnivTyVars = [k,a,b]
dcExTyCoVars = [k',c,co]
dcUserTyVarBinders = [k,a,k',c]
dcEqSpec = [b ~# (c|>co)]
dcOtherTheta = []
- dcOrigArgTys = []
+ dcOrigArgTys = [a]
dcRepTyCon = T
+ dcStricts = [NotMarkedStrict, MarkedStrict]
+ dcArgCbvInfos = [ArgCbv, ArgCbv, ArgCbv] -- (EXCO1)
+
+* `dataConKindEqSpec` returns [k'~k].
+* `dataConRepArgTys` returns [ b~#(c|>co), a ]
+
+(EXCO1) In a call of the data constructor worker we will see
+ MkT tk ta tb tk' tc (co1::tk'~#tk) (co2::tb~#(tc |> co1))
+ dcArgCbvInfos returns a [ArgCbvInfo] that lines up with all the
+ value arguments, /including/ co1. (Coercion arguments are unlifted,
+ hence ArgCbv; see Note [ArgCbvInfo].)
-Function call 'dataConKindEqSpec' returns [k'~k]
+ dcArgCbvInfos lines up with dcStricts almost always; they differ in length
+ only in the rare case that we have existential coercion variables
Note [DataCon arities]
~~~~~~~~~~~~~~~~~~~~~~
@@ -830,7 +863,7 @@ data DataConRep
, dcr_boxer :: DataConBoxer
- , dcr_arg_tys :: [Scaled Type] -- Final, representation argument types,
+ , dcr_arg_tys :: [Scaled Type] -- Final, representation /value/ argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
@@ -853,7 +886,8 @@ type DataConEnv a = UniqFM DataCon a -- Keyed by DataCon
-- In the AST, the @SourceText@ is hidden inside the extension point
-- 'Language.Haskell.Syntax.Extension.XConDeclField'.
data HsSrcBang
- = HsSrcBang SourceText SrcUnpackedness SrcStrictness -- See Note [Pragma source text] in "GHC.Types.SourceText"
+ = HsSrcBang SourceText SrcUnpackedness SrcStrictness
+ -- See Note [Pragma source text] in "GHC.Types.SourceText"
deriving Data.Data
-- | Haskell Implementation Bang
@@ -861,14 +895,14 @@ data HsSrcBang
-- Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
- = HsLazy -- ^ Lazy field, or one with an unlifted type
+ = HsLazy -- ^ Lazy field, or one with an unlifted type
+
| HsStrict Bool -- ^ Strict but not unpacked field
- -- True <=> we could have unpacked, but opted not to
- -- because of -O0.
- -- See Note [Detecting useless UNPACK pragmas]
- | HsUnpack (Maybe Coercion)
- -- ^ Strict and unpacked field
- -- co :: arg-ty ~ product-ty HsBang
+ -- True <=> we could have unpacked, but opted not to because of -O0
+ -- See Note [Detecting useless UNPACK pragmas]
+
+ | HsUnpack (Maybe Coercion) -- ^ Strict and unpacked field
+ -- co :: arg-ty ~ product-ty HsBang
deriving Data.Data
@@ -879,6 +913,51 @@ data HsImplBang
data StrictnessMark = MarkedStrict | NotMarkedStrict
deriving Eq
+-- | How a data constructor worker treats one of its value arguments
+-- See Note [ArgCbvInfo]
+data ArgCbvInfo
+ = ArgCbn -- ^ Call-by-need: definitely lifted, and no bang:
+ -- the worker does not evaluate the argument
+ | ArgCbv -- ^ Call-by-value: definitely unlifted, or has a bang
+ -- (MarkedStrict): the argument is certainly evaluated
+ | ArgRepPoly -- ^ No bang, but representation-polymorphic,
+ -- so we don't know whether it is lifted or not
+ deriving Eq
+
+argCbvInfoStrictnessMark :: ArgCbvInfo -> StrictnessMark
+-- Conservative: ArgRepPoly might be lifted, so NotMarkedStrict
+argCbvInfoStrictnessMark ArgCbv = MarkedStrict
+argCbvInfoStrictnessMark ArgCbn = NotMarkedStrict
+argCbvInfoStrictnessMark ArgRepPoly = NotMarkedStrict
+
+{- Note [ArgCbvInfo]
+~~~~~~~~~~~~~~~~~~~~
+`dcArgCbvInfos :: [ArgCbvInfo]` tells, for each value argument of a data
+constructor worker, whether that argument is certainly evaluated
+(ArgCbv), certainly not evaluated (ArgCbn), or we don't know
+(ArgRepPoly, e.g. the fields of an unboxed tuple (#,#), whose types
+are representation-polymorphic until instantiated).
+
+An argument is evaluated if it has an unlifted type, or if it is a strict
+field (see Note [Strict fields in Core] in GHC.Core). For many purposes
+these are the same thing, so we combine them here; e.g. both
+ K (case x of (a,b) -> a) where K has a strict field
+ I# (case x of (a,b) -> a#)
+should become (case x of (a,b) -> K a) in the Simplifier (#28169).
+
+Consumers must decide what to do with ArgRepPoly, and the right choice
+depends on the consumer, in opposite directions:
+
+* `GHC.Core.Opt.Simplify.Utils.dataConArgInfo` treats ArgRepPoly as /lazy/.
+ There "strict" licenses the StrictArg transformation, which is only an
+ optimisation; claiming laziness is always safe.
+
+* `exprIsHNF` (check_field) and `exprOkForSpeculation` (field_ok) in
+ GHC.Core.Utils treat ArgRepPoly as /possibly strict/. There, wrongly
+ claiming laziness would wrongly say that (K e) is a value even if `e`
+ is an unlifted expression that might diverge.
+-}
+
-- | An 'EqSpec' is a tyvar/type pair representing an equality made in
-- rejigging a GADT constructor
data EqSpec = EqSpec TyVar Type
@@ -950,9 +1029,8 @@ Terminology:
you the demand signature of the wrapper, if it exists.
These demand signatures are set in GHC.Types.Id.Make.mkDataConWorkId,
- computed from the single source of truth `dataConRepStrictness`, which is
- generated from `dcStricts`.
- Note that `dataConRepStrictness` lines up 1-1 with `idDmdSig (dataConWorkId dc)`.
+ computed from the single source of truth `dataConRepArgCbvInfos`.
+ So `dataConRepArgCbvInfos` lines up 1-1 with `idDmdSig (dataConWorkId dc)`.
Note [Detecting useless UNPACK pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1032,6 +1110,11 @@ instance Outputable StrictnessMark where
ppr MarkedStrict = text "!"
ppr NotMarkedStrict = empty
+instance Outputable ArgCbvInfo where
+ ppr ArgCbn = text "cbn"
+ ppr ArgCbv = text "cbv"
+ ppr ArgRepPoly = text "rep-poly"
+
instance Binary StrictnessMark where
put_ bh NotMarkedStrict = putByte bh 0
put_ bh MarkedStrict = putByte bh 1
@@ -1118,7 +1201,7 @@ mkDataCon name declared_infix prom_info
impl_bangs -- Must match orig_arg_tys 1-1
str_marks -- Must be empty or match dataConRepArgTys 1-1
fields
- univ_tvs ex_tvs conc_tvs user_tvbs
+ univ_tvs ex_tcvs conc_tvs user_tvbs
eq_spec theta
orig_arg_tys orig_res_ty rep_info rep_tycon tag
stupid_theta work_id rep
@@ -1132,44 +1215,62 @@ mkDataCon name declared_infix prom_info
= con
where
- is_vanilla = null ex_tvs && null eq_spec && null theta
- str_marks' | not $ any isMarkedStrict str_marks = []
- | otherwise = str_marks
-
- con = MkData {dcName = name, dcUnique = nameUnique name,
- dcVanilla = is_vanilla, dcInfix = declared_infix,
- dcUnivTyVars = univ_tvs,
- dcExTyCoVars = ex_tvs,
- dcConcreteTyVars = conc_tvs,
- dcUserTyVarBinders = user_tvbs,
- dcEqSpec = eq_spec,
- dcOtherTheta = theta,
- dcStupidTheta = stupid_theta,
- dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
- dcRepTyCon = rep_tycon,
- dcSrcBangs = arg_stricts, dcImplBangs = impl_bangs,
- dcStricts = str_marks',
- dcFields = fields, dcTag = tag, dcRepType = rep_ty,
- dcWorkId = work_id,
- dcRep = rep,
- dcSourceArity = length orig_arg_tys,
- dcRepArity = length rep_arg_tys + count isCoVar ex_tvs,
- dcPromoted = promoted }
+ is_vanilla = null ex_tcvs && null eq_spec && null theta
+ full_arg_info = replicate n_ex_co_vars ArgCbv -- Coercions are unlifted
+ ++ zipWith mk_arg_info str_marks rep_arg_tys
+ mk_arg_info str (Scaled _ ty)
+ | isMarkedStrict str = ArgCbv
+ | definitelyLiftedType ty = ArgCbn
+ | definitelyUnliftedType ty = ArgCbv
+ | otherwise = ArgRepPoly
+ is_lazy = all (== ArgCbn) full_arg_info
+
+ con = MkData { dcName = name
+ , dcUnique = nameUnique name
+ , dcInfix = declared_infix
+ , dcTag = tag
+ , dcVanilla = is_vanilla
+
+ , dcUnivTyVars = univ_tvs
+ , dcExTyCoVars = ex_tcvs
+ , dcConcreteTyVars = conc_tvs
+ , dcUserTyVarBinders = user_tvbs
+ , dcEqSpec = eq_spec
+ , dcOtherTheta = theta
+ , dcStupidTheta = stupid_theta
+ , dcOrigArgTys = orig_arg_tys
+ , dcOrigResTy = orig_res_ty
+
+ , dcRep = rep
+ , dcRepType = rep_ty
+ , dcRepTyCon = rep_tycon
+ , dcSrcBangs = arg_stricts
+ , dcImplBangs = impl_bangs
+ , dcStricts = assertPpr (equalLength str_marks rep_arg_tys)
+ (ppr name <+> ppr str_marks)
+ str_marks
+ , dcArgCbvInfos = full_arg_info
+ , dcIsLazy = is_lazy
+ , dcFields = fields
+ , dcWorkId = work_id
+ , dcSourceArity = length orig_arg_tys
+ , dcRepArity = n_ex_co_vars + length rep_arg_tys
+ , dcPromoted = promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
- rep_arg_tys = dataConRepArgTys con
+ n_ex_co_vars = count isCoVar ex_tcvs
+ rep_arg_tys = dataConRepArgTys con
- rep_ty =
- case rep of
+ rep_ty = case rep of
-- If the DataCon has no wrapper, then the worker's type *is* the
-- user-facing type, so we can simply use dataConWrapperType.
NoDataConRep -> dataConWrapperType con
-- If the DataCon has a wrapper, then the worker's type is never seen
-- by the user. The visibilities we pick do not matter here.
- DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tvs $
+ DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tcvs $
mkScaledFunctionTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
-- res_arg_tys is a mixture of TypeLike and ConstraintLike,
@@ -1192,8 +1293,8 @@ mkDataCon name declared_infix prom_info
prom_res_kind roles rep_info
roles = map (\tv -> if isTyVar tv then Nominal else Phantom)
- (univ_tvs ++ ex_tvs)
- ++ map (const Representational) (theta ++ map scaledThing orig_arg_tys)
+ (univ_tvs ++ ex_tcvs)
+ ++ mapConst Representational (theta ++ map scaledThing orig_arg_tys)
freshNames :: [Name] -> [Name]
-- Make an infinite list of Names whose Uniques and OccNames
@@ -1399,20 +1500,19 @@ isNullarySrcDataCon dc = dataConSourceArity dc == 0
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
-isLazyDataConRep :: DataCon -> Bool
--- ^ True <==> All fields are lazy
-isLazyDataConRep dc = null (dcStricts dc)
-
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the runtime arguments of a Core DataCon worker
--- application.
--- The length of the list matches `dataConRepArgTys` (e.g., the number
--- of runtime arguments).
-dataConRepStrictness dc
- | isLazyDataConRep dc
- = replicate (dataConRepArity dc) NotMarkedStrict
- | otherwise
- = dcStricts dc
+-- application. Matches 1-1 with `dataConRepArgTys`
+dataConRepStrictness = dcStricts
+
+dataConRepArgCbvInfos :: DataCon -> [ArgCbvInfo]
+-- ^ Describes each value argument of a Core DataCon worker
+-- application, /including/ any existential CoVar args
+-- See Note [ArgCbvInfo] and (EXCO1) in Note [Existential coercion variables]
+dataConRepArgCbvInfos = dcArgCbvInfos
+
+dataConRepIsLazy :: DataCon -> Bool
+dataConRepIsLazy = dcIsLazy
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
@@ -1523,10 +1623,11 @@ dataConWrapperType (MkData { dcUserTyVarBinders = user_tvbs,
res_ty
-- | Finds the instantiated types of the arguments required to construct a
--- 'DataCon' representation
+-- data constructor worker application
-- NB: these INCLUDE any dictionary args
--- but EXCLUDE the data-declaration context, which is discarded
--- It's all post-flattening etc; this is a representation type
+-- but EXCLUDE the "stupid theta" data-declaration context, which is discarded
+--
+-- Result list is 1-1 with dataConRepArgTys, and dataConRepStrictness
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
@@ -1621,9 +1722,10 @@ dataConOrigArgTys dc = dcOrigArgTys dc
dataConOtherTheta :: DataCon -> ThetaType
dataConOtherTheta dc = dcOtherTheta dc
--- | Returns the arg types of the worker, including *all* non-dependent
--- evidence, after any flattening has been done and without substituting for
--- any type variables
+-- | Returns the arg types of the worker, after any flattening has been done and
+-- without substituting for any type variables
+--
+-- Includes evidence, namely `dcEqSpec` and `dcOtherTheta`
dataConRepArgTys :: DataCon -> [Scaled Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
@@ -1642,8 +1744,10 @@ dataConRepArgTys (MkData { dcRep = rep
-- I think it's because of the call in mkDataCon, which in turn feeds
-- into dcRepArity, which in turn is used in mkDataConWorkId.
-- c.f. #23022
- | otherwise -> assert (null eq_spec) $
- map unrestricted theta ++ orig_arg_tys
+ | otherwise -> assert (null eq_spec) $
+ -- null eq_spec: all GADTs go via DCR
+ -- See `dataConUserTyVarsNeedWrapper`
+ map unrestricted theta ++ orig_arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
=====================================
compiler/GHC/Core/FamInstEnv.hs
=====================================
@@ -828,7 +828,7 @@ mkSingleCoAxiom role ax_name tvs eta_tvs cvs fam_tc lhs_tys rhs_ty
-- Note [Storing compatibility]
where
branch = mkCoAxBranch tvs eta_tvs cvs lhs_tys rhs_ty
- (map (const Nominal) tvs)
+ (mapConst Nominal tvs)
(getSrcSpan ax_name)
-- | Create a coercion constructor (axiom) suitable for the given
=====================================
compiler/GHC/Core/Opt/DmdAnal.hs
=====================================
@@ -1020,15 +1020,16 @@ dmdTransform :: AnalEnv -- ^ The analysis environment
-- this function plus demand on its free variables
-- See Note [DmdSig: demand signatures, and demand-sig arity] in "GHC.Types.Demand"
dmdTransform env var sd
- -- Data constructors
+ -- Data constructor workers
| Just con <- isDataConWorkId_maybe var
= -- pprTraceWith "dmdTransform:DataCon" (\ty -> ppr con $$ ppr sd $$ ppr ty) $
- dmdTransformDataConSig (dataConRepStrictness con) sd
- -- See Note [DmdAnal for DataCon wrappers]
+ dmdTransformDataConSig (dataConRepArgCbvInfos con) sd
+ -- See Note [DmdAnal for DataCon wrappers]
| Just rhs <- dataConWrapUnfolding_maybe var
, WithDmdType dmd_ty _rhs' <- dmdAnal env sd rhs
= dmd_ty
+
-- Dictionary component selectors
-- Used to be controlled by a flag.
-- See #18429 for some perf measurements.
@@ -1036,10 +1037,12 @@ dmdTransform env var sd
= -- pprTrace "dmdTransform:DictSel" (ppr var $$ ppr (idDmdSig var) $$ ppr sd) $
dmdTransformDictSelSig (idDmdSig var) sd
-- Imported functions
+
| isGlobalId var
, let res = dmdTransformSig (idDmdSig var) sd
= -- pprTrace "dmdTransform:import" (vcat [ppr var, ppr (idDmdSig var), ppr sd, ppr res])
res
+
-- Top-level or local let-bound thing for which we use LetDown ('useLetUp').
-- In that case, we have a strictness signature to unleash in our AnalEnv.
| Just (sig, top_lvl) <- lookupSigEnv env var
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -64,6 +64,7 @@ import GHC.Builtin.KnownKeys( runRWKey, seqHashKey )
import GHC.Builtin.WiredIn.Ids( seqId )
import qualified GHC.Data.List.Infinite as Inf
+import GHC.Data.List.Infinite ( Infinite(..) )
import GHC.Data.Maybe ( isNothing, orElse, mapMaybe )
import GHC.Data.FastString
import GHC.Unit.Module ( moduleName )
@@ -75,7 +76,6 @@ import GHC.Utils.Logger
import GHC.Utils.Misc
import Control.Monad
-import Data.List.NonEmpty (NonEmpty (..))
{-
The guts of the simplifier is in this module, but the driver loop for
@@ -1639,7 +1639,7 @@ rebuild_go env expr cont
ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
, sc_cont = cont, sc_hole_ty = fun_ty }
- -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ -> do { arg' <- simplArg env fun_ty arg_se arg arg_mco
; rebuild_go env (App expr arg') cont }
completeBindX :: SimplEnv
@@ -1841,27 +1841,21 @@ pushCast env co cont
go_mco (MCo co) opt cont = go co opt cont
simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
- -> Maybe ArgInfo -- ^ Just <=> This arg `ai` occurs in an app
- -- `f a1 ... an` where we have ArgInfo on
- -- how `f` uses `ai`, affecting the Stop
- -- continuation passed to 'simplExprC'
-> OutType -- ^ Type of the function applied to this arg
-> StaticEnv -> CoreExpr -- ^ Expression with its static envt
-> MOutCoercion -- Wrap this around the result
-> SimplM OutExpr
-simplArg _ _ _ (Simplified {}) arg mco
+-- Simplify an argument in a boring context
+-- c.f. the lazy-argument case of `rebuildCall`, which does the same,
+-- but with a more informative Stop continuation
+simplArg _ _ (Simplified {}) arg mco
= -- See Note [Avoid repeated simplification]
case mco of
MRefl -> return arg -- Vastly common case
MCo co -> return (mkCast arg co)
-simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
- = do { let arg_env' = arg_se `setInScopeFromE` env
- arg_ty = funArgTy fun_ty
- stop = case mb_arg_info of
- Nothing -> mkBoringStop arg_ty
- Just ai -> mkLazyArgStop arg_ty ai
- cont = addCastMCo mco stop
- ; simplExprC arg_env' arg cont }
+simplArg env fun_ty (UnSimplified arg_se) arg mco
+ = simplExprC (arg_se `setInScopeFromE` env) arg $
+ addCastMCo mco (mkBoringStop (funArgTy fun_ty))
{-
************************************************************************
@@ -1920,7 +1914,7 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
-- in this round of the Simplifier
-> simplNonRecE env from_what bndr (arg, arg_env) body cont
- _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ _ -> do { arg' <- simplArg env fun_ty arg_se arg arg_mco
; completeBindX env from_what bndr arg' body cont }
}
where
@@ -2255,31 +2249,49 @@ zap the SubstEnv. This is VITAL. Consider
We'll clone the inner \x, adding x->x' in the id_subst Then when we
inline y, we must *not* replace x by x' in the inlined copy!!
-Note [Fast path for lazy data constructors]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-For applications of a /lazy/ data constructor worker, the full glory of
-rebuildCall is a waste of effort;
+Note [Simplifying data constructor applications]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+For applications of a data constructor worker, much of the work done for
+an ordinary function application is a waste of effort:
+* Workers are global, so there is no need to look in the substitution
* They never inline, obviously
* They have no rewrite rules
-* Lazy constructors don't need the `StrictArg` treatment.
-So it's fine to zoom straight to `rebuild` which just rebuilds the
-call in a very straightforward way.
-
-For a data constructor worker that is strict (see Note [Strict fields in Core])
-we take the slow path, so that we'll transform
- K (case x of (a,b) -> a) --> case x of (a,b) -> K a
-via the StrictArg case of rebuildCall
-
-Some programs have a /lot/ of data constructors in the source program
-(compiler/perf/T9961 is an example), so this fast path can be very
-valuable.
+* We know their argument strictness without looking at their type
+So `simplInId` takes a short cut:
+
+(SDC1) If the constructor is completely lazy (`dataConRepIsLazy`: all
+ arguments are lifted and none has a bang), there is nothing for
+ `rebuildCall` to do, so we zoom straight to `rebuild`, which just
+ rebuilds the call in a very straightforward way.
+
+ This is not just a nicety: `rebuildCall` costs noticeably more per
+ argument than `rebuild` (ArgInfo, ArgSpecs, argInfoExpr, closures), and
+ some programs have a /lot/ of data constructors (compiler/perf/T9961 is
+ an example). Sending lazy constructors through `rebuildCall` made T9961
+ allocate about 3% more, even with the specialised DataConArgInfo of (SDC2).
+
+(SDC2) Otherwise we go straight to `rebuildCall`, skipping `simplOutId`,
+ with a `DataConArgInfo` built by `dataConArgInfo`. `DataConArgInfo` is a
+ specialised form of `ArgInfo`, with far fewer fields: a worker has no
+ rules, no unfolding discounts, never diverges, and its argument strictness
+ is given by `dataConRepArgCbvInfos`. `rebuildCall` has a separate, much
+ simpler, equation for it.
+
+ We want `rebuildCall`, rather than `rebuild`, for its StrictArg treatment
+ of arguments that are evaluated: strict fields (see Note [Strict fields
+ in Core]), and unlifted arguments (#28169). E.g. we want
+ K (case x of (a,b) -> a) --> case x of (a,b) -> K a
+ I# (case x of (a,b) -> a#) --> case x of (a,b) -> I# a#
+ See Note [ArgCbvInfo] in GHC.Core.DataCon.
-}
simplInId :: SimplEnv -> InId -> SimplCont -> SimplM (SimplFloats, OutExpr)
simplInId env var cont
- | Just dc <- isDataConWorkId_maybe var
- , isLazyDataConRep dc -- See Note [Fast path for lazy data constructors]
- = rebuild env (Var var) cont
+ | Just dc <- isDataConWorkId_maybe var -- See Note [Simplifying data constructor applications]
+ = if dataConRepIsLazy dc
+ then rebuild env (Var var) cont -- (SDC1)
+ else rebuildCall (zapSubstEnv env) (dataConArgInfo dc) cont -- (SDC2)
+
| otherwise
= assertPpr (not (isCoVar var)) (ppr var) $
case substId env var of
@@ -2439,54 +2451,123 @@ rebuildCall :: SimplEnvIS -> ArgInfo -> SimplCont
-- it is usually empty, and regardless should be ignored.
-- Only the in-scope set matters, plus the seMode flags
--- Check the invariant
-rebuildCall env arg_info _cont
- | assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env $$ ppr arg_info) False
- = pprPanic "rebuildCall" empty
-
----------- Bottoming applications --------------
-rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_dmds = [] }) cont
- -- When we run out of demands, it means that the call is definitely bottom.
- -- See (TC2) in Note [Trimming the continuation for bottoming functions]
- = rebuild env (argInfoExpr fun rev_args) (mkBottomCont cont)
-
----------- Simplify type applications --------------
-rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })
- = rebuildCall env (addTyArgTo info arg_ty hole_ty) cont
-
----------- Simplify value arguments --------------------
-rebuildCall env fun_info
- (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_hole_ty = fun_ty, sc_cont = cont })
- | UnSimplified arg_env <- arg_se
- , isStrictArgInfo fun_info -- Strict arguments
- , seCaseCase env -- But only when case-of-case is on.
- -- See Note [Case-of-case and full laziness]
- = simplExprF (arg_env `setInScopeFromE` env) arg $
- addCastMCo arg_mco $
- StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
- , sc_dup = NoDup
- , sc_cont = cont }
- -- Note [Shadowing in the Simplifier]
-
- | otherwise -- Lazy, or already simplified arguments
- -- DO NOT float anything outside, hence simplExprC
- -- There is no benefit (unlike in a let-binding), and we'd
- -- have to be very careful about bogus strictness through
- -- floating a demanded let.
- = do { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
- ; rebuildCall env (addValArgTo fun_info arg' fun_ty) cont }
-
----------- No further useful info, revert to generic rebuild ------------
-rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_arg_specs, ai_rules = rules }) cont
- | null rules
- = rebuild env (argInfoExpr fun rev_arg_specs) cont
- | otherwise -- Try rules again: Plan (AFTER) in Note [When to apply rewrite rules]
- = do { let arg_specs = reverse rev_arg_specs
- ; mb_match <- tryRules env rules fun (map argSpecArg arg_specs)
- ; case mb_match of
- Just rule_match -> fireRuleAFTER env rule_match arg_specs cont
- Nothing -> rebuild env (argInfoExpr fun rev_arg_specs) cont }
+-- NB: rebuildCall takes the ArgInfo apart once, and then loops with `go`,
+-- passing only the pieces that change from one argument to the next.
+-- We only re-package an ArgInfo when we need one, for a StrictArg
+-- continuation. This saves allocating a fresh ArgInfo record for every
+-- argument, which is measurable (e.g. compiler/perf/T9961).
+-- Similarly `go` loops over the [Demand] in the RemainingArgDmds; the
+-- Divergence (which says what happens when they run out) does not change.
+---------- Data constructor workers ------------
+-- A specialised, much simpler, version of the general case below
+-- See (SDC2) in Note [Simplifying data constructor applications]
+rebuildCall env (DataConArgInfo { ai_dc_app = app0, ai_dc_args = dc_args0 })
+ cont0
+ = assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env) $
+ go app0 dc_args0 cont0
+ where
+ -- `app` is the data constructor applied to the arguments so far
+ go :: OutExpr -> [ArgCbvInfo] -> SimplCont -> SimplM (SimplFloats, OutExpr)
+ go app dc_args (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
+ = go (App app (Type arg_ty)) dc_args cont
+
+ go app (dc_arg : dc_args)
+ (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
+ , sc_hole_ty = fun_ty, sc_cont = cont })
+ | ArgCbv <- dc_arg -- Strict (or unlifted) field; ArgRepPoly is lazy
+ -- See Note [ArgCbvInfo] in GHC.Core.DataCon
+ , UnSimplified arg_env <- arg_se
+ , seCaseCase env -- Only when case-of-case is on.
+ -- See Note [Case-of-case and full laziness]
+ = simplExprF (arg_env `setInScopeFromE` env) arg $
+ addCastMCo arg_mco $
+ StrictArg { sc_fun = DataConArgInfo { ai_dc_app = app
+ , ai_dc_args = dc_arg : dc_args }
+ , sc_fun_ty = fun_ty
+ , sc_dup = NoDup
+ , sc_cont = cont }
+
+ | otherwise
+ = do { arg' <- simplArg env fun_ty arg_se arg arg_mco
+ ; go (App app arg') dc_args cont }
+
+ go app _ cont -- No rules for data constructors
+ = rebuild env app cont
+
+---------- The general case ------------
+rebuildCall env info@(ArgInfo { ai_fun_id = fun, ai_args = rev_args0, ai_rules = rules
+ , ai_encl = encl, ai_discs = discs0
+ , ai_dmds = dmd_ty0@(DmdType { dt_env = dmd_env0
+ , dt_args = dmds0 }) })
+ cont0
+ = assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env $$ ppr info) $
+ go rev_args0 dmds0 discs0 cont0
+ where
+ go :: [ArgSpec] -> [Demand] -> Infinite Int -> SimplCont
+ -> SimplM (SimplFloats, OutExpr)
+
+ ---------- Bottoming applications --------------
+ go rev_args [] _ cont
+ | isDeadEndDiv (de_div dmd_env0) -- c.f. splitArgDmd
+ -- When we run out of demands, it means that the call is definitely bottom.
+ -- See (TC2) in Note [Trimming the continuation for bottoming functions]
+ = rebuild env (argInfoExpr fun rev_args) (mkBottomCont cont)
+
+ ---------- Simplify type applications --------------
+ go rev_args dmds discs (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })
+ = go (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } : rev_args) dmds discs cont
+
+ ---------- Simplify value arguments --------------------
+ go rev_args dmds discs@(Inf _ discs')
+ (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
+ , sc_hole_ty = fun_ty, sc_cont = cont })
+ | UnSimplified arg_env <- arg_se
+ , seCaseCase env -- Only when case-of-case is on.
+ -- See Note [Case-of-case and full laziness]
+ , isStrUsedDmd dmd -- Strict arguments; c.f. isStrictArgInfo
+ -- NB: mkArgInfo makes unlifted args strict
+ = simplExprF (arg_env `setInScopeFromE` env) arg $
+ addCastMCo arg_mco $
+ StrictArg { sc_fun = info { ai_args = rev_args, ai_discs = discs
+ , ai_dmds = dmd_ty0 { dt_args = dmds } }
+ , sc_fun_ty = fun_ty
+ , sc_dup = NoDup
+ , sc_cont = cont }
+ -- Note [Shadowing in the Simplifier]
+
+ | otherwise -- Lazy, or already simplified arguments
+ -- DO NOT float anything outside, hence simplExprC
+ -- There is no benefit (unlike in a let-binding), and we'd
+ -- have to be very careful about bogus strictness through
+ -- floating a demanded let.
+ = do { arg' <- case arg_se of
+ Simplified {} -- See Note [Avoid repeated simplification]
+ -> return (mkCastMCo arg arg_mco)
+ UnSimplified arg_env
+ -> simplExprC (arg_env `setInScopeFromE` env) arg $
+ addCastMCo arg_mco $
+ Stop (funArgTy fun_ty) (lazyArgCallCtxt encl discs)
+ (subDemandIfEvaluated dmd) -- c.f. mkLazyArgStop
+ ; go (ValArg { as_arg = arg', as_hole_ty = fun_ty, as_dmd = dmd } : rev_args)
+ dmds' discs' cont }
+ where
+ !(dmd, dmds') = case dmds of
+ dmd : dmds' -> (dmd, dmds')
+ [] -> (topDmd, [])
+ -- Not bottoming (see first equation of `go`),
+ -- so the default demand is topDmd
+ -- Bang: avoid allocating thunks for dmd and dmds'
+
+ ---------- No further useful info, revert to generic rebuild ------------
+ go rev_arg_specs _ _ cont
+ | null rules
+ = rebuild env (argInfoExpr fun rev_arg_specs) cont
+ | otherwise -- Try rules again: Plan (AFTER) in Note [When to apply rewrite rules]
+ = do { let arg_specs = reverse rev_arg_specs
+ ; mb_match <- tryRules env rules fun (map argSpecArg arg_specs)
+ ; case mb_match of
+ Just rule_match -> fireRuleAFTER env rule_match arg_specs cont
+ Nothing -> rebuild env (argInfoExpr fun rev_arg_specs) cont }
-----------------------------------
tryInlining :: SimplEnv -> Logger -> OutId -> SimplCont -> SimplM (Maybe OutExpr)
@@ -3649,7 +3730,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
| otherwise
= go vs the_strs
where
- the_strs = dataConRepStrictness con
+ the_strs = map argCbvInfoStrictnessMark (dataConRepArgCbvInfos con)
go [] [] = []
go (v:vs') strs | isTyVar v = v : go vs' strs
@@ -3659,7 +3740,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
ppr vs $$
ppr_with_length (map strdisp the_strs) $$
ppr_with_length (dataConRepArgTys con) $$
- ppr_with_length (dataConRepStrictness con))
+ ppr_with_length (dataConRepArgCbvInfos con))
where
ppr_with_length list
= ppr list <+> parens (text "length =" <+> ppr (length list))
@@ -4053,20 +4134,22 @@ This trimming can also be done with other continuations:
We implement the trimming in three parts:
-(TC1) In `mkArgInfo`, for a bottoming function, we make a list of `RemainingArgDmds`
- with a finite list of elements (in the example above, just one).
+(TC1) In `mkArgInfo`, for a bottoming function, we use its `DmdType` as the
+ `RemainingArgDmds`. It has a finite list of argument demands (in the example
+ above, just one), and a divergence that `isDeadEndDiv`.
- For comparison, note that, for non-bottoming functions, the `RemainingArgDmds`
- always finishes with an infinite list of `topDmd`.
+ For comparison, note that, for non-bottoming functions, the divergence is
+ not `isDeadEndDiv`, so `splitArgDmd` yields `topDmd` once the argument
+ demands run out.
-(TC2) In `rebuildCall`, when we run out of `RemainingArgDmds` we discard the
+(TC2) In `rebuildCall`, when `splitArgDmd` returns Nothing we discard the
remaining continuation.
After discarding the continuation, the types might not match, in which case
we leave behind a (case <hole> of {}) wrapper. See the call to `mkBottomCont`.
(TC3) In `mkDupableContWithDmds`, we similarly discard the continuation when
- we run out of `RemainingArgDmds`.
+ `splitArgDmd` returns Nothing.
-}
--------------------
@@ -4098,7 +4181,7 @@ mkDupableCont :: SimplEnvIS
-- extra let/join-floats and in-scope variables
, SimplCont) -- dup_cont: duplicable continuation
mkDupableCont env cont
- = mkDupableContWithDmds (zapSubstEnv env) (repeat topDmd) cont
+ = mkDupableContWithDmds (zapSubstEnv env) nopDmdType cont
mkDupableContWithDmds
:: SimplEnvIS -> RemainingArgDmds
@@ -4116,7 +4199,7 @@ mkDupableContWithDmds env remaining_dmds cont
-- => simply trim the continuation
-- c.f. the null-demands case in `rebuildCall`
-- See (TC3) in Note [Trimming the continuation for bottoming functions]
- | null remaining_dmds
+ | Nothing <- splitArgDmd remaining_dmds
= return (emptyFloats env, mkBottomCont cont)
mkDupableContWithDmds _ _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
@@ -4158,18 +4241,24 @@ mkDupableContWithDmds env _
(StrictArg { sc_fun = fun, sc_cont = cont
, sc_fun_ty = fun_ty })
-- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
- | isNothing (isDataConId_maybe (ai_fun fun))
+ | ArgInfo { ai_fun_id = fun_id, ai_dmds = fun_dmds, ai_args = args } <- fun
+ -- Not a DataConArgInfo: these always use Plan B, which is just as well,
+ -- because a DataConArgInfo does not record its arguments separately
+ , isNothing (isDataConId_maybe fun_id)
-- isDataConId: see point (DJ4) of Note [Duplicating join points]
+ -- NB: fun_id is never a data constructor /worker/ (they use
+ -- DataConArgInfo), but it can be a data constructor /wrapper/
, thumbsUpPlanA cont
= -- Use Plan A of Note [Duplicating StrictArg]
--- pprTrace "Using plan A" (ppr (ai_fun fun) $$ text "args" <+> ppr (ai_args fun) $$ text "cont" <+> ppr cont) $
- do { let _ :| dmds = expectNonEmpty (ai_dmds fun) -- See Invariant of StrictArg;
- -- ai_dmds is never empty
+-- pprTrace "Using plan A" (ppr (ai_fun_id fun) $$ text "args" <+> ppr (ai_args fun) $$ text "cont" <+> ppr cont) $
+ do { let dmds = case splitArgDmd fun_dmds of
+ Just (_, dmds) -> dmds
+ Nothing -> pprPanic "mkDupableContWithDmds" (ppr fun)
+ -- See Invariant of StrictArg
; (floats1, cont') <- mkDupableContWithDmds env dmds cont
-- Use the demands from the function to add the right
-- demand info on any bindings we make for further args
- ; (floats_s, args') <- mapAndUnzipM (makeTrivialArg env)
- (ai_args fun)
+ ; (floats_s, args') <- mapAndUnzipM (makeTrivialArg env) args
; return ( foldl' addLetFloats floats1 floats_s
, StrictArg { sc_fun = fun { ai_args = args' }
, sc_cont = cont'
@@ -4210,13 +4299,14 @@ mkDupableContWithDmds env dmds
-- let a = ...arg...
-- in [...hole...] a
-- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
- do { let dmd:|cont_dmds =
- -- We took care to handle an empty demand list at the start,
- -- ensuring this call to 'expectNonEmpty' does not panic (#27261).
- expectNonEmpty dmds
+ do { let (dmd, cont_dmds) = case splitArgDmd dmds of
+ Just prs -> prs
+ Nothing -> pprPanic "mkDupableContWithDmds:ApplyToVal" (ppr cont)
+ -- We took care to handle bottoming demands at the start,
+ -- ensuring this does not panic (#27261).
; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
; let env' = env `setInScopeFromF` floats1
- ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
+ ; arg' <- simplArg env' hole_ty se arg arg_mco
; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
; let all_floats = floats1 `addLetFloats` let_floats2
; return ( all_floats
@@ -4281,10 +4371,10 @@ mkDupableStrictBind env arg_bndr join_rhs res_ty
, sc_cont = mkBoringStop res_ty } )
| otherwise
= do { join_bndr <- newJoinId [arg_bndr] res_ty
- ; let arg_info = ArgInfo { ai_fun = join_bndr
- , ai_rules = [], ai_args = []
- , ai_encl = False, ai_dmds = repeat topDmd
- , ai_discs = Inf.repeat 0 }
+ ; let arg_info = ArgInfo { ai_fun_id = join_bndr
+ , ai_rules = [], ai_args = []
+ , ai_encl = False, ai_dmds = nopDmdType
+ , ai_discs = Inf.repeat 0 }
; return ( addJoinFloats (emptyFloats env) $
unitJoinFloat $
NonRec join_bndr $
@@ -4306,10 +4396,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
| otherwise
= do { let rhs_ty' = exprType alt_rhs_in
- bangs
- | DataAlt c <- con
- = dataConRepStrictness c
- | otherwise = []
+ bangs = case con of
+ DataAlt dc -> map argCbvInfoStrictnessMark (dataConRepArgCbvInfos dc)
+ _ -> []
abstracted_binders = abstract_binders alt_bndrs bangs
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -31,11 +31,11 @@ module GHC.Core.Opt.Simplify.Utils (
interestingCallContext,
-- ArgInfo
- ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo,
+ ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo, dataConArgInfo,
addValArgTo, addTyArgTo,
argInfoExpr, argSpecArg,
pushOutArgs, pushArgSpecs,
- isStrictArgInfo, lazyArgContext,
+ isStrictArgInfo, lazyArgContext, lazyArgCallCtxt,
abstractFloats,
@@ -44,7 +44,6 @@ module GHC.Core.Opt.Simplify.Utils (
) where
import GHC.Prelude hiding (head, init, last, tail)
-import qualified GHC.Prelude as Partial (head)
import GHC.Core
import GHC.Types.Literal ( isLitRubbish )
@@ -64,7 +63,8 @@ import GHC.Core.Unfold.Make
import GHC.Core.Opt.Simplify.Monad
import GHC.Core.Type hiding( substTy )
import GHC.Core.Coercion hiding( substCo )
-import GHC.Core.DataCon ( dataConWorkId, isNullaryRepDataCon )
+import GHC.Core.DataCon ( DataCon, ArgCbvInfo(..), dataConWorkId, isNullaryRepDataCon
+ , dataConRepArgCbvInfos )
import GHC.Core.Multiplicity
import GHC.Core.Opt.ConstantFold
@@ -150,7 +150,7 @@ Key points:
data SimplCont
= Stop -- ^ Stop[e] = e
OutType -- ^ Type of the <hole>
- CallCtxt -- ^ Tells if there is something interesting about
+ !CallCtxt -- ^ Tells if there is something interesting about
-- the syntactic context, and hence the inliner
-- should be a bit keener (see interestingCallContext)
-- Specifically:
@@ -158,7 +158,7 @@ data SimplCont
-- Inlining the call might allow the rule to fire
-- Never ValAppCxt (use ApplyToVal instead)
-- or CaseCtxt (use Select instead)
- SubDemand -- ^ The evaluation context of e. Tells how e is evaluated.
+ !SubDemand -- ^ The evaluation context of e. Tells how e is evaluated.
-- This fuels eta-expansion or eta-reduction without looking
-- at lambda bodies, for example.
--
@@ -212,7 +212,7 @@ data SimplCont
, sc_fun :: ArgInfo -- Specifies f, e1..en, whether f has rules, etc
-- plus demands and discount flags for *this* arg
-- and further args
- -- Invariant: ai_dmds and ai_discs are never empty
+ -- Invariant: (splitArgDmd ai_dmds) is never Nothing
, sc_fun_ty :: OutType -- Type of the function (f e1 .. en),
-- presumably (arg_ty -> res_ty)
-- where res_ty is expected by sc_cont
@@ -317,7 +317,10 @@ instance Outputable SimplCont where
ppr (StrictBind { sc_bndr = b, sc_cont = cont })
= (text "StrictBind" <+> ppr b) $$ ppr cont
ppr (StrictArg { sc_fun = ai, sc_cont = cont })
- = (text "StrictArg" <+> ppr (ai_fun ai)) $$ ppr cont
+ = (text "StrictArg" <+> pp_fun ai) $$ ppr cont
+ where
+ pp_fun (ArgInfo { ai_fun_id = fun }) = ppr fun
+ pp_fun (DataConArgInfo { ai_dc_app = app }) = ppr app
ppr (Select { sc_env = env, sc_bndr = bndr, sc_alts = alts, sc_cont = cont })
= (text "Select" <> braces (ppr env) <+> ppr bndr) $$
whenPprDebug (nest 2 $ ppr alts) $$ ppr cont
@@ -352,9 +355,9 @@ doesn't matter because we'll never compute them all.
data ArgInfo
= ArgInfo {
- ai_fun :: OutId, -- ^ The function
- ai_args :: [ArgSpec], -- ^ ...applied to these args (which are in *reverse* order)
- -- NB: all these argumennts are already simplified
+ ai_fun_id :: OutId, -- ^ The function
+ ai_args :: [ArgSpec], -- ^ ...applied to these args (which are in *reverse* order)
+ -- NB: all these argumennts are already simplified
ai_rules :: [CoreRule], -- ^ Rules for this function
ai_encl :: Bool,
@@ -365,6 +368,7 @@ data ArgInfo
ai_dmds :: RemainingArgDmds,
-- ^ Demands on remaining value arguments (beyond 'ai_args')
+ -- Take it apart with 'splitArgDmd'
ai_discs :: Infinite Int
-- ^ Discounts for remaining value arguments (beyond 'ai_args')
@@ -372,12 +376,32 @@ data ArgInfo
-- A non-zero value means: be keener to inline
}
+ -- | A specialised ArgInfo for a data constructor /worker/;
+ -- see Note [Simplifying data constructor applications]
+ -- in GHC.Core.Opt.Simplify.Iteration.
+ -- A worker has no rules, no unfolding discounts, never diverges, and
+ -- its argument strictness is fixed; so we need many fewer fields.
+ | DataConArgInfo {
+ ai_dc_app :: OutExpr, -- ^ The data constructor worker, applied to
+ -- the (simplified) arguments so far
+ -- NB: we never need to duplicate a StrictArg
+ -- whose sc_fun is a DataConArgInfo, so we do
+ -- not need the args separately; see point
+ -- (DJ4) of Note [Duplicating join points]
+ ai_dc_args :: [ArgCbvInfo] -- ^ Info about the remaining value arguments
+ -- See Note [ArgCbvInfo] in GHC.Core.DataCon
+ }
+
-- | 'RemainingArgDmds' gives the demands on any remaining value arguments.
--
--- It is usually infinite (with 'topDmd's in the tail), but if it is finite it
--- guarantees that the function diverges after being applied to that number
--- of arguments.
-type RemainingArgDmds = [Demand]
+-- Take it apart with 'splitArgDmd'. When its 'dt_args' run out, the
+-- Divergence in its 'dt_env' says what happens next:
+-- * if 'isDeadEndDiv', the function diverges after being applied to that
+-- number of arguments; 'splitArgDmd' returns Nothing.
+-- * otherwise all further arguments have demand 'topDmd'
+-- See Note [Trimming the continuation for bottoming functions]
+-- in GHC.Core.Opt.Simplify.Iteration
+type RemainingArgDmds = DmdType
data ArgSpec
-- | A value argument
@@ -389,20 +413,31 @@ data ArgSpec
, as_hole_ty :: OutType } -- ^ Type of the function (presumably @t1 -> t2@ for 'ValArg' or @forall a. blah@ for 'TyArg')
instance Outputable ArgInfo where
- ppr (ArgInfo { ai_fun = fun, ai_args = args, ai_dmds = dmds, ai_rules = rules })
+ ppr (ArgInfo { ai_fun_id = fun, ai_args = args, ai_dmds = dmds, ai_rules = rules })
= text "ArgInfo" <+> braces
(sep [ text "fun =" <+> ppr fun
- , text "dmds(first 10) =" <+> ppr (take 10 dmds)
+ , text "dmds =" <+> ppr dmds
, text "args =" <+> ppr args
, text "rewrite =" <+> ppr rules ])
+ ppr (DataConArgInfo { ai_dc_app = app, ai_dc_args = dc_args })
+ = text "DataConArgInfo" <+> braces
+ (sep [ text "app =" <+> ppr app
+ , text "dc_args =" <+> ppr dc_args ])
instance Outputable ArgSpec where
ppr (ValArg { as_arg = arg }) = text "ValArg" <+> ppr arg
ppr (TyArg { as_arg_ty = ty }) = text "TyArg" <+> ppr ty
addValArgTo :: ArgInfo -> OutExpr -> OutType -> ArgInfo
+addValArgTo ai@(DataConArgInfo { ai_dc_app = app, ai_dc_args = dc_args }) arg _hole_ty
+ | _ : dc_args' <- dc_args
+ = DataConArgInfo { ai_dc_app = App app arg, ai_dc_args = dc_args' }
+ | otherwise
+ = pprPanic "addValArgTo:DataConArgInfo" (ppr ai $$ ppr arg)
+
addValArgTo ai arg hole_ty
- | ArgInfo { ai_dmds = dmd:dmds, ai_discs = Inf _ discs } <- ai
+ | ArgInfo { ai_dmds = dmds0, ai_discs = Inf _ discs } <- ai
+ , Just (dmd, dmds) <- splitArgDmd dmds0
-- Pop the top demand and and discounts off
, let arg_spec = ValArg { as_arg = arg, as_hole_ty = hole_ty, as_dmd = dmd }
= ai { ai_args = arg_spec : ai_args ai
@@ -413,15 +448,40 @@ addValArgTo ai arg hole_ty
-- There should always be enough demands and discounts
addTyArgTo :: ArgInfo -> OutType -> OutType -> ArgInfo
-addTyArgTo ai arg_ty hole_ty = ai { ai_args = arg_spec : ai_args ai }
- where
- arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }
+addTyArgTo ai@(DataConArgInfo { ai_dc_app = app }) arg_ty _hole_ty
+ = ai { ai_dc_app = App app (Type arg_ty) }
+addTyArgTo ai arg_ty hole_ty
+ = ai { ai_args = TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } : ai_args ai }
+
+argCbvInfoDmd :: ArgCbvInfo -> Demand
+-- The demand that a data constructor worker places on an argument
+-- Treat ArgRepPoly as lazy; see Note [ArgCbvInfo] in GHC.Core.DataCon
+-- c.f. GHC.Types.Id.Make.mkDataConWorkId, which makes the same choice
+argCbvInfoDmd ArgCbv = evalDmd
+argCbvInfoDmd ArgCbn = topDmd
+argCbvInfoDmd ArgRepPoly = topDmd
isStrictArgInfo :: ArgInfo -> Bool
-- True if the function is strict in the next argument
+isStrictArgInfo (DataConArgInfo { ai_dc_args = dc_args })
+ = case dc_args of { ArgCbv : _ -> True; _ -> False }
isStrictArgInfo (ArgInfo { ai_dmds = dmds })
- | dmd:_ <- dmds = isStrUsedDmd dmd
- | otherwise = False
+ | Just (dmd,_) <- splitArgDmd dmds = isStrUsedDmd dmd
+ | otherwise = False
+
+argInfoNextDmd :: ArgInfo -> Demand
+-- The demand on the next argument; the call should not be bottoming
+argInfoNextDmd ai@(DataConArgInfo { ai_dc_args = dc_args })
+ | dc_arg : _ <- dc_args = argCbvInfoDmd dc_arg
+ | otherwise = pprPanic "argInfoNextDmd" (ppr ai)
+argInfoNextDmd ai@(ArgInfo { ai_dmds = dmds })
+ | Just (dmd,_) <- splitArgDmd dmds = dmd
+ | otherwise = pprPanic "argInfoNextDmd" (ppr ai)
+
+argInfoHasRules :: ArgInfo -> Bool
+-- True <=> this function, or an enclosing one, has rules; see ai_encl
+argInfoHasRules (DataConArgInfo {}) = False
+argInfoHasRules (ArgInfo { ai_encl = encl }) = encl
pushOutArgs :: Type -> [OutExpr] -> SimplCont -> SimplCont
pushOutArgs _fun_ty [] cont
@@ -478,7 +538,7 @@ mkRhsStop ty is_rec bndr_dmd = Stop ty (RhsCtxt is_rec) (subDemandIfEvaluated bn
mkLazyArgStop :: OutType -> ArgInfo -> SimplCont
mkLazyArgStop ty fun_info = Stop ty (lazyArgContext fun_info) arg_sd
where
- arg_sd = subDemandIfEvaluated (Partial.head (ai_dmds fun_info))
+ arg_sd = subDemandIfEvaluated (argInfoNextDmd fun_info)
-------------------
contIsRhs :: SimplCont -> Maybe RecFlag
@@ -669,7 +729,7 @@ contEvalContext bndrs cont = go cont
, text "cont:" <+> ppr cont ])
topSubDmd
- go (StrictArg{sc_fun=fun_info}) = subDemandIfEvaluated (Partial.head (ai_dmds fun_info))
+ go (StrictArg{sc_fun=fun_info}) = subDemandIfEvaluated (argInfoNextDmd fun_info)
go (StrictBind{sc_bndr=bndr}) = subDemandIfEvaluated (idDemandInfo bndr)
go (Select{}) = topSubDmd
-- Perhaps reconstruct the demand on the scrutinee by looking at field
@@ -705,21 +765,29 @@ mkBottomCont cont = go cont
stop_cont = contStop k
-------------------
+dataConArgInfo :: DataCon -> ArgInfo
+-- Like mkArgInfo, but specialised for a data constructor worker
+-- See Note [Simplifying data constructor applications]
+-- in GHC.Core.Opt.Simplify.Iteration
+dataConArgInfo dc
+ = DataConArgInfo { ai_dc_app = Var (dataConWorkId dc)
+ , ai_dc_args = dataConRepArgCbvInfos dc }
+
mkArgInfo :: SimplEnv -> Id -> [CoreRule] -> SimplCont -> ArgInfo
mkArgInfo env fun rules_for_fun cont
| n_val_args < idArity fun -- Note [Unsaturated functions]
- = ArgInfo { ai_fun = fun, ai_args = []
+ = ArgInfo { ai_fun_id = fun, ai_args = []
, ai_rules = rules_for_fun
, ai_encl = False
- , ai_dmds = vanilla_dmds
+ , ai_dmds = nopDmdType
, ai_discs = vanilla_discounts }
| otherwise
- = ArgInfo { ai_fun = fun
- , ai_args = []
- , ai_rules = rules_for_fun
- , ai_encl = fun_has_rules || contHasRules cont
- , ai_dmds = add_type_strictness (idType fun) arg_dmds
- , ai_discs = arg_discounts }
+ = ArgInfo { ai_fun_id = fun
+ , ai_args = []
+ , ai_rules = rules_for_fun
+ , ai_encl = fun_has_rules || contHasRules cont
+ , ai_dmds = add_type_strictness (idType fun) arg_dmd_ty
+ , ai_discs = arg_discounts }
where
n_val_args = countValArgs cont
@@ -732,30 +800,19 @@ mkArgInfo env fun rules_for_fun cont
-> discounts Inf.++ vanilla_discounts
_ -> vanilla_discounts
- vanilla_dmds :: RemainingArgDmds
- vanilla_dmds = repeat topDmd
-
- arg_dmds :: RemainingArgDmds
- arg_dmds
+ arg_dmd_ty :: RemainingArgDmds
+ arg_dmd_ty
| not (seInline env)
- = vanilla_dmds -- See Note [Do not expose strictness if sm_inline=False]
- | otherwise
- = -- add_type_str fun_ty $
- case splitDmdSig (idDmdSig fun) of
- (demands, result_info)
- | not (demands `lengthExceeds` n_val_args)
- -> remaining_dmds -- Enough args, use the strictness given.
- | otherwise
- -> warnPprTrace True "More demands than arity" (ppr fun <+> ppr (idArity fun)
+ = nopDmdType -- See Note [Do not expose strictness if sm_inline=False]
+ | DmdSig dmd_ty@(DmdType { dt_args = demands }) <- idDmdSig fun
+ = if not (demands `lengthExceeds` n_val_args)
+ then dmd_ty -- Enough args, use the strictness given.
+ -- If the divergence isDeadEndDiv, the result is bottom
+ -- after (length demands) args; see (TC1) in
+ -- Note [Trimming the continuation for bottoming functions]
+ else warnPprTrace True "More demands than arity" (ppr fun <+> ppr (idArity fun)
<+> ppr n_val_args <+> ppr demands) $
- vanilla_dmds -- Not enough args, or no strictness
-
- where
- remaining_dmds :: RemainingArgDmds
- -- isDeadEndDiv: if remaining_dmds is finite, result is bottom
- -- See (TC1) in Note [Trimming the continuation for bottoming functions]
- remaining_dmds | isDeadEndDiv result_info = demands
- | otherwise = demands ++ vanilla_dmds
+ nopDmdType -- Not enough args, or no strictness
add_type_strictness :: Type -> RemainingArgDmds -> RemainingArgDmds
-- If the function arg /types/ are strict, record that in the RemainingArgDmds
@@ -764,27 +821,35 @@ mkArgInfo env fun rules_for_fun cont
-- add_type_strictness is done repeatedly (for each call);
-- might be better once-for-all in the function
-- But beware primops/datacons with no strictness
-
- add_type_strictness fun_ty dmds
- | null dmds = []
-
- | Just (_, fun_ty') <- splitForAllTyCoVar_maybe fun_ty
- = add_type_strictness fun_ty' dmds -- Look through foralls
-
- | Just (_, _, arg_ty, fun_ty') <- splitFunTy_maybe fun_ty -- Add strict-type info
- , dmd : rest_dmds <- dmds
- , let dmd'
- | definitelyUnliftedType arg_ty
- = strictifyDmd dmd
- | otherwise
- -- Something that's not definitely unlifted.
- -- If the type is representation-polymorphic, we can't know whether
- -- it's strict.
- = dmd
- = dmd' : add_type_strictness fun_ty' rest_dmds
-
- | otherwise
- = dmds
+ add_type_strictness fun_ty dmd_ty@(DmdType { dt_env = dmd_env, dt_args = dmds0 })
+ = dmd_ty { dt_args = go fun_ty dmds0 }
+ where
+ -- NB: when the dt_args run out we must carry on (with the default
+ -- demand, topDmd) as long as there are more argument types, unless
+ -- the call is bottoming. c.f. splitArgDmd
+ is_bottoming = isDeadEndDiv (de_div dmd_env)
+ next_dmd (dmd : dmds) = Just (dmd, dmds)
+ next_dmd [] | is_bottoming = Nothing
+ | otherwise = Just (topDmd, [])
+
+ go fun_ty dmds
+ | Just (_, fun_ty') <- splitForAllTyCoVar_maybe fun_ty
+ = go fun_ty' dmds -- Look through foralls
+
+ | Just (_, _, arg_ty, fun_ty') <- splitFunTy_maybe fun_ty -- Add strict-type info
+ , Just (dmd, rest_dmds) <- next_dmd dmds
+ , let dmd'
+ | definitelyUnliftedType arg_ty
+ = strictifyDmd dmd
+ | otherwise
+ -- Something that's not definitely unlifted.
+ -- If the type is representation-polymorphic, we can't know whether
+ -- it's strict.
+ = dmd
+ = dmd' : go fun_ty' rest_dmds
+
+ | otherwise
+ = dmds
{- Note [Unsaturated functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -964,12 +1029,19 @@ the incentive to disappear when we inline `f`!
lazyArgContext :: ArgInfo -> CallCtxt
-- Use this for lazy arguments
+lazyArgContext (DataConArgInfo {}) = BoringCtxt
lazyArgContext (ArgInfo { ai_encl = encl_rules, ai_discs = discs })
+ = lazyArgCallCtxt encl_rules discs
+
+lazyArgCallCtxt :: Bool -> Infinite Int -> CallCtxt
+-- Same as lazyArgContext, but taking the relevant pieces of the ArgInfo
+lazyArgCallCtxt encl_rules discs
| encl_rules = RuleArgCtxt
| Inf disc _ <- discs, disc > 0 = DiscArgCtxt -- Be keener here
| otherwise = BoringCtxt -- Nothing interesting
strictArgContext :: ArgInfo -> CallCtxt
+strictArgContext (DataConArgInfo {}) = RhsCtxt NonRecursive -- See comments below
strictArgContext (ArgInfo { ai_encl = encl_rules, ai_discs = discs })
-- Use this for strict arguments
| encl_rules = RuleArgCtxt
@@ -1050,7 +1122,7 @@ contHasRules cont
go (ApplyToVal { sc_cont = cont }) = go cont
go (ApplyToTy { sc_cont = cont }) = go cont
go (CastIt { sc_cont = cont }) = go cont
- go (StrictArg { sc_fun = fun }) = ai_encl fun
+ go (StrictArg { sc_fun = fun }) = argInfoHasRules fun
go (Stop _ RuleArgCtxt _) = True
go (TickIt _ c) = go c
go (Select {}) = False
=====================================
compiler/GHC/Core/Opt/SpecConstr.hs
=====================================
@@ -2605,7 +2605,7 @@ callToPat env bndr_occs call@(Call fn args con_env)
= do { let in_scope = substInScopeSet (sc_subst env)
; arg_triples <- argsToPats env in_scope con_env (idType fn) args bndr_occs
- (repeat NotMarkedStrict)
+ (repeat ArgCbn)
-- This trims the args to be no longer than
-- the lambdas in the function definition (bndr_occs)
@@ -2666,7 +2666,7 @@ argsToPats :: ScEnv
-> Type -- ^ type of the head (function or data constructor)
-> [CoreArg] -- ^ arguments of the head
-> [ArgOcc] -- ^ occurrence info, one per argument; the result is trimmed to this length
- -> [StrictnessMark] -- ^ strictness info, one per value argument
+ -> [ArgCbvInfo] -- ^ strictness info, one per value argument
-> UniqSM [(Bool, CoreArg, [Id])]
argsToPats env in_scope val_env = go
where
@@ -2674,7 +2674,7 @@ argsToPats env in_scope val_env = go
go _ _ [] _ = return []
go fun_ty (arg : args) (occ : occs) strs
= do { (pat, strs') <- case arg of
- Type {} -> do { pat <- argToPat env in_scope val_env arg_ty arg occ NotMarkedStrict
+ Type {} -> do { pat <- argToPat env in_scope val_env arg_ty arg occ ArgCbn
; return (pat, strs) }
_ | str : strs' <- strs
-> do { pat <- argToPat env in_scope val_env arg_ty arg occ str
@@ -2699,7 +2699,7 @@ argToPat :: ScEnv
-> Type -- ^ type for this argument
-> CoreArg -- ^ A call arg (or component thereof)
-> ArgOcc -- ^ occurrence info for the argument
- -> StrictnessMark -- ^ Tells us if this argument is a strict field of a data constructor
+ -> ArgCbvInfo -- ^ Tells us if this argument is a strict field of a data constructor
-- See Note [SpecConstr and strict fields]
-> UniqSM (Bool, CoreArg, [Id])
@@ -2726,7 +2726,7 @@ argToPat1 :: ScEnv
-> Type
-> Expr CoreBndr
-> ArgOcc
- -> StrictnessMark
+ -> ArgCbvInfo
-> UniqSM (Bool, Expr CoreBndr, [Id])
argToPat1 _env _in_scope _val_env _pat_ty arg@(Type {}) _arg_occ _arg_str
= return (False, arg, [])
@@ -2767,9 +2767,9 @@ argToPat1 env in_scope val_env _pat_ty arg arg_occ _arg_str
, not (ignoreDataCon env dc) -- See Note [NoSpecConstr]
, Just arg_occs <- mb_scrut dc
= do { let (ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) args
- con_str :: [StrictnessMark]
+ con_str :: [ArgCbvInfo]
-- con_str corresponds 1-1 with the /value/ arguments
- con_str = dataConRepStrictness dc
+ con_str = dataConRepArgCbvInfos dc
con_ty = applyTypeToArgs (dataConRepType dc) ty_args
-- ; pprTraceM "bangs" (ppr (length rest_args == length con_str) $$
-- ppr dc $$
@@ -2808,7 +2808,7 @@ argToPat1 env in_scope val_env _pat_ty (Var v) arg_occ arg_str
-- box that we can eliminate in the caller
, not (ignoreType env (varType v))
-- See Note [SpecConstr and strict fields]
- = return (True, Var v, if isMarkedStrict arg_str then [v] else mempty)
+ = return (True, Var v, if arg_str == ArgCbv then [v] else mempty)
where
is_value
| isLocalId v = v `elemInScopeSet` in_scope
@@ -2860,11 +2860,13 @@ argToPat1 _env _in_scope _val_env pat_ty _arg _arg_occ arg_str
= wildCardPat pat_ty arg_str
-- | wildCardPats are always boring
-wildCardPat :: Type -> StrictnessMark -> UniqSM (Bool, CoreArg, [Id])
+wildCardPat :: Type -> ArgCbvInfo -> UniqSM (Bool, CoreArg, [Id])
wildCardPat ty str
= do { id <- mkSysLocalOrCoVarM (fsLit "sc") ManyTy ty
-- ; pprTraceM "wildCardPat" (ppr id' <+> ppr (idUnfolding id'))
- ; return (False, varToCoreExpr id, if isMarkedStrict str then [id] else []) }
+ ; return (False, varToCoreExpr id, if str == ArgCbv then [id] else []) }
+ -- NB: unlifted (ArgCbv) args will be filtered out by
+ -- wantCbvForId in mkSeqs; see Note [SpecConstr and strict fields]
isValue :: ValueEnv -> CoreExpr -> Maybe Value
isValue _env (Lit lit)
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -221,7 +221,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
zapped_arg_vars = map zap_var arg_vars
; (subst, cloned_arg_vars) <- cloneBndrsM empty_subst zapped_arg_vars
; let res_ty' = substTyUnchecked subst res_ty
- init_str_marks = map (const NotMarkedStrict) cloned_arg_vars
+ init_str_marks = mapConst NotMarkedStrict cloned_arg_vars
; (useful1, work_args_str, wrap_fn_str, fn_args)
<- -- pprTrace "mkWWbodies" (ppr fun_id $$ ppr (arg_vars `zip` cloned_arg_vars) $$ ppr demands) $
@@ -1050,7 +1050,7 @@ unbox_one_arg opts arg_var
-- Mark arguments coming out of strict fields so we can seq them in the worker
-- See Note [Call-by-value for worker args]
- all_str_marks = (map (const NotMarkedStrict) ex_tvs') ++ con_str_marks
+ all_str_marks = mapConst NotMarkedStrict ex_tvs' ++ con_str_marks
; (nested_useful, worker_args, wrap_fn, wrap_args)
<- mkWWstr opts (ex_tvs' ++ arg_ids') all_str_marks
=====================================
compiler/GHC/Core/SimpleOpt.hs
=====================================
@@ -1726,12 +1726,10 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
-- See Note [Strict fields in Core] for what a field seq is and (SFC2) for
-- why we insert them
mkFieldSeqFloats in_scope dc args
- | isLazyDataConRep dc
- = (in_scope, nilOL, args)
- | otherwise
- = (in_scope', floats', ty_args ++ val_args')
+ | dataConRepIsLazy dc = (in_scope, nilOL, args) -- Short cut in common case
+ | otherwise = (in_scope', floats', tyco_args ++ val_args')
where
- (ty_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args
+ (tyco_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args
(in_scope', floats', val_args') = foldr do_one (in_scope, nilOL, []) $
zipEqual str_marks val_args
str_marks = dataConRepStrictness dc
=====================================
compiler/GHC/Core/TyCon.hs
=====================================
@@ -1504,16 +1504,27 @@ There are a number of wrinkles
(UCM2) The TyCon for a unary class is /not/ identified as a newtype.
Rather, it has its own AlgTyConRhs, namely `UnaryClassTyCon`
-(UCM3) Unlike non-unary classes, a value of type (C ty), where `C` is a unary
+(UCM3a) Unlike non-unary classes, a value of type (C ty), where `C` is a unary
class, might be bottom, because it is represented by the method type alone.
See GHC.Core.Type.isTerminatingType, and Note [NON-BOTTOM-DICTS invariant]
in GHC.Core
- Similarly in exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval,
- in GHC.Core.Utils. In the utility funcion `app_ok` we need a special
- case for the DFunIds; they generally terminate, but not for unary classes.
-
-(UMC4) To avoid regressions, in Core we want to remember that
+(UCM3b) Following (UCM3a), (MkC e) is a value, or ok-for-speculation, only if
+ `e` is. So `GHC.Core.Utils.exprIsHNF`, `exprIsConLike`, and `app_ok`
+ (used by exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval) have a
+ special case for unary-class data constructors. (#28183 shows why this
+ matters.)
+
+ We do /not/ achieve this by giving the data constructor a strict field
+ data C a = MkC !(a->a)
+ That would be semantically fine, but it leaks into DmdAnal, the StrictArg
+ treatment in the Simplifier, and the field seqs of (SFC2) in Note [Strict
+ fields in Core]; for example (op dict x) would become
+ case $cop of m { __DEFAULT -> m x }
+ which bloats code (T5321FD got 10% worse). Those field seqs are pointless
+ for unary classes anyway, because of (UCM13).
+
+(UCM4) To avoid regressions, in Core we want to remember that
(MkUC x) is really just x
(op d) is really just d
We account for this in several places:
@@ -3065,8 +3076,8 @@ isUnaryClassTyCon tc@(TyCon { tyConDetails = details })
isTerminatingTyCon :: TyCon -> Bool
-- ^ True <=> a value of type (T t1..tn), where `T` is this TyCon, cannot be bottom.
--- The only TyCons that satisfy `isTerminatingTyCon` are non-unary class TyCons.
--- See (UCM3) in Note [Unary class magic], and
+-- The only TyCons that satisfy `isTerminatingTyCon` are /non-unary/ class TyCons.
+-- See (UCM3a) in Note [Unary class magic], and
-- Note [NON-BOTTOM-DICTS invariant] in GHC.Core.
-- An AbstractTyCon returns False: it comes from an hs-boot file, and the real
-- declaration may turn out to be a unary class. See (NBD2) in that Note.
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -1781,7 +1781,7 @@ fun_kind_arg_flags = go emptySubst
where
argf | isVisibleFunArg af = Required
| otherwise = Inferred
- go _ _ arg_tys = map (const Required) arg_tys
+ go _ _ arg_tys = mapConst Required arg_tys
-- something is ill-kinded. But this can happen
-- when printing errors. Assume everything is Required.
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -2271,15 +2271,14 @@ app_ok fun_ok primop_ok fun val_args
| otherwise
= case idDetails fun of
DFunId terminating -> terminating
- -- DFuns terminate, unless the dict is implemented
- -- by a no-op in which case they may not
- -- See (UCM3) in Note [Unary class magic] in GHC.Core.TyCon
+ -- DFuns terminate, except for unary classes
+ -- See (UCM3a) in Note [Unary class magic] in GHC.Core.TyCon
DataConWorkId dc
- | isLazyDataConRep dc
- -> args_ok
- | otherwise
- -> fields_ok (dataConRepStrictness dc)
+ | isUnaryClassDataCon dc -> all ok_for_spec val_args
+ -- (MkC e) is just e; see (UCM3b) in Note [Unary class magic]
+ | dataConRepIsLazy dc -> True -- Args are all thunks
+ | otherwise -> fields_ok (dataConRepArgCbvInfos dc)
ClassOpId _ is_terminating_result
| is_terminating_result -- See Note [exprOkForSpeculation and type classes]
@@ -2344,13 +2343,16 @@ app_ok fun_ok primop_ok fun val_args
-- Used for strict DataCon worker arguments
-- See (SFC1) of Note [Strict fields in Core]
-- See Note [exprOkForSpeculation] (a,b)
- fields_ok str_marks = all3Prefix field_ok val_arg_tys str_marks val_args
- field_ok :: Type -> StrictnessMark -> CoreExpr -> Bool
- field_ok arg_ty str arg
- = ok_for_spec arg || (definitely_lifted arg_ty arg && str==NotMarkedStrict)
+ fields_ok arg_infos = all3Prefix field_ok val_arg_tys arg_infos val_args
+ field_ok :: Type -> ArgCbvInfo -> CoreExpr -> Bool
+ -- Conservative: treat ArgRepPoly as possibly strict; see Note [ArgCbvInfo]
+ field_ok _ ArgCbn _ = True
+ field_ok _ ArgCbv arg = ok_for_spec arg
+ field_ok arg_ty ArgRepPoly arg = arg_ok arg_ty arg
-- The (ok_for_spec arg) test works for /both/ for unlifted types, /and/
-- for lifted but strict fields. E.g. K (I# 3) is ok-for-spec,
-- even if K is strict
+ -- For ArgRepPoly, arg_ok looks at the type of the argument itself
-- We want to see if the argument type is definitely lifted.
-- But consider
@@ -2650,9 +2652,9 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
is_hnf_like e
where
is_hnf_like (Var v) -- NB: There are no value args at this point
- = id_app_is_value v [] -- Catches nullary constructors,
- -- so that [] and () are values, for example
- -- and (e.g.) primops that don't have unfoldings
+ = check_app v [] -- Catches nullary constructors,
+ -- so that [] and () are values, for example
+ -- and (e.g.) primops that don't have unfoldings
|| is_con_unf (idUnfolding v)
-- Check the thing's unfolding; it might be bound to a value
-- or to a guaranteed-evaluated variable (isEvaldUnfolding)
@@ -2687,67 +2689,75 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
= is_hnf_like rhs
is_hnf_like _ = False
- -- Collect arguments through Casts and Ticks and call id_app_is_value
+ -- Collect arguments through Casts and Ticks and call check_app
app_is_value :: CoreExpr -> [CoreArg] -> Bool
- app_is_value (Var f) as = id_app_is_value f as
+ app_is_value (Var f) as = check_app f as
app_is_value (Tick _ f) as = app_is_value f as
app_is_value (Cast f _) as = app_is_value f as
app_is_value (App f a) as | isValArg a = app_is_value f (a:as)
| otherwise = app_is_value f as
app_is_value _ _ = False
- id_app_is_value id val_args
- | Just dc <- isDataConWorkId_maybe id
- , isUnaryClassDataCon dc
- = all is_hnf_like val_args -- Look through unary class data cons
- | otherwise
- -- See Note [exprIsHNF for function applications]
- -- for the specification and examples
+ -- check_app: See Note [exprIsHNF for function applications]
+ -- for the specification and examples
+ -- We check arity (and CONLIKEness) first because it's cheaper
+ -- and we reject quickly on saturated apps.
+ check_app :: Id -> [CoreArg] -> Bool
+ check_app id val_args
= case compare (idArity id) (length val_args) of
- EQ | is_con id -> -- Saturated app of a DataCon/CONLIKE Id
- case mb_str_marks id of
- Just str_marks -> -- with strict fields; see (SFC1) of Note [Strict fields in Core]
- assert (val_args `equalLength` str_marks) $
- fields_hnf str_marks
- Nothing -> -- without strict fields: like PAP
- args_hnf -- NB: CONLIKEs are lazy!
-
- GT -> -- PAP: Check unlifted val_args
- args_hnf
+ EQ -> check_saturated id val_args -- Saturated application
+ GT -> check_args id val_args -- Partial application
+ LT -> False -- Over-saturated
- _ -> False
+ check_saturated :: Id -> [CoreArg] -> Bool
+ check_saturated id val_args
+ | Just dc <- isDataConWorkId_maybe id
+ , isUnaryClassDataCon dc -- (MkC e) is just e
+ = all is_hnf_like val_args -- See (UCM3b) in Note [Unary class magic]
+ | Just dc <- isDataConWorkId_maybe id
+ , let arg_infos = dataConRepArgCbvInfos dc
+ = -- Saturated data constructors; use `check_field`
+ -- to ensure we account for strict and unlifted fields
+ assertPpr (equalLength val_args arg_infos)
+ (ppr dc $$ ppr val_args $$ ppr arg_infos) $
+ all2Prefix check_field val_args arg_infos
+
+ | is_con id -- Saturated CONLIKE: check the arguments
+ = check_args id val_args
+
+ | otherwise -- Saturated function, not a constructor => not HNF
+ = False
+
+ -- check_args: check that any unlifted args are hnf-like
+ -- NB: there may be fewer val_args than arg_tys (e.g. (map f))
+ check_args :: Id -> [CoreArg] -> Bool
+ check_args id val_args = all2Prefix check_arg val_args arg_tys
where
- -- Saturated, Strict DataCon: Check unlifted val_args and strict fields
- fields_hnf str_marks = all3Prefix check_field val_arg_tys str_marks val_args
-
- -- PAP: Check unlifted val_args
- args_hnf = all2Prefix check_arg val_arg_tys val_args
-
- val_arg_tys = splitUninstantiatedValArgTys (idType id)
- -- val_arg_tys = map exprType val_args, but much less costly.
- -- The obvious definition regresses T16577 by 30% so we don't do it.
-
- check_arg a_ty a
- | mightBeUnliftedType a_ty = is_hnf_like a
- | otherwise = True
- -- Check unliftedness; for example f (x /# 12#) where f has arity two,
- -- and the first argument is unboxed. This is not a value!
- -- But f 34# is a value, so check args for HNFs.
- -- NB: We check arity (and CONLIKEness) first because it's cheaper
- -- and we reject quickly on saturated apps.
- check_field a_ty str a
- | mightBeUnliftedType a_ty = is_hnf_like a
- | isMarkedStrict str = is_hnf_like a
- | otherwise = True
- -- isMarkedStrict: Respect Note [Strict fields in Core]
-
- mb_str_marks id
- | Just dc <- isDataConWorkId_maybe id
- , not (isLazyDataConRep dc)
- = Just (dataConRepStrictness dc)
- | otherwise
- = Nothing
+ arg_tys = get_val_arg_tys id
+
+ -- check_arg: check unliftedness; for example f (x /# 12#) where f
+ -- has arity two, and the first argument is unboxed. This is not a value!
+ -- But f 34# is a value, so check unlifted args for HNFs.
+ check_arg arg arg_ty
+ | mightBeUnliftedType arg_ty = is_hnf_like arg
+ | otherwise = True
+
+ -- check_field: used for a data constructor worker:
+ -- check unlifted val_args /and/ strict fields
+ -- See (SFC1) of Note [Strict fields in Core]
+ -- Conservative: treat ArgRepPoly as possibly strict; see Note [ArgCbvInfo]
+ -- (check_arg would do the same, because the uninstantiated type of a
+ -- rep-poly field might be unlifted.)
+ check_field :: CoreArg -> ArgCbvInfo -> Bool
+ check_field _ ArgCbn = True
+ check_field arg ArgCbv = is_hnf_like arg
+ check_field arg ArgRepPoly = is_hnf_like arg
+
+ get_val_arg_tys id = splitUninstantiatedValArgTys (idType id)
+ -- val_arg_tys = map exprType val_args, but much less costly.
+ -- The obvious definition regresses T16577 by 30% so we don't do it.
+
{-
Note [exprIsHNF Tick]
@@ -2903,7 +2913,7 @@ dataConInstPat fss uniqs mult con inst_tys
ex_tvs = dataConExTyCoVars con
arg_tys = dataConRepArgTys con
arg_strs = dataConRepStrictness con -- 1-1 with arg_tys
- n_ex = length ex_tvs
+ n_ex = length ex_tvs
-- split the Uniques and FastStrings
(ex_uniqs, id_uniqs) = splitAt n_ex uniqs
=====================================
compiler/GHC/Tc/Gen/HsType.hs
=====================================
@@ -1369,7 +1369,7 @@ tc_hs_tuple_ty rn_ty mode HsBoxedOrConstraintTuple hs_tys exp_kind
checkExpectedKind hs_ty ty kind arg_kind
| ((L loc hs_ty),ty,kind) <- zip3 hs_tys tys kinds ]
- ; finish_tuple rn_ty tup_sort tys' (map (const arg_kind) tys') exp_kind }
+ ; finish_tuple rn_ty tup_sort tys' (mapConst arg_kind tys') exp_kind }
tc_hs_tuple_ty rn_ty mode HsUnboxedTuple tys exp_kind =
tc_tuple rn_ty mode UnboxedTuple tys exp_kind
=====================================
compiler/GHC/Tc/Gen/Pat.hs
=====================================
@@ -655,7 +655,7 @@ tc_pat scaled_exp_pat_ty@(Scaled w_pat exp_pat_ty) penv ps_pat thing_inside =
OrPat _ pats -> do -- See Note [Implementation of OrPatterns], Typechecker (1)
{ let pats_list = NE.toList pats
- pat_exp_tys = map (const scaled_exp_pat_ty) pats_list
+ pat_exp_tys = mapConst scaled_exp_pat_ty pats_list
; (pats_list', (res, pat_ct)) <- tc_lpats pat_exp_tys penv pats_list (captureConstraints thing_inside)
; let pats' = NE.fromList pats_list' -- tc_lpats preserves non-emptiness
; emitConstraints pat_ct
=====================================
compiler/GHC/Tc/TyCl.hs
=====================================
@@ -3713,7 +3713,7 @@ tcTyFamInstEqn fam_tc mb_clsinfo
-- (tcFamInstEqnGuts zonks to Type)
; let ax = mkCoAxBranch qtvs [] [] pats rhs_ty
- (map (const Nominal) qtvs)
+ (mapConst Nominal qtvs)
(locA loc)
vi = VI { vi_loc = locA loc
, vi_qtvs = qtvs
=====================================
compiler/GHC/Tc/TyCl/Build.hs
=====================================
@@ -291,9 +291,9 @@ type MethInfo -- A temporary intermediate, to communicate
buildClass :: Name -- Name of the class/tycon (they have the same Name)
-> Kind
- -> [TyConBinder] -- Of the tycon
+ -> [TyConBinder] -- Of the tycon
-> [Role]
- -> [FunDep TyVar] -- Functional dependencies
+ -> [FunDep TyVar] -- Functional dependencies
-> KnotTied ThetaType -- Superclasess
-> [ClassATItem] -- Associated types
-> [KnotTied MethInfo] -- Methods
@@ -330,7 +330,9 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
rec_tycon = classTyCon rec_clas
univ_bndrs = tyVarSpecToBinders $ tyConInvisTVBinders binders
univ_tvs = binderVars univ_bndrs
- bang_opts = FixedBangOpts (map (const HsLazy) args)
+ bang_opts = FixedBangOpts (mapConst HsLazy args)
+ -- NB: even for unary classes the field is lazy;
+ -- see (UCM3b) in Note [Unary class magic]
; rep_nm <- newTyConRepName datacon_name
; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs")
@@ -338,7 +340,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
datacon_name
False -- Not declared infix
rep_nm
- (map (const no_bang) args)
+ (mapConst no_bang args)
[{- No fields -}]
univ_tvs
[{- no existentials -}]
@@ -353,8 +355,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
; let rhs | unary_class
= UnaryClassTyCon dict_con
| isCTupleTyConName tycon_name
- = TupleTyCon { data_con = dict_con
- , tup_sort = ConstraintTuple }
+ = TupleTyCon { data_con = dict_con, tup_sort = ConstraintTuple }
| otherwise
= mkDataTyConRhs [dict_con]
=====================================
compiler/GHC/Tc/TyCl/Instance.hs
=====================================
@@ -837,7 +837,7 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env
rep_tc = mkAlgTyCon rep_tc_name user_kind
ty_binders (length extra_tcbs)
res_kind
- (map (const Nominal) ty_binders)
+ (mapConst Nominal ty_binders)
(fmap (typeCheckCType . unLoc) cType) stupid_theta
tc_rhs parent
gadt_syntax
=====================================
compiler/GHC/Tc/TyCl/Utils.hs
=====================================
@@ -471,7 +471,7 @@ initialRoleEnv hsc_src annots = extendNameEnvList emptyNameEnv .
initialRoleEnv1 :: HscSource -> RoleAnnotEnv -> TyCon -> (Name, [Role])
initialRoleEnv1 hsc_src annots_env tc
- | isFamilyTyCon tc = (name, map (const Nominal) bndrs)
+ | isFamilyTyCon tc = (name, mapConst Nominal bndrs)
| isAlgTyCon tc = (name, default_roles)
| isTypeSynonymTyCon tc = (name, default_roles)
| otherwise = pprPanic "initialRoleEnv1" (ppr tc)
=====================================
compiler/GHC/Types/Demand.hs
=====================================
@@ -59,7 +59,7 @@ module GHC.Types.Demand (
nopDmdType, botDmdType,
lubDmdType, maxDmdType, plusDmdType, multDmdType, discardArgDmds,
-- ** Other operations
- peelFV, findIdDemand, addDemand, splitDmdTy, deferAfterPreciseException,
+ peelFV, findIdDemand, addDemand, splitDmdTy, splitArgDmd, deferAfterPreciseException,
-- * Demand signatures
DmdSig(..), mkDmdSigForArity, mkClosedDmdSig, mkVanillaDmdSig,
@@ -92,7 +92,7 @@ import GHC.Types.Basic
import GHC.Data.Maybe ( orElse )
import GHC.Core.Type ( Type, isTerminatingType )
-import GHC.Core.DataCon ( splitDataProductType_maybe, StrictnessMark, isMarkedStrict )
+import GHC.Core.DataCon ( splitDataProductType_maybe, ArgCbvInfo(..) )
import GHC.Core.Multiplicity ( scaledThing )
import GHC.Utils.Binary
@@ -1996,6 +1996,24 @@ splitDmdTy :: DmdType -> (Demand, DmdType)
splitDmdTy ty@DmdType{dt_args=dmd:args} = (dmd, ty{dt_args=args})
splitDmdTy ty@DmdType{dt_env=env} = (defaultArgDmd (de_div env), ty)
+splitArgDmd :: DmdType -> Maybe (Demand, DmdType)
+-- ^ Split off the demand on the next argument of a function with this DmdType
+-- * Nothing <=> the call is definitely bottom; that is, we have run
+-- out of argument demands, and the divergence isDeadEndDiv
+-- * Just (d, ty') <=> d is the demand on the next argument
+-- Contrast `splitDmdTy`, which returns the default argument demand when
+-- we run out, rather than Nothing.
+-- Used in the Simplifier; see Note [Trimming the continuation for bottoming functions]
+-- in GHC.Core.Opt.Simplify.Iteration
+{-# INLINE splitArgDmd #-}
+splitArgDmd ty@(DmdType { dt_args = dmd : dmds })
+ = Just (dmd, ty { dt_args = dmds })
+splitArgDmd ty@(DmdType { dt_env = env })
+ | isDeadEndDiv div = Nothing
+ | otherwise = Just (defaultArgDmd div, ty)
+ where
+ div = de_div env
+
multDmdType :: Card -> DmdType -> DmdType
multDmdType C_11 dmd_ty = dmd_ty -- a vital optimisation for T25196
multDmdType n (DmdType fv args)
@@ -2487,17 +2505,19 @@ dmdTransformSig (DmdSig dmd_ty@(DmdType _ arg_ds)) sd
-- | A special 'DmdTransformer' for data constructors that feeds product
-- demands into the constructor arguments.
-dmdTransformDataConSig :: [StrictnessMark] -> DmdTransformer
+dmdTransformDataConSig :: [ArgCbvInfo] -> DmdTransformer
-- See Note [Demand transformer for data constructors]
-dmdTransformDataConSig str_marks sd = case viewProd arity body_sd of
+dmdTransformDataConSig arg_infos sd = case viewProd arity body_sd of
Just (_, dmds) -> mk_body_ty n dmds
Nothing -> nopDmdType
where
- arity = length str_marks
+ arity = length arg_infos
(n, body_sd) = peelManyCalls arity sd
- mk_body_ty n dmds = DmdType nopDmdEnv (zipWith (bump n) str_marks dmds)
- bump n str dmd | isMarkedStrict str = multDmd n (plusDmd str_field_dmd dmd)
- | otherwise = multDmd n dmd
+ mk_body_ty n dmds = DmdType nopDmdEnv (zipWith (bump n) arg_infos dmds)
+ -- ArgRepPoly: treat as lazy, which is the conservative choice here
+ -- See Note [ArgCbvInfo] in GHC.Core.DataCon
+ bump n ArgCbv dmd = multDmd n (plusDmd str_field_dmd dmd)
+ bump n _ dmd = multDmd n dmd
str_field_dmd = seqDmd -- See the bit about strict fields
-- in Note [Demand transformer for data constructors]
=====================================
compiler/GHC/Types/Id/Make.hs
=====================================
@@ -541,7 +541,6 @@ mkDataConWorkId wkr_name data_con
univ_tvs = dataConUnivTyVars data_con
ex_tcvs = dataConExTyCoVars data_con
arg_tys = dataConRepArgTys data_con -- Should be same as dataConOrigArgTys
- str_marks = dataConRepStrictness data_con
----------- Workers for data types --------------
alg_wkr_info = noCafIdInfo
@@ -555,12 +554,22 @@ mkDataConWorkId wkr_name data_con
`setLFInfo` wkr_lf_info
wkr_inline_prag = alwaysConLikePragma
- wkr_arity = dataConRepArity data_con
- wkr_sig = mkClosedDmdSig wkr_dmds topDiv
- wkr_dmds = map mk_dmd str_marks
- mk_dmd MarkedStrict = evalDmd
- mk_dmd NotMarkedStrict = topDmd
+ -- Strictness signature has arity = wkr_arity
+ -- i.e. including any existential CoVars
+ -- See (EXCO1) in Note [Existential coercion variables]
+ wkr_arity = dataConRepArity data_con
+ arg_infos = dataConRepArgCbvInfos data_con
+ wkr_dmds = map mk_dmd arg_infos
+ wkr_sig = assertPpr (arg_infos `lengthIs` wkr_arity &&
+ splitUninstantiatedValArgTys wkr_ty `lengthIs` wkr_arity)
+ (ppr data_con $$ ppr arg_infos $$ ppr wkr_ty) $
+ mkClosedDmdSig wkr_dmds topDiv
+ -- NB: GHC.Core.Opt.Simplify.Utils.dataConArgInfo uses this signature,
+ -- and relies on ArgRepPoly being treated as lazy; see Note [ArgCbvInfo]
+ mk_dmd ArgCbv = evalDmd
+ mk_dmd ArgCbn = topDmd
+ mk_dmd ArgRepPoly = topDmd
-- See Note [LFInfo of DataCon workers and wrappers]
wkr_lf_info
@@ -824,7 +833,7 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con
wrap_ty = dataConWrapperType data_con
ev_tys = eqSpecPreds eq_spec ++ theta
all_arg_tys = map unrestricted ev_tys ++ orig_arg_tys
- ev_ibangs = map (const HsLazy) ev_tys
+ ev_ibangs = mapConst HsLazy ev_tys
orig_bangs = dataConSrcBangs data_con
wrap_arg_tys
@@ -852,14 +861,14 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con
arg_ibangs
| new_tycon
- = map (const HsLazy) orig_arg_tys -- See Note [HsImplBangs for newtypes]
- -- orig_arg_tys should be a singleton, but
- -- if a user declared a wrong newtype we
- -- detect this later (see test T2334A)
+ = mapConst HsLazy orig_arg_tys -- See Note [HsImplBangs for newtypes]
+ -- orig_arg_tys should be a singleton, but
+ -- if a user declared a wrong newtype we
+ -- detect this later (see test T2334A)
| otherwise
= case dc_bang_opts of
SrcBangOpts bang_opts -> zipWith (dataConSrcToImplBang platform bang_opts fam_envs)
- orig_arg_tys orig_bangs
+ orig_arg_tys orig_bangs
FixedBangOpts bangs -> bangs
(rep_tys_w_strs, wrappers)
@@ -999,11 +1008,11 @@ For further reading, see:
Note [Bangs on imported data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs
+We pass `DataConBangOpts` to `mkDataConRep` to make use of `HsImplBangs`
from imported modules.
-- Nothing <=> use HsSrcBangs
-- Just bangs <=> use HsImplBangs
+- SrcBangOpts opts <=> use HsSrcBangs
+- FixedBangOpts impl_bangs <=> use impl_bangs
For imported types we can't work it all out from the HsSrcBangs,
because we want to be very sure to follow what the original module
@@ -1011,8 +1020,8 @@ because we want to be very sure to follow what the original module
flags were enabled when it was compiled. So we record the decisions in
the interface file.
-The HsImplBangs passed are in 1-1 correspondence with the
-dataConOrigArgTys of the DataCon.
+The `HsImplBangs` passed are in 1-1 correspondence with the
+`dataConOrigArgTys` of the DataCon.
Note [Data con wrappers and unlifted types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Utils/Misc.hs
=====================================
@@ -18,7 +18,7 @@ module GHC.Utils.Misc (
unzipWith,
- mapFst, mapSnd, chkAppend,
+ mapFst, mapSnd, mapConst, chkAppend,
mapAndUnzip, mapAndUnzip3, mapAndUnzip4,
filterOut, partitionWith, partitionWithM,
@@ -329,6 +329,10 @@ mapSnd :: Functor f => (b->c) -> f(a,b) -> f(a,c)
mapFst = fmap . first
mapSnd = fmap . second
+mapConst :: a -> [b] -> [a]
+-- (mapConst k [a,b,c]) returns [k,k,k]
+mapConst k xs = [ k | _ <- xs ]
+
zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d])
zipWithAndUnzip f (a:as) (b:bs)
= let (r1, r2) = f a b
=====================================
testsuite/tests/simplCore/should_compile/T28169.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE MagicHash #-}
+
+module T28169 where
+import GHC.Exts
+
+f :: Int# -> (Int,Int)
+f x = let y = I# (let z = x +# 1# in z *# z)
+ in (y + y, y * y)
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,6 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+
+# T28169: test that there are no calls to boxed arithmetic,e.g. GHC.Internal.Num.$fNumInt_$c+
+test('T28169', grep_errmsg(r'\$c'), compile, ['-O -ddump-simpl -dsuppress-uniques'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/750032e34ac16192323604eed84a1b6…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/750032e34ac16192323604eed84a1b6…
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
26 Nov '26
Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC
Commits:
694da176 by Simon Peyton Jones at 2026-11-26T13:47:42+00:00
Add splitThunkCpr
This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form
of "thunk splitting" for strict bindings that have CPR information.
See Note [Thunk splitting] in WorkWrap.hs 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.
- - - - -
11 changed files:
- compiler/GHC/Core/Opt/CprAnal.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/WorkWrap.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Utils/Monad.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/CprAnal.hs
=====================================
@@ -173,6 +173,25 @@ So currently we have
1. Strictness
2. CPR
3. worker/wrapper (for strictness and CPR)
+
+Wrinkles
+
+(CPR1) We have a flag `-fcpr-anal`, which sets `Opt_CprAnal`, enabled in -O1 and
+ -O1. Strangely, it does /not/ switch off CPR analysis! Rather, it just
+ switches off the worker/wrapper exploitation of CPR analysis, in `mkWWcpr_entry`.
+ The analysis itself runes whenever `-fstrictness` is on.
+
+ This is peculiar and, I suspect accidental. It would make more sense to switch
+ off the analysis itself with `-fno-cpr-anal`.
+
+ It goes back to at least
+ commit ecb1752ffa12dfa71053f640e6cce64d15e47e8f
+ Author: Christiaan Baaij <christiaan.baaij(a)gmail.com>
+ Date: Wed Aug 5 14:22:14 2015 +0200
+
+ Make -fcpr-off a dynamic flag
+
+ This note is just a breadcrumb to inform the next person who trips over this.
-}
--
@@ -343,7 +362,7 @@ cprTransform env id args
-- Any local binding, except for data structure bindings
-- See Note [Efficient Top sigs in SigEnv]
| Just sig <- lookupSigEnv env id
- = applyCprTy (getCprSig sig) (length args)
+ = applyCprTy (cprSigType sig) (length args)
-- See Note [CPR for data structures]
| Just rhs <- cprDataStructureUnfolding_maybe id
= fst $ cprAnal env rhs
@@ -362,7 +381,7 @@ cprTransform env id args
= cprTransformDataConWork env con args
-- Imported function
| otherwise
- = applyCprTy (getCprSig (idCprSig id)) (length args)
+ = applyCprTy (cprSigType (idCprSig id)) (length args)
-- | Precise, hand-written CPR transformers for select Ids
cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType
@@ -870,27 +889,42 @@ Does f have the CPR property? Well, no.
However, if the strictness analyser has figured out (in a previous
iteration) that it's strict, then we DON'T need to forget the CPR info.
Instead we can retain the CPR info and do the thunk-splitting transform
-(see WorkWrap.splitThunk).
+(see Note [Thunk splitting] esp (B) CPR-led thunk splitting).
This made a big difference to PrelBase.modInt, which had something like
modInt = \ x -> let r = ... -> I# v in
...body strict in r...
-r's RHS isn't a value yet; but modInt returns r in various branches, so
-if r doesn't have the CPR property then neither does modInt
+r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so
+if `r` doesn't have the CPR property then neither does `modInt`
+
Another case I found in practice (in Complex.magnitude), looks like this:
- let k = if ... then I# a else I# b
- in ... body strict in k ....
+ let k* = if ... then I# a else I# b
+ in ... body strict in k ....
(For this example, it doesn't matter whether k is returned as part of
the overall result; but it does matter that k's RHS has the CPR property.)
+
Left to itself, the simplifier will make a join point thus:
- let $j k = ...body strict in k...
- if ... then $j (I# a) else $j (I# b)
+ let $j k = ...body strict in k...
+ if ... then $j (I# a) else $j (I# b)
+
With thunk-splitting, we get instead
- let $j x = let k = I#x in ...body strict in k...
- in if ... then $j a else $j b
+ let k* = case (if ... then I# a else I# b) of I# z -> I# z
+ in ... body strict in k ....
+Now the simplifier should pull out the `case` to give
+ case (if ... then I# a else I# b) of I# z ->
+ let k = I# z in ... body strict in k ...
+Now case-of-if will give
+ let $j z = let k = I# z in ...body strict in k... in
+ if ... then $j a else $j b
This is much better; there's a good chance the I# won't get allocated.
+TL'DR: During CPR analysis we want to give `k` the CPR property in `body`.
+
+What if the type involved has more than one constructor? E.g.
+ let k* = if ... then Just a else Just b
+ in ... body strict in k ....
+That is good too: see (TS5) in Note [Thunk splitting]
-But what about botCpr? Consider
+Finally, what about botCpr? Consider
lvl = error "boom"
fac -1 = lvl
fac 0 = 1
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -51,7 +51,6 @@ import GHC.Types.Literal ( litIsLifted ) --, mkLitInt ) -- temporarily comment
import GHC.Types.SourceText
import GHC.Types.Id
import GHC.Types.Id.Info
-import GHC.Types.Cpr( isTopCprSig )
import GHC.Types.InlinePragma
import GHC.Types.Name ( mkSystemVarName, isExternalName, getOccFS )
import GHC.Types.Demand
@@ -1830,7 +1829,7 @@ simplNonRecE :: HasDebugCallStack
simplNonRecE env from_what bndr (rhs, rhs_se) body cont
| assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True
- , useStrictBind env from_what bndr
+ , useStrictBind env from_what bndr rhs
= -- Evaluate RHS strictly
simplExprF (rhs_se `setInScopeFromE` env) rhs
(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
@@ -1865,11 +1864,10 @@ simplRecE env pairs body cont
; return (floats1 `addFloats` floats2, expr') }
-useStrictBind :: SimplEnv -> FromWhat -> InId -> Bool
+useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool
-- Can we use a StrictBind continuation for this let-binding?
--- If so, return a binder that is suitable to become a lambda binder,
--- i.e. one satisfying `lamBndrInfoOK`; see (SB3) in Note [StrictBind]
-useStrictBind env from_what bndr
+-- See (SB3) in Note [StrictBind]
+useStrictBind env from_what bndr rhs
-- If we are coming from a beta-reduction (FromBeta) we must
-- establish the let-can-float invariant, so we must go via StrictBind
-- If not, the invariant holds already, and it's optional.
@@ -1880,6 +1878,11 @@ useStrictBind env from_what bndr
| not (isStrUsedDmd dmd_info)
= False
+ -- Not if the RHS is ok-for-spec; no benefit. In particular if the RHS is a
+ -- value lambda, we return False: only thunks use StrictBind
+ | exprOkForSpeculation rhs
+ = False
+
-- Not if case-of-case is off
-- See (SB1) in Note [StrictBind]
| not (seCaseCase env)
@@ -1889,13 +1892,8 @@ useStrictBind env from_what bndr
= True
-- Not for things with RULES or INLINE or NOINLINE
- -- or with a strictnes or CPR signature -- all things we might lose
-- See (SB3) in Note [StrictBind]
- | isStableUnfolding (unfoldingInfo info)
- || not (isEmptyRuleInfo (ruleInfo info))
- || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
- || not (isNopSig (dmdSigInfo info))
- || not (isTopCprSig (cprSigInfo info))
+ | hasRulesOrInline info
= False
| otherwise
@@ -4243,9 +4241,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
, alt') }
-- See Note [Duplicated env]
-{-
-Note [Do not add unfoldings to join points at birth]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [Do not add unfoldings to join points at birth]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15360)
case (case (case (case ...))) of
@@ -4316,7 +4313,7 @@ The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
- StrictBind body Stop
+ StrictBind body Stop))
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
@@ -4455,7 +4452,7 @@ hack and bit us in multiple small and not-so-small ways
Consider this
case (case .. ) of c {
- I# c# -> ....c....
+ I# c# -> ....c.... }
If we make a join point with c but not c# we get
$j = \c -> ....c....
@@ -4655,30 +4652,56 @@ We simplify `rhs` with a StrictBind continuation that continues with
invariants] in GHC.Core. But a let-binder `x` usually has IdInfo that a
lambda binder may not have (an unfolding, arity, a demand signature...).
- So `useStrictBind_maybe` zaps that info, keeping only the occurrence info
- and the demand info. If it happens to stay as a let-binding arity info will
- be re-derived, so nothing is lost.
+ So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use
+ `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence
+ info and the demand info.
- The exceptions are RULES, a stable unfolding, and a non-default inlining
- activation: these cannot be re-derived, and we have nowhere convenient to
- put them if `x` becomes a lambda binder. For example:
+ However, if the let-binder has
+ * RULES
+ * a stable unfolding
+ * a non-default inlining activation
+ we'd permanently lose these things if we lambda-bind it. For example:
let {-# NOINLINE x #-}
x! = case y of { ... }
in blah
- If we make a join point j x = blah, we have nowhere convenient
- to put that NOINLINE. Ditto INLINE or RULES. So in these cases we
- simply don't use StrictBind. It's very unusual, so no harm done.
- But it does happen; one example is this, in the Applicative (ST s)
- instance in GHC.Internal.Control.Monad.St.Lazy.Imp
+ If we make a join point j x = blah, we have nowhere convenient to put that
+ NOINLINE. Ditto INLINE or RULES. It's unusual. But it happens; one example
+ is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp
{-# NOINLINE res1 #-}
!res1 = unST fm s
- TL;DR: the sc_bndr::Id field in StrictBind always satisfies `lamBndrInfoOK`.
- This means that in the above example { x! = case y of ... } we won't
- float the `case y` out. And perhaps that's fine because of the NOINLNE.
- We could imagine instead imposing these conditions only when we /duplicate/
- the StrictBind, rather than when we /create/ it, but that would require a
- bigger refactor.
+ So in these cases we simply don't use StrictBind -- see `useStrictBind`. We
+ could imagine instead imposing these conditions only when we /duplicate/ the
+ StrictBind, rather than when we /create/ it, but that would require a bigger
+ refactor. See (SB5) for why we don't worry if the binder has strictness or
+ CPR information.
+
+(SB4) Shortcoming: not using StrictBind has a cost. If we have
+ {-# NOINLINE x #-}
+ x! = case y of (a,b) -> a
+ then isnce x is used strictly, we'd usually float that `case y` outwards -- but
+ we do so precisely by using StrictBind. But since the NOINLINE stops us using
+ StrictBind we won't float out the case.
+
+ Fixing this would require `mkDupableCont` to return a non-duplicable tail of
+ the continuation (declining to duplicate a StrictBind with a NOINLINE, say).
+ But that's a lot of plumbing for a very narrow case. Who writes INLINE or NOINLINE
+ or RULES for a thunk? So we just accept the shortcoming.
+
+(SB5) What if a thunk has a strictness signature, or CPR information? We
+ could make `useStrictBind` say False in these cases too, but that turns
+ out to be a net loss: keeping a thunk is worse than losing the strictness
+ information. Example, where f1,f2 are both strict:
+ let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 }
+ in body
+ Keeping it as-is would use CBV for calls of `f` in `body`. But
+ allowing StrictBind would give us
+ join j f* = body
+ in case x of { True -> j f1; False -> j f2 }
+ which avoids the thunk. It's a trade-off.
+
+ For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap,
+ especially (B) CPR-led thunk splitting.
Note [Join point abstraction] Historical note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Core/Opt/WorkWrap.hs
=====================================
@@ -598,13 +598,20 @@ tryWW ww_opts is_rec fn_id rhs
= splitFun ww_opts new_fn_id rhs
-- See Note [Thunk splitting]
- | isNonRec is_rec, is_thunk
- = splitThunk ww_opts is_rec new_fn_id rhs
+ | isNonRec is_rec -- See (TS4)
+ , is_thunk -- All join points go via splitFun
+ , not (hasRulesOrInline (fn_info)) -- See (TS9)
+ = do { -- Try strictness then CPR; see (TS5)
+ rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM`
+ splitThunkCpr ww_opts new_fn_id rhs `orElseM`
+ return rhs
+ ; return [ (new_fn_id, rhs') ] }
| otherwise
= return [ (new_fn_id, rhs) ]
where
+ is_join = isJoinId fn_id
fn_info = idInfo fn_id
(wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info)
new_fn_id = zap_join_cpr $ zap_usage fn_id
@@ -613,14 +620,13 @@ tryWW ww_opts is_rec fn_id rhs
-- See Note [Zapping DmdEnv after Demand Analyzer] and
-- See Note [Zapping Used Once info in WorkWrap]
- zap_join_cpr id
- | isJoinId id = id `setIdCprSig` topCprSig
- | otherwise = id
+ zap_join_cpr id | is_join = id `setIdCprSig` topCprSig
+ | otherwise = id
-- See Note [Don't w/w join points for CPR]
- is_fun = notNull wrap_dmds || isJoinId fn_id
- is_thunk = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id)
- && not (isUnliftedType (idType fn_id))
+ is_fun = notNull wrap_dmds || is_join
+ is_thunk = not (exprIsHNF rhs)
+ && not (isUnliftedType (idType fn_id))
{-
Note [Zapping DmdEnv after Demand Analyzer]
@@ -806,7 +812,7 @@ splitFun ww_opts fn_id rhs
(wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info)
- cpr_ty = getCprSig (cprSigInfo fn_info)
+ cpr_ty = cprSigType (cprSigInfo fn_info)
-- Arity of the CPR sig should match idArity when it's not a join point.
-- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal
cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info)
@@ -957,114 +963,182 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>]
Note [Thunk splitting]
~~~~~~~~~~~~~~~~~~~~~~
-Suppose x is used strictly; never mind whether it has the CPR
-property. I'll use a '*' to mean "x* is demanded strictly".
-
- let
- x* = x-rhs
+The worker/wrapper split mainly affects let-bound /functions/. But we can also use
+demand and CPR information to improve let-bound /thunks/. Specifically:
+
+* (A) Demand-led thunk splitting:
+ If a thunk is demanded strictly, perhaps nestedly, we can turn it into a
+ case, perhaps nestedly. For example
+ let x :: (Int, Int)
+ {- Dmd = SP(S,L) -}
+ x = rhs
+ in body
+ We would ultimately like to get
+ case rhs of x { (a,b) ->
+ case a of { I# a# ->
+ body
+
+ This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x`
+ and `a` inside `body`.
+
+* (B) CPR-led thunk splitting:
+ If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly
+ at top level, we can again generate a case
+ let x :: (Int, Int)
+ {- Dmd = S, Cpr = (_, I# _) -}
+ x = rhs
+ in body
+ The CPR info says that if `x` is evaluated (which it is), it'll return a pair,
+ whose second component can very cheaply be evaluated to a (I# b#). We would
+ like to end up with
+ case rhs of x { (a,b) ->
+ case b of { I# b# ->
+ body
+ which is good for the same reasons as before. See (TS3) for an example.
+
+Implementation
+~~~~~~~~~~~~~~
+The worker/wrapper pass does not generate these nested case expressions directly.
+Instead it generates a regular let-binding but, since the binder is marked as
+strict, any `case` expressions in the RHS will float out. Specifically:
+
+(TS1) For (A), `splitThunkStr` generates the binding
+ let x! = case rhs of { (a,b) ->
+ case a of { I# a# ->
+ (I# a, b)
+ Now when the Simplifier floats the `case` expressions out, we get
+ case rhs of { (a,b) ->
+ case a of { I# a# ->
+ let x = (I# a, b)
in body
+ which is equivalent to the expression in (A) above.
-splitThunk transforms like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> I# a }
- in body
+ `splitThunkStr` also works on /absent/ thunks: see (TS6).
-This is a little strange: we are re-using the same `x` in the RHS; and
-the RHS takes `x` apart and reboxes it. But because the outer 'let' is
-strict, and the inner let mentions `x` only once, the simplifier
-transform it to
- case x-rhs of
- I# a -> let x* = I# a
- in body
-
-That is good: in `body` we know the form of `x`, which
- * gives the CPR property, and
- * allows case-of-case to happen on x
-
-Notes
-* I tried transforming like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> x }
- in body
- where I return `x` itself, rather than reboxing it. But this
- turned out to cause some regressions, which I never fully
- investigated.
-
-* Suppose x-rhs is itself a case:
- x-rhs = case e of { T -> I# e1; F -> I# e2 }
- Then we'll get
- join j a = let x* = I# a in body
- in case e of { T -> j e1; F -> j e2 }
- which is good (no boxing). But in the original, unsplit program
- we would transform
- let x* = case e of ... in body
- ==> join j2 x = body
- in case e of { T -> j2 (I# e1); F -> j (I# e2) }
- which is not good (boxing).
+ Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function
+ argument w/w splitting function, to do the unpacking. This automatically
+ deals with nested strictness.
-* In fact, splitThunk uses the function argument w/w splitting
- function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L))
- then the splitting will go deeper too.
+(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again
+ using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks.
-* For recursive thunks, the Simplifier is unable to float `x-rhs` out of
- `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
- back to the original definition, so we just split non-recursive thunks.
+Wrinkles:
-Note [Thunk splitting for top-level binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Top-level bindings are never strict. Yet they can be absent, as T14270 shows:
-
- module T14270 (mkTrApp) where
- mkTrApp x y
- | Just ... <- ... typeRepKind x ...
- = undefined
- | otherwise
- = undefined
- typeRepKind = Tick scc undefined
-
-(T19180 is a profiling-free test case for this)
-Note that `typeRepKind` is not exported and its only use site in
-`mkTrApp` guards a bottoming expression. Thus, demand analysis
-figures out that `typeRepKind` is absent and splits the thunk to
-
- typeRepKind =
- let typeRepKind = Tick scc undefined in
- let typeRepKind = absentError in
- typeRepKind
-
-But now we have a local binding with an External Name
-(See Note [About the NameSorts]). That will trigger a CoreLint error, which we
-get around by localising the Id for the auxiliary bindings in 'splitThunk'.
+(TS3) Here's an example of (B), thunk-splitting based on CPR information.
+ Suppose we have
+ let x! = case e of { T -> Just e1; F -> Just e2 }
+ in body
+ If the Simplifier floats the `case` out, we get
+ join j2 x = body
+ in case e of { T -> j2 (Just e1); F -> j2 (Just e2) }
+ which is not good (boxing).
+
+ If we first do the thunk-splitting transformation, we get
+ let x! = case (case e of { T -> Just e1; F -> Just e2 }) of
+ Just a -> Just a
+ in body
+
+ Now when the Simplifier floats we will get:
+ join j a = let x = Just a in body
+ in case e of { T -> j e1; F -> j e2 }
+ which is much better (no boxing). But see (TS9).
+
+(TS4) We only do thunk-splitting for thunks that are non-recursive
+ For recursive thunks, the Simplifier is unable to float `rhs` out of
+ x's RHS, because `x` occurs freely in `rhs`, and will just change it
+ back to the original definition.
+
+(TS5) Notice that (B) CPR-led thunk splitting can be useful:
+ * when multi-constructor data types are involved, so that the argument-unboxing
+ mechanism (A) is impotent. See the example in (TS3), which uses `Maybe`.
+ * when the binder is only demanded head-strictly, but CPR has nested information.
+
+ So (A) and (B) have complementary benefits. We might do even better by
+ /combining/ (A) and (B), but at the moment we try (A) first, and then try (B)
+ if (A) is impotent. Combining them would be more work.
+
+(TS6) We can also exploit /absence/. Consider
+ let x {-# Dmd = A #-} = rhs
+ in body
+ Generally speaking `x` will be absent becuase it is passed to functions that
+ don't use it, in which case worker/wrapper on those calls will make `x` unused.
+ But suppose `x` is absent inside a /lazy/ argument:
+ let f p = (fst p, 99) in
+ let x = rhs in
+ f (True, x)
+ Here f's argument is lazy, but `x` is definitely absent, and we could replace
+ `x` with an absent filler. Using (TS1) would give us
+ let x = absentError "urk" in ...
+ which is great.
+
+ So `splitThunkStr` works /regardless/ of the demand on `x`; whether it fires is
+ determined only by the `useful` flag returned by `mkWWstr_one`.
+
+(TS7) Adopting (TS6) leads to one other complication: a top-level binder with
+ an External Name (see Note [About the NameSorts]) can be Absent. If so,
+ it must not be used as a local binder in the `Let` created by `splitThunkStr`.
+ T19180 is a test case for this rather obscure situation.
+
+ Solution: use `localiseId` to localise the binder for the `Let`.
+
+(TS8) Consider out poster child test case for `splitThunkCpr`, in (TS3).
+ x! = case e of { True -> Just 1; False -> Just 2 }
+ But suppose we have `-fworker-wrapper-cbv` enabled (reminder: see
+ Note [Worker/wrapper for strict arguments]). Then alas `splitThunkStr`
+ will fire, but it'll be a no-op in this case. But since it fires, `splitThunkCpr`
+ never gets a chance.
+
+ Hacky but effective solution: switch off `wo_unlift_strict` locally in `splitThunkStr`.
+
+(TS9) `splitThunkStr` implicitly relies on floating a case out of a strict binding.
+ But if the thunk has a RULE or INLINE/NOINLINE pragma that won't happen; see
+ (SB4) in Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration. So we test
+ these things before applying thunk splitting.
-}
--- | See Note [Thunk splitting].
---
--- splitThunk converts the *non-recursive* binding
+-- | splitThunkStr converts the *non-recursive* binding
-- x = e
-- into
--- x = let x' = e in
--- case x' of I# y -> let x' = I# y in x'
--- See comments above. Is it not beautifully short?
--- Moreover, it works just as well when there are
--- several binders, and if the binders are lifted
--- E.g. x = e
--- --> x = let x' = e in
--- case x' of (a,b) -> let x' = (a,b) in x'
--- Here, x' is a localised version of x, in case x is a
--- top-level Id with an External Name, because Lint rejects local binders with
--- External Names; see Note [About the NameSorts] in GHC.Types.Name.
---
--- How can we do thunk-splitting on a top-level binder? See
--- Note [Thunk splitting for top-level binders].
-splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)]
-splitThunk ww_opts is_rec x rhs
- = assert (not (isJoinId x)) $
- do { let x' = localiseId x -- See comment above
- ; (useful,_args, wrap_fn, fn_arg)
- <- mkWWstr_one ww_opts x' NotMarkedStrict
- ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ]
- ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive
- return res
- else return [(x, rhs)] }
+-- x = let x = e in
+-- case x of I# y -> I# y
+-- See Note [Thunk splitting].
+splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+splitThunkStr ww_opts x rhs
+ = -- NB: does not depend on x's demand being strict; it might be absent, see (TS6)
+ do { let x' = localiseId x -- See (TS7)
+ ww_opts' = ww_opts { wo_unlift_strict = False } -- See (TS8)
+ ; (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts' x' NotMarkedStrict
+ -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting]
+
+ ; if useful
+ then return (Just (Let (NonRec x' rhs) $
+ wrap_fn fn_arg))
+ else return Nothing }
+
+splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+-- See Note [Thunk splitting]
+-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR
+-- property, say Just (Just _), return this new RHS:
+-- let x' = rhs in
+-- case x' of { Just p -> case p of { Just q -> -- Unpacking code
+-- Just (Just q) }} -- Repacking code
+-- Works for multi-constructor data types, where splitThunkStr will fail
+splitThunkCpr ww_opts x rhs
+ | wo_cpr_anal ww_opts -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
+ , isStrUsedDmd (idDemandInfo x) -- See (TS2)
+ = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $ -- It's a thunk
+ do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr
+ -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting]
+ ; if useful
+ then return (Just (Let (NonRec x rhs) $
+ unpacker rebuild_result))
+ else return Nothing }
+
+ | otherwise
+ = return Nothing
+ where
+ cpr_type :: CprType
+ cpr_type = cprSigType (idCprSig x)
+ cpr :: Cpr
+ cpr = cprTypeCpr cpr_type
+
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser
{-# LANGUAGE ViewPatterns #-}
module GHC.Core.Opt.WorkWrap.Utils
- ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one
+ ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one
, needsVoidWorkerArg
, DataConPatContext(..)
, UnboxingDecision(..), canUnboxArg
@@ -139,13 +139,18 @@ data WwOpts
= MkWwOpts
{ -- | Environment of type/data family instances
wo_fam_envs :: !FamInstEnvs
+
, -- | Options for the "Simple optimiser"
wo_simple_opts :: !SimpleOpts
+
, -- | Whether to enable "Constructed Product Result" analysis.
-- (Originally from DOI: 10.1017/S0956796803004751)
+ -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
wo_cpr_anal :: !Bool
+
, -- | Used for absent argument error message
wo_module :: !Module
+
, -- | Generate workers even if the only effect is some args get passed
-- unlifted. See Note [WW for calling convention]
wo_unlift_strict :: !Bool }
@@ -230,8 +235,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
; let (work_args, work_marks) = unzip work_args_str
-- Do CPR w/w. See Note [Always do CPR w/w]
- ; (useful2, wrap_fn_cpr, work_fn_cpr)
- <- mkWWcpr_entry opts res_ty' res_cpr
+ ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr
; let (work_lam_args, work_call_args, work_call_str)
| needsVoidWorkerArg fun_id arg_vars work_args
@@ -662,8 +666,10 @@ canUnboxResult fam_envs ty cpr
= DontUnbox
where
- -- See Note [non-algebraic or open body type warning]
- open_body_ty_warning = warnPprTrace True "canUnboxResult: non-algebraic or open body type" (ppr ty) Nothing
+ -- See Note [Non-algebraic or open body type warning]
+ open_body_ty_warning
+ = warnPprTrace True "canUnboxResult: non-algebraic or open body type"
+ (ppr ty) Nothing
@@ -808,7 +814,7 @@ match the number of constructor arguments; this happened in #8037.
If so, the worker/wrapper split doesn't work right and we get a Core Lint
bug. The fix here is simply to decline to do w/w if that happens.
-Note [non-algebraic or open body type warning]
+Note [Non-algebraic or open body type warning]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are a few cases where the W/W transformation is told that something
returns a constructor, but the type at hand doesn't really match this. One
@@ -829,8 +835,60 @@ This warning also triggers for the stream fusion library within `text`.
We can't easily W/W constructed results like `Stream` because we have no simple
way to express existential types in the worker's type signature.
+Note [Worker/wrapper for strict arguments]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Consider
+ f x = case x of
+ [] -> blah
+ (y:ys) -> f ys
+
+Clearly `f` is strict, but its argument is not a product type, so by default
+we don't worker/wrapper it. But it is arguably valuable to do so. We could
+do this:
+
+ f x = case x of xx { DEFAULT -> $wf xx }
+ $wf xx = case xx of
+ [] -> blah
+ (y:ys) -> f ys
+
+Now the worker `$wf` knows that its argument `xx` will be evaluated
+and properly tagged, so the code for the `case xx` does not need to do
+an "eval" (see `GHC.StgToCmm.Expr.cgCase`). A call (f (a:as)) will
+have the wrapper inlined, and will drop the `case x`, so no eval
+happens at all.
+
+The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]`
+in GHC.Types.Id.Info) and the code generator guarantees that every
+call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`).
+
+Is this a win? Not always:
+* It can cause slight code size increases. This is since we push evals to every
+ call sites which there might be many. And the evals will only disappear at
+ call sites where we already known that the argument is evaluated.
+
+* It will also cause many more functions to get a worker/wrapper split
+ which can play badly with rules (see Ticket #20364). In particular
+ if you depend on rules firing on functions marked as NOINLINE
+ without marking use sites of these functions as INLINE or INLINEABLE
+ then things will break.
+
+ But if you want a function to match in a RULE, it is /in any case/ good
+ practice to have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it
+ doesn't inline until the rule has had a chance to fire.
+
+So there is a flag, `-fworker-wrapper-cbv`, to control whether we do
+w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`). The
+flag is off by default. The choice is made in
+GHC.Core.Opt.WorkWrap.Utils.wwUseForUnlifting
+
+See also `Note [WW for calling convention]`
+
Note [WW for calling convention]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ NB: This Note is more of a discussion.
+ Read Note [Worker/wrapper for strict arguments] first,
+ which covers the same ground with more precision
+
If we know a function f will always evaluate a particular argument
we might decide that it should rather get evaluated by the caller.
We call this "unlifting" the argument.
@@ -856,10 +914,9 @@ Hence we have the following strategies with different trade-offs:
A) Never do W/W *just* for unlifting of arguments.
+ Very conservative - doesn't break any rules
- - Lot's of performance left on the table
+ - Lots of performance left on the table
-B) Do W/W on just about anything where it might be
- beneficial.
+B) Do W/W on just about anything where it might be beneficial.
+ Exploits pretty much every opportunity for unlifting.
- A bit of compile time/code size cost for all the wrappers.
- Can break rules which would otherwise fire. See #20364.
@@ -883,10 +940,10 @@ C) Unlift *any* (non-boot exported) functions arguments if they are strict.
functionality. I haven't tried this approach because it's not trivial to
implement and doing W/W splits seems to work well enough.
-Currently we use the first approach A) by default, with a flag that allows users
-to fall back to the more aggressive approach B).
+Currently we use the first approach (A) by default, with a flag `-fworker-wrapper-cbv`
+that allows users to fall back to the more aggressive approach (B).
-I also tried the third approach C) using eta-expansion at call sites to avoid
+I also tried the third approach (C) using eta-expansion at call sites to avoid
modifying the PAP-handling code which wasn't fruitful. See
https://gitlab.haskell.org/ghc/ghc/-/merge_requests/5614#note_389903. We could
still try to do C) in the future by having PAP calls which will evaluate the
@@ -895,53 +952,6 @@ be neither a small nor simple change so we stick with A) and a flag for B) for
now.
See also Note [EPT enforcement] and Note [CBV Function Ids: overview]
-
-Note [Worker/wrapper for strict arguments]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Consider
- f x = case x of
- [] -> blah
- (y:ys) -> f ys
-
-Clearly `f` is strict, but its argument is not a product type, so by default
-we don't worker/wrapper it. But it is arguably valuable to do so. We could
-do this:
-
- f x = case x of xx { DEFAULT -> $wf xx }
- $wf xx = case xx of
- [] -> blah
- (y:ys) -> f ys
-
-Now the worker `$wf` knows that its argument `xx` will be evaluated
-and properly tagged, so the code for the `case xx` does not need to do
-an "eval" (see `GHC.StgToCmm.Expr.cgCase`). A call (f (a:as)) will
-have the wrapper inlined, and will drop the `case x`, so no eval
-happens at all.
-
-The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]`
-in GHC.Types.Id.Info) and the code generator guarantees that every
-call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`).
-
-Is this a win? Not always:
-* It can cause slight codesize increases. This is since we push evals to every
- call sites which there might be many. And the evals will only disappear at
- call sites where we already known that the argument is evaluated.
-
-* It will also cause many more functions to get a worker/wrapper split
- which can play badly with rules (see Ticket #20364). In particular
- if you depend on rules firing on functions marked as NOINLINE
- without marking use sites of these functions as INLINE or INLINEABLE
- then things will break.
- But if you want a function to match in a RULE, it is /in any case/ good practice to
- have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it doesn't inline until
- the rule has had a chance to fire.
-
-So there is a flag, `-fworker-wrapper-cbv`, to control whether we do
-w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`). The
-flag is off by default. The choice is made in
-GHC.Core.Opt.WorkWrape.Utils.wwUseForUnlifting
-
-See also `Note [WW for calling convention]` in GHC.Core.Opt.WorkWrap.Utils
-}
{-
@@ -985,6 +995,12 @@ mkWWstr opts args str_marks
-- * wrap_arg assumes work_args are in scope, and builds a ConApp that
-- reconstructs the RHS of wrap_var that we pass to the original RHS
-- See Note [Worker/wrapper for Strictness and Absence]
+--
+-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int
+-- = ( True -- useful
+-- , [p,q#], -- work_args
+-- , \e -> case x of (p,q) -> case q of I# q# -> e -- wrap_fn
+-- , (p, I# q) ) -- wrap_arg
mkWWstr_one :: WwOpts
-> Var
-> StrictnessMark
@@ -1008,7 +1024,7 @@ mkWWstr_one opts arg str_mark =
DontUnbox
| isStrictDmd arg_dmd || isMarkedStrict str_mark
- , wwUseForUnlifting opts -- See Note [WW for calling convention]
+ , wwUseForUnlifting opts -- See Note [Worker/wrapper for strict arguments]
, not (isFunTy arg_ty)
, not (isUnliftedType arg_ty) -- Already unlifted!
-- NB: function arguments have a fixed RuntimeRep,
@@ -1163,7 +1179,7 @@ function is worthy for splitting:
2b But if e.g. a large tuple or product type is always demanded we might
decide to "unlift" it. That is tighten the calling convention for that
argument to require it to be passed as a pointer to the value itself.
- See Note [WW for calling convention].
+ See Note [Worker/wrapper for strict arguments]
3. In all other cases (e.g., lazy, used demand and not eval'd),
'finaliseArgBoxities' will have cleared the Boxity flag to 'Boxed'
@@ -1604,7 +1620,9 @@ mkWWcpr_entry
CoreExpr -> CoreExpr) -- New worker. 'nop_fn' if not useful
-- ^ Entrypoint to CPR W/W. See Note [Worker/wrapper for CPR] for an overview.
mkWWcpr_entry opts body_ty body_cpr
- | not (wo_cpr_anal opts) = return (boringSplit, nop_fn, nop_fn)
+ | not (wo_cpr_anal opts) -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
+ = return (boringSplit, nop_fn, nop_fn)
+
| otherwise = do
-- Part (1)
res_bndr <- mk_res_bndr body_ty
@@ -1637,7 +1655,9 @@ mk_res_bndr body_ty = do
-- 1. A 'WwUse' capturing whether the split does anything useful.
-- 2. The list of transit variables (see the Note).
-- 3. The result builder expression for the wrapper. The original case binder if not useful.
--- 4. The result unpacking expression for the worker. 'nop_fn' if not useful.
+-- Assumes that the transit vars are in scope
+-- 4. The result unpacking expression for the worker. 'nop_fn' if not useful
+-- Brings the transit vars into scope
type CprWwResultOne = (WwUse, OrdList Var, CoreExpr , CoreExpr -> CoreExpr)
type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr)
@@ -1768,7 +1788,7 @@ To achieve said transformation, 'mkWWcpr_entry'
what belongs in the case scrutinee of the unpacker through the communicated
Id `r`: The unpacking expression will be free in that variable.
(This is a similar contract as that of 'mkWWstr_one' for strict args.)
- 3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables
+ 3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables
that have to be transferred from the worker to the wrapper, where the
constructed result can be rebuilt, `a` and `b` above. Part (3) is
responsible for tupling them up in the worker and taking the tuple apart
=====================================
compiler/GHC/HsToCore/Utils.hs
=====================================
@@ -147,8 +147,7 @@ selectMatchVar w pat = go pat
go_leaf var
| not (hasRulesOrInline (idInfo var))
- = assert (isManyTy w) $
- return (mkLamBndrFromLetBndr var)
+ = return (mkLamBndrFromLetBndr var)
| otherwise
= new_match_var (idType var)
=====================================
compiler/GHC/Types/Cpr.hs
=====================================
@@ -8,6 +8,7 @@
module GHC.Types.Cpr (
Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr,
CprType (..), topCprType, botCprType, flatConCprType,
+ cprTypeArity, cprTypeCpr,
lubCprType, applyCprTy, abstractCprTy, trimCprTy,
UnpackConFieldsResult (..), unpackConFieldsCpr,
CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig,
@@ -106,6 +107,12 @@ data CprType
-- 'ct_arty' arguments
}
+cprTypeArity :: CprType -> Arity
+cprTypeArity = ct_arty
+
+cprTypeCpr :: CprType -> Cpr
+cprTypeCpr = ct_cpr
+
instance Eq CprType where
a == b = ct_cpr a == ct_cpr b
&& (ct_arty a == ct_arty b || ct_cpr a == topCpr)
@@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr
-- | The arity of the wrapped 'CprType' is the arity at which it is safe
-- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand"
-newtype CprSig = CprSig { getCprSig :: CprType }
+newtype CprSig = CprSig { cprSigType :: CprType }
deriving (Eq, Binary)
-- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig'
=====================================
compiler/GHC/Types/Id/Info.hs
=====================================
@@ -32,7 +32,7 @@ module GHC.Types.Id.Info (
setOneShotInfo,
-- ** Zapping various forms of Info
- zapLamInfo, zapFragileInfo,
+ zapLamInfo, zapFragileInfo, hasRulesOrInline,
lazifyDemandInfo, floatifyDemandInfo,
zapUsageInfo, zapUsageEnvInfo, zapUsedOnceInfo,
zapTailCallInfo, zapCallArityInfo, trimUnfolding,
@@ -963,3 +963,10 @@ zapTailCallInfo info
zapCallArityInfo :: IdInfo -> IdInfo
zapCallArityInfo info = setCallArityInfo info 0
+
+hasRulesOrInline :: IdInfo -> Bool
+-- See (SB3) of Note [StrictBind]
+hasRulesOrInline info
+ = isStableUnfolding (unfoldingInfo info)
+ || not (isEmptyRuleInfo (ruleInfo info))
+ || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
=====================================
compiler/GHC/Utils/Monad.hs
=====================================
@@ -16,7 +16,7 @@ module GHC.Utils.Monad
, mapAccumLM
, mapSndM
, concatMapM
- , mapMaybeM
+ , mapMaybeM, orElseM
, anyM, allM, orM
, foldlM, foldlM_, foldrM, foldMapM
, whenM, unlessM
@@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = do { cond <- condM
; unless cond acc }
+-- | Monadic version of @orElse@
+infixr 4 `orElseM`
+orElseM :: Monad m => m (Maybe a) -> m a -> m a
+orElseM ma def = do { mb_r <- ma
+ ; case mb_r of
+ Just x -> return x
+ Nothing -> def }
+
-- | Like 'filterM', only it reverses the sense of the test.
filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterOutM p =
=====================================
testsuite/tests/simplCore/should_compile/T28158.hs
=====================================
@@ -0,0 +1,22 @@
+{-# OPTIONS_GHC -fworker-wrapper-cbv #-}
+-- Adding this option makes things harder for splitThunkCpr, which
+-- this test is testing. See (TS8) in Note [Thunk splitting]
+
+module T28158 where
+
+-- Here we miss CPR on y
+-- It's a bit of an obscure example, but still; see #28158
+f :: a -> a -> a -> [Int] -> [Int]
+f a b c xs = let y = case xs of
+ [0] -> Just a
+ [1] -> Just b
+ _ -> Just c
+ in h y (case y of
+ Just z -> reverse (reverse (reverse (
+ reverse (reverse (reverse (
+ reverse (reverse xs)))))))
+ Nothing -> xs++xs)
+
+h :: Maybe a -> b -> b
+h (Just y) e = h Nothing e
+h Nothing e = e
=====================================
testsuite/tests/simplCore/should_compile/T28158.stderr
=====================================
@@ -0,0 +1,58 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 98, types: 108, coercions: 0, joins: 1/1}
+
+Rec {
+$wh
+ = \ @a @b ds e ->
+ case ds of ds1 { __DEFAULT ->
+ case e of e1 { __DEFAULT ->
+ case ds1 of {
+ Nothing -> e1;
+ Just y -> $wh Nothing e1
+ }
+ }
+ }
+end Rec }
+
+h = \ @a @b ds e -> $wh ds e
+
+$wf
+ = \ @a a1 b c xs ->
+ join {
+ $j ww
+ = $wh
+ (Just ww)
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1 (reverse1 (reverse1 (reverse1 xs []) []) []) []) [])
+ [])
+ [])
+ []) } in
+ case xs of {
+ [] -> jump $j c;
+ : ds ds1 ->
+ case ds of { I# ds2 ->
+ case ds2 of {
+ __DEFAULT -> jump $j c;
+ 0# ->
+ case ds1 of {
+ [] -> jump $j a1;
+ : ipv ipv1 -> jump $j c
+ };
+ 1# ->
+ case ds1 of {
+ [] -> jump $j b;
+ : ipv ipv1 -> jump $j c
+ }
+ }
+ }
+ }
+
+f = \ @a a1 b c xs -> $wf a1 b c xs
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -637,5 +637,5 @@ test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
test('T27965', normal, compile, ['-O'])
test('T27965a', normal, compile, ['-O'])
test('T27965b', normal, compile, ['-O'])
-
+test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/694da176149247fc98666f26a632293…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/694da176149247fc98666f26a632293…
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/sjakobi/T28190-js-th-tests-alone
by Simon Jakobi (@sjakobi) 26 Nov '26
by Simon Jakobi (@sjakobi) 26 Nov '26
26 Nov '26
Simon Jakobi pushed new branch wip/sjakobi/T28190-js-th-tests-alone at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/sjakobi/T28190-js-th-tests-al…
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/davide/fix_tests_over_io_managers] 2 commits: testsuite: fix framework failure on window for tests using all_available_io_managers_except()
by David Eichmann (@DavidEichmann) 26 Nov '26
by David Eichmann (@DavidEichmann) 26 Nov '26
26 Nov '26
David Eichmann pushed to branch wip/davide/fix_tests_over_io_managers at Glasgow Haskell Compiler / GHC
Commits:
272565f4 by David Eichmann at 2026-11-26T11:50:33+00:00
testsuite: fix framework failure on window for tests using all_available_io_managers_except()
- - - - -
a936120d by David Eichmann at 2026-11-26T12:09:57+00:00
testsuite: use `all_available_io_managers` for various tests
Affected tests:
* T10590
* T21969
* T21969a
* T21969b
* T21969c
* T21969d
* T21969e
* T21969f
- - - - -
3 changed files:
- testsuite/driver/testutil.py
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/rts/all.T
Changes:
=====================================
testsuite/driver/testutil.py
=====================================
@@ -184,8 +184,10 @@ def shorten_metric_name(name: str) -> str:
# I/O manager discovery for a haskell binary. Returns the set of IO Manager
# strings supported by the binary
def discover_io_managers(hs_exe: Union[str, Path], cwd: Union[str, Path]) -> Set[str]:
+ # We must use an absolute path for the executable. Relative paths break on windows.
+ hs_exe_path = Path(cwd).joinpath(hs_exe)
rp = subprocess.run(
- [str(hs_exe), '+RTS', '--info', '-RTS'],
+ [hs_exe_path, '+RTS', '--info', '-RTS'],
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
=====================================
testsuite/tests/concurrent/should_run/all.T
=====================================
@@ -271,7 +271,8 @@ test('T21969',
extra_run_opts('50000'),
run_timeout_multiplier(0.3), # default timeout seems to be 300, but lockups happen quickly
req_target_smp,
- req_ghc_smp
+ req_ghc_smp,
+ all_available_io_managers,
],
compile_and_run, [''])
@@ -289,24 +290,28 @@ test('T21969',
test('T21969a',
[ only_ways(['threaded1','threaded2', 'nonmoving_thr', 'profthreaded']),
when(opsys('mingw32'),skip), # POSIX only
+ all_available_io_managers,
],
compile_and_run, [''])
test('T21969b',
[ only_ways(['threaded1','threaded2', 'nonmoving_thr', 'profthreaded']),
when(opsys('mingw32'),skip), # POSIX only
+ all_available_io_managers,
],
compile_and_run, [''])
test('T21969c',
[ only_ways(['threaded1','threaded2', 'nonmoving_thr', 'profthreaded']),
when(opsys('mingw32'),skip), # POSIX only
+ all_available_io_managers,
],
compile_and_run, [''])
test('T21969d',
[ only_ways(['threaded1','threaded2', 'nonmoving_thr', 'profthreaded']),
when(opsys('mingw32'),skip), # POSIX only
+ all_available_io_managers,
],
compile_and_run, [''])
@@ -314,12 +319,14 @@ test('T21969e',
[ only_ways(['threaded1','threaded2', 'nonmoving_thr', 'profthreaded']),
when(opsys('mingw32'),skip), # POSIX only
run_timeout_multiplier(0.3),
+ all_available_io_managers,
],
compile_and_run, [''])
test('T21969f',
[ only_ways(['threaded1','threaded2', 'nonmoving_thr', 'profthreaded']),
when(opsys('mingw32'),skip), # POSIX only
+ all_available_io_managers,
],
compile_and_run, [''])
=====================================
testsuite/tests/rts/all.T
=====================================
@@ -408,6 +408,7 @@ test('T10590', [ ignore_stderr
, when(opsys('mingw32'), skip)
, js_skip # JS backend doesn't support pipes
, req_process
+ , all_available_io_managers
], compile_and_run, [''])
# Run with stdin and stdout closed -- that is what leaves those descriptors
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/a0424fca10ad0f2333369de84b71aa…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/a0424fca10ad0f2333369de84b71aa…
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] 23 commits: CoreMap: look up a non-recursive let with the key order of the store
by Rodrigo Mesquita (@alt-romes) 26 Nov '26
by Rodrigo Mesquita (@alt-romes) 26 Nov '26
26 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
- - - - -
8fa152ed by Rodrigo Mesquita at 2026-11-26T11:13:26+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
- - - - -
206 changed files:
- .gitlab-ci.yml
- + 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/3d92ebe4b1bdfcbc09f382d951a423…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3d92ebe4b1bdfcbc09f382d951a423…
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/T28171] rts/nonmoving: fix wakeBlockingQueue missing update remembered set push
by Teo Camarasu (@teo) 26 Nov '26
by Teo Camarasu (@teo) 26 Nov '26
26 Nov '26
Teo Camarasu pushed to branch wip/T28171 at Glasgow Haskell Compiler / GHC
Commits:
c9ac9ddb by Teo Camarasu at 2026-11-26T10:38:37+00:00
rts/nonmoving: fix wakeBlockingQueue missing update remembered set push
When we wake up a blocking queue, we replace the blocking queue with an
indirection.
An indirection has fewer fields than a blocking queue, so we are, in
essence, overwriting some fields with NULL. Thus they need to be pushed
to the update remembered set.
The test shows that this is observable. We can have a situation where a
thread is ONLY being kept alive by being on a blocking queue. If the
nonmoving mark can't see it there then it will be GC'd overly eagerly
and we will get a NonTermination exception when it gets cleaned up.
We also push the other fields to the update remembered set to enforce
the invariant, but I'm not sure if those will ever cause issues in the
same way.
Resolves #28171
- - - - -
5 changed files:
- + changelog.d/T28171
- rts/Threads.c
- + testsuite/tests/rts/T28171.hs
- + testsuite/tests/rts/T28171.stdout
- testsuite/tests/rts/all.T
Changes:
=====================================
changelog.d/T28171
=====================================
@@ -0,0 +1,8 @@
+section: rts
+synopsis: Fix the nonmoving GC sending spurious NonTermination exceptions
+description:
+ We fix the nonmoving GC's logic for waking up threads blocked on a thunk, which had
+ a bug leading to threads being falsely being GC'd too soon.
+ This could lead to spurious NonTermination exceptions.
+mrs: !17050
+issues: #28171
=====================================
rts/Threads.c
=====================================
@@ -440,9 +440,19 @@ wakeBlockingQueue(Capability *cap, StgBlockingQueue *bq)
if (i != &stg_IND_info) {
ASSERT(i == &stg_MSG_BLACKHOLE_info);
tryWakeupThread(cap,msg->tso);
+
}
}
+ // Changing the closure type to IND makes these fields inaccessible,
+ // so we need to push them to the update remembered set.
+ // See Note [Update remembered set] in rts/sm/NonMovingMark.c
+ IF_NONMOVING_WRITE_BARRIER_ENABLED {
+ updateRemembSetPushClosure(cap, (StgClosure *) bq->bh);
+ updateRemembSetPushClosure(cap, (StgClosure *) bq->owner);
+ updateRemembSetPushClosure(cap, (StgClosure *) bq->queue);
+ }
+
// overwrite the BQ with an indirection so it will be
// collected at the next GC.
OVERWRITE_INFO(bq, &stg_IND_info);
=====================================
testsuite/tests/rts/T28171.hs
=====================================
@@ -0,0 +1,32 @@
+import Control.Concurrent
+import Control.Concurrent.MVar
+import Control.Exception
+import Control.Monad
+import System.Mem
+import System.IO.Unsafe
+
+main :: IO ()
+main = do
+ forM_ [1 .. 1000] $ \r -> do
+ -- Create a thunk that will never finish evaluating
+ let t = unsafePerformIO (threadDelay (100000000000 + r))
+ -- Begin nonmoving GC
+ performMajorGC
+ performMajorGC
+ x <- newEmptyMVar
+ y <- newEmptyMVar
+ -- we start evaluating it on two threads in parallel
+ k <- forkIO (putMVar x () >> void (evaluate t))
+ performMajorGC
+ -- The second thread gets added to the waking queue
+ _ <- forkIO (putMVar y () >> void (evaluate t))
+ takeMVar x
+ takeMVar y
+ -- We kill the original thread.
+ -- And now wake up the other threads.
+ -- We need to ensure that the nonmoving GC can see that thread.
+ -- Otherwise we will get a NonTermination exception
+ killThread k
+ performMajorGC
+ performMajorGC
+ putStrLn "done"
=====================================
testsuite/tests/rts/T28171.stdout
=====================================
@@ -0,0 +1 @@
+done
=====================================
testsuite/tests/rts/all.T
=====================================
@@ -807,3 +807,9 @@ test('T27376',
only_ways(['nonmoving_thr', 'nonmoving_thr_sanity']),
extra_run_opts('+RTS -A2m -RTS') ],
compile_and_run, ['-O2'])
+
+test('T28171',
+ [ req_target_smp,
+ extra_ways(['nonmoving_thr', 'nonmoving_thr_sanity']),
+ only_ways(['nonmoving_thr', 'nonmoving_thr_sanity'])],
+ compile_and_run, [''])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/c9ac9ddb655b3146dff9ec86873e07d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/c9ac9ddb655b3146dff9ec86873e07d…
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/dcoutts/posix-cond-vars] 36 commits: NCG: List each destination of a jump table once
by Duncan Coutts (@dcoutts) 26 Nov '26
by Duncan Coutts (@dcoutts) 26 Nov '26
26 Nov '26
Duncan Coutts pushed to branch wip/dcoutts/posix-cond-vars at Glasgow Haskell Compiler / GHC
Commits:
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.
- - - - -
6c648418 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Make clock_gettime required on posix platforms
It was defined in POSIX.1-2001 and has been manditory since
POSIX.1-2008. We will rely on CLOCK_MONOTONIC for the RTS-internal
monotonic time source.
On macOS it has been available since 10.12 released in 2016 (and EOL
2019). We already have 11.0 as our minimum version for which we build
binaries (MACOSX_DEPLOYMENT_TARGET=11.0).
Also we must now drop the workaround from #12858 that would make the CI
configuration invoke configure in a way that would always fail to detect
clock_gettime (since obviously now we must detect it). Re-generate the
gitlab jobs files for the benefit of CI.
- - - - -
15089ab3 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Simplify time code based on assuming defined(HAVE_CLOCK_GETTIME)
No need to fall back to gettimeofday or times
- - - - -
3af0e05e by Duncan Coutts at 2026-11-26T09:34:03+00:00
Use clock_gettime CLOCK_REALTIME for getUnixEpochTime
- - - - -
e7a633c4 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Simplify getCurrentThreadCPUTime to use clock_gettime
except on Solaris where it doesn't work.
In particular, this means we now use it on macOS. It apparently works
there from 10.12 onwards.
We drop the check for clock_getcpuclockid which is linux-specific,
archaic, and in any case isn't necessarily fatal.
- - - - -
fadaf01a by Duncan Coutts at 2026-11-26T09:34:03+00:00
Remove now-redundant darwin time code
- - - - -
59b3e667 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Simplify getProcessCPUTime to use clock_gettime CLOCK_PROCESS_CPUTIME_ID
It would be nice to check during startup using sysconf that this is
really available. Unfortunately this doesn't actually work on macOS: it
reports via sysconf that it is not available, when actually it is.
Great.
- - - - -
4a29464f by Duncan Coutts at 2026-11-26T09:34:03+00:00
Tidy up posix time headers in various places
Also remove the definition of CLOCK_ID in HsBase.h, where CLOCK_ID does
not appear to be used at all. And we're going to tweak the clock
definitions soon so we don't want these parallel definitions getting
out of sync.
- - - - -
85f219c7 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Split getPageFaults out into OSStats.{h,c}
Strictly speaking it never had any business living with the time
functions. It was merely convenience. Moving it out allows the remainder
to use PosixSource.h (at least on posix).
- - - - -
ed86f8a2 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Move getProcessTimes to its only use site
Historically getProcessTimes made sense, since the main way to get the
elapsed time would also get the cpu time as well. After recent time code
simplification on posix then in all platforms it is just the pair of
getProcessCPUTime and getProcessElapsedTime separarely. So we can remove
three identical implementations and move it to be a local function in
Stats.c where it is used.
- - - - -
c90c7905 by Duncan Coutts at 2026-11-26T09:34:03+00:00
Make the "get the time" functions more consistent
We had:
Time getProcessElapsedTime(void); // pulbic
StgWord64 getMonotonicNSec(void); // public
void getUnixEpochTime(StgWord64 *sec, StgWord32 *nsec); // internal
These don't follow any naming convention, nor any common type
convention.
Now we have:
Time getMonotonicTime(void); // internal
Time getWallClockTime(void); // internal
StgWord64 getMonotonicNSec(void); // public compat alias
Time getProcessElapsedTime(void); // public compat alias
Now the two main ones use a common representation: Time which is int64_t
nanoseconds since the epoch. And their names better reflect that they
use different clocks: a monotonic clock, or a real time / wall clock.
We keep getMonotonicNSec and getProcessElapsedTime as aliases for
getMonotonicTime(). They are still used in ghc-internal.
Future directions: export the new ones from ghc-internal and base, and
provide clock precision functions. Provide more clocks, like coarse
ones: faster but less precise.
- - - - -
cd5ded58 by Duncan Coutts at 2026-11-26T09:40:00+00:00
Improve win32 implementation of getMonotonicNSec
We don't need the fallback GetTickCount method.
Fixes #14233
- - - - -
6398ae00 by Duncan Coutts at 2026-11-26T09:40:00+00:00
Improve win32 implementation of getUnixEpochTime
We can now use GetSystemTimePreciseAsFileTime, which is supported from
Windows 8 onwards. This is the recommendation from MS.
- - - - -
0372f600 by Duncan Coutts at 2026-11-26T09:40:00+00:00
Remove initializeTimer
It is now a no-op on all platforms.
- - - - -
11181865 by Duncan Coutts at 2026-11-26T09:40:00+00:00
Refine the meaning of the main monotonic clock and add a high-res clock
We now define the monotonic clock to prioritise accuracy, and to be
steady: which implies it must count time while the system is suspended.
In particular this means that on Linux we must use CLOCK_BOOTTIME.
Since different use cases want different trade-offs (where such
trade-offs are necessary on some platforms) we also add support for a
high resolution clock. This is defined to be as precise as possible, but
not necessarily steady or accurate over long timer periods. This is the
appropriate choice for measuring the time of short-running actions. We
don't get use this one, but will do in susbequent changes.
- - - - -
23cc892e by Duncan Coutts at 2026-11-26T09:40:00+00:00
Switch some RTS uses from getMonotonicTime to getHighResolutionTime
Wherever we want to measure the duration of relatively short time
intervals then we want getHighResolutionTime rather than
getMonotonicTime. In particular this is appropriate for RTS stats,
profiling and the eventlog timestamps.
In practice this is hardly a change in behaviour compared to the prior
implementation of getMonotonicNSec/getProcessElapsedTime. On Linux and
FreeBSD it used CLOCK_MONOTONIC, and still does (or the more-or-less
equivalent CLOCK_BOOTTIME on Linux). On macOS it used the low-level
mach_absolute_time and now uses the equivalent CLOCK_UPTIME_RAW for
getHighResolutionTime. While on Windows getHighResolutionTime uses
QueryPerformanceCounter, the same as previously.
- - - - -
979bb3a4 by Duncan Coutts at 2026-11-26T09:40:00+00:00
Add support for macOS non-standard clock_gettime_nsec_np
It's a way to get what we want with fewer conversions, so plausibly
faster.
- - - - -
f9f1227d by Duncan Coutts at 2026-11-26T09:40:00+00:00
Remove unused rtsSleep utility
- - - - -
01ca4f22 by Duncan Coutts at 2026-11-26T09:40:00+00:00
Add a changelog entry for the clock_gettime changes
- - - - -
b17be13d by Duncan Coutts at 2026-11-26T09:42:11+00:00
Rename timedWaitCondition to waitConditionTimedRelative
We will add an absolute variant, at least for posix.
- - - - -
26b28309 by Duncan Coutts at 2026-11-26T09:42:11+00:00
Improve waitConditionTimedRelative
We really want to use the monotonic clock, to avoid discontinuities due
to the real time clock, but support for the monotonic clock for cond var
timed waits is patchy. There are newer posix functions that provide it,
but many platforms don't support these yet and have some of their own
non-standard extensions.
Furthermore, the existing timed wait code is pretty unpleasent: it uses
both a static and a dynamic test to try to use a monotonic clock, but if
either test fails then it falls back to a realtime clock. This is ok ish
for implementing relative timeouts, but we will also want to support
absolute timeouts (in the monotonic clock). Fortunately the static test
can go because we now require clock_gettime unconditionally. The dynamic
test is weird: it presumes the existence of platforms supporting
pthread_condattr_setclock but not supporting CLOCK_MONOTONIC. There do
not appear to be any such platforms (which is unsurprising since
clock_gettime predates pthread_condattr_setclock).
- - - - -
07583214 by Duncan Coutts at 2026-11-26T09:42:11+00:00
Add waitConditionTimedAbsolute for posix platforms
We add support for a waitConditionTimedAbsolute using an absolute
timeout using the monotonic clock. This will be useful later for
flexible timers, where the timeout is most naturally expressed as an
absolute (monotonic) time.
We don't currently provide this for Win32 because we do not need it for
flexible timers there: win32 uses a different timer implementation
entirely.
If more portable use cases arise, we could provide this on win32 but it
would have to do some time conversions to implement it in terms of a
relative-time timed wait (with only millisecond precision).
- - - - -
0f246338 by Duncan Coutts at 2026-11-26T09:42:11+00:00
Remove wrong initialiser INIT_COND_VAR, and add MUTEX_STATIC_INIT
INIT_COND_VAR was a static initialiser for condition variables. It had a
bogus implementation on Windows (though it could have a correct one,
namely CONDITION_VARIABLE_INIT). On posix, although
PTHREAD_COND_INITIALIZER exists, our own Condition abstraction relies
sometimes on setting attributes, which cannot be done statically (in a
portable way).
INIT_COND_VAR was also unused, so removing it is easy.
Add MUTEX_STATIC_INIT which is a (hopefully) correct portable static
initialiser for mutexes. This is convenient to avoid initSubsystemFoo
calls that do nothing but initialise mutexes.
- - - - -
155 changed files:
- .gitlab-ci.yml
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/jobs.yaml
- + changelog.d/27694
- + changelog.d/T27137
- + changelog.d/T27637
- + changelog.d/T27862
- + changelog.d/T28135
- + changelog.d/clock_gettime
- + changelog.d/make-depends-link-nodes
- 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/Driver/Downsweep.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeFile.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/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/TyCl.hs
- + distrib/configure.ac
- docs/users_guide/make-depends-json-schema-1_0.json
- libraries/ghc-internal/include/HsBase.h
- m4/fp_check_pthreads.m4
- + rts/GetTime.c
- rts/GetTime.h
- + rts/OSStats.h
- rts/RtsStartup.c
- rts/RtsUtils.c
- rts/Stats.c
- rts/StgCRun.c
- rts/configure.ac
- rts/eventlog/EventLog.c
- rts/include/rts/GetTime.h
- rts/include/rts/OSThreads.h
- rts/include/rts/Time.h
- rts/posix/Clock.h
- rts/posix/GetTime.c
- + rts/posix/OSStats.c
- rts/posix/OSThreads.c
- + rts/posix/OSThreads.h
- rts/posix/Poll.c
- rts/posix/Select.c
- rts/posix/SelectBis.c
- rts/posix/Ticker.c
- rts/posix/Timeout.c
- rts/rts.cabal
- rts/sm/GC.c
- rts/wasm/GetTime.c
- + rts/wasm/OSStats.c
- rts/win32/GetTime.c
- + rts/win32/OSStats.c
- rts/win32/OSThreads.c
- 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/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_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/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/printer/T18791.stderr
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/rts/IOManager.hsc
- testsuite/tests/rts/TimeoutQueue.c
- testsuite/tests/rts/all.T
- testsuite/tests/rts/symbols/rts-check-symbols.stdout
- + 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
- 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/ba943922650eb4a2c1122a96158ef9…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ba943922650eb4a2c1122a96158ef9…
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