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@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/750032e34ac16192323604eed84a1b6c... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/750032e34ac16192323604eed84a1b6c... 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