Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC Commits: bfe578d6 by Simon Peyton Jones at 2026-11-20T23:38:35+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 #28258) 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. - - - - - 9 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/Types/Cpr.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 ===================================== @@ -343,7 +343,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 +362,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 +870,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,10 @@ useStrictBind env from_what bndr | not (isStrUsedDmd dmd_info) = False + -- Not if the RHS is ok-for-spec; no benefit + | exprOkForSpeculation rhs + = False + -- Not if case-of-case is off -- See (SB1) in Note [StrictBind] | not (seCaseCase env) @@ -1894,8 +1896,6 @@ useStrictBind env from_what bndr | isStableUnfolding (unfoldingInfo info) || not (isEmptyRuleInfo (ruleInfo info)) || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info))) - || not (isNopSig (dmdSigInfo info)) - || not (isTopCprSig (cprSigInfo info)) = False | otherwise @@ -4243,9 +4243,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 +4315,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 +4454,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 +4654,43 @@ 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. + + 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,19 @@ 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 + = 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 +619,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 +811,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 +962,165 @@ 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) } + Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function + argument w/w splitting function, to do the unpacking. This automatically + deals with nested strictness. + +(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again + using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks. + +Wrinkles: + +(TS3) Here's an example of (B), thunk-splitting based on CPR information, in action. + 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). -* 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. + 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 -* 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. + 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). -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'. +(TS4) We only do thunk-splitting for thunks that are non-recursive + 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. + +(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`. -} --- | 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 + = do { let x' = localiseId x -- See (TS7) + ; (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 + | 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 @@ -230,8 +230,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 @@ -985,6 +984,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 @@ -1637,7 +1642,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 +1775,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/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/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,18 @@ +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,47 @@ + +==================== Tidy Core ==================== +Result size of Tidy Core + = {terms: 72, types: 76, coercions: 0, joins: 1/1} + +Rec { +h = \ @a @b ds e -> + case ds of { + Nothing -> e; + Just y -> h Nothing e + } +end Rec } + +f = \ @a a1 b c xs -> + join { + $j ww + = h (Just ww) + (reverse1 + (reverse1 + (reverse1 + (reverse1 + (reverse1 (reverse1 (reverse1 (reverse 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 + } + } + } + } + + + ===================================== testsuite/tests/simplCore/should_compile/all.T ===================================== @@ -636,3 +636,4 @@ test('T27962a', [extra_files(['T27962.hs'])], multimod_compile, ['T27962', '-v0 test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings']) test('T27965', normal, compile, ['-O']) test('T27965a', 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/bfe578d65058267134b03d49263c43d4... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/bfe578d65058267134b03d49263c43d4... 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