Simon Peyton Jones pushed to branch wip/T27212 at Glasgow Haskell Compiler / GHC Commits: d2b9078f by Simon Peyton Jones at 2026-11-20T23:14:07+00:00 Document and refactor eta-reduction documentation Triggered by #27212, this patch does several related things. * #27212 suggested that `findRhsArity` should ask for eta-expansion whenever the RHS's `manifestArity` is less than the arity it finds. That is a misconception: it deliberately compares with `exprArity`, which counts PAPs, so that we do not eta-expand PAPs (#9020). Switching to `manifestArity` makes compile time worse in T13960 and T13056. So this patch changes no code here; we continue to expand only to increase `exprArity` not `manifestArity`. Instead it documents the design in `findRhsArity`, `tryEtaExpandRhs`, `wantEtaExpansion` and Note [Do not eta-expand PAPs] (which now records the #27212 experiment). * Refactor GHC.Core.Opt.Arity.tryEtaReduce, which was hard to understand: - Accumulate an MCoercion rather than a Coercion, so the common no-cast case builds no coercions at all. - Separate equations of `go` for type and value arguments. For value arguments, the new `getTrivialHead_maybe` looks through any nesting of casts and floatable ticks, and `mkEtaReduceFunCo` builds the coercion. - Make the FunCo with `mkFunCo2` and compute its right-hand FunTyFlag from the coercion kinds. The cast can turn a Type-kinded argument into a Constraint-kinded one. New test T27212 covers this. - `mkEtaReduceForAllMCo` builds the ForAllCo for type arguments. It is tiresomely similar to `mkEtaForAllMCo`, but with the visibilities the other way round (#24014). It will go away again once !17006 lands. - New helper `mCoToCo` in GHC.Core.TyCo.Make. * Drop the checks on multiplicity in `tryEtaReduce`, which sometimes disabled eta-reduction. For example, (\x. K x) has type Int -> T, but the data constructor has type K :: Int %1 -> T, so we used to refuse to eta-reduce it to K. But Note [Linting linearity] in GHC.Core.Lint (EXAMPLE 4) already says that we do not preserve linearity under eta-reduction, so this change just puts that claim into practice. See (EtaMult) in Note [Eta reduction soundness]. Consequences in the testsuite: - T18052a: the pattern-synonym builder (\x y. (x,y)) is now just (,). - T21888a: the NOINLINE function (f x = Just x) becomes (f = Just), so f loses its CPR signature. The test is about demands, not CPR. * Tidy up the documentation of eta-reduction: - Relabel the criteria in Note [Eta reduction soundness] as (EtaA), (EtaS), (EtaR), (EtaE), (EtaT), (EtaJ), (EtaB) and (EtaW), and update all references to them. Also fix references to point (2) of Note [Eta reduction makes sense], which no longer exists. - Replace the confused "never reduce arity" bullet with an example in (EtaA), cross-referenced from Note [Arity robustness]. - Add historical notes (EtaMult) and (EtaBot). - Label the equations in Note [Eta reduction with casted arguments] (ECA1-4), and point to the code that implements them. LLM disclosure: I interacted with Claude a lot for this MR, but I wrote all the code and docs myself. - - - - - 13 changed files: - compiler/GHC/Core/Coercion.hs - compiler/GHC/Core/Opt/Arity.hs - compiler/GHC/Core/Opt/OccurAnal.hs - compiler/GHC/Core/Opt/Simplify/Env.hs - compiler/GHC/Core/Opt/Simplify/Iteration.hs - compiler/GHC/Core/Opt/Simplify/Utils.hs - compiler/GHC/Core/TyCo/Make.hs - compiler/GHC/Core/Type.hs - compiler/GHC/Core/Utils.hs - testsuite/tests/dmdanal/sigs/T21888a.stderr - testsuite/tests/printer/T18052a.stderr - + testsuite/tests/simplCore/should_compile/T27212.hs - testsuite/tests/simplCore/should_compile/all.T Changes: ===================================== compiler/GHC/Core/Coercion.hs ===================================== @@ -74,7 +74,7 @@ module GHC.Core.Coercion ( isReflCoVar_maybe, assertGoodForAllCo, - coToMCo, kindCoToMKindCo, + coToMCo, kindCoToMKindCo, mCoToCo, mkTransMCo, mkTransMCoL, mkTransMCoR, mkCastTyMCo, mkSymMCo, mkFunResMCo, mkPiMCos, isReflMCo, checkReflexiveMCo, ===================================== compiler/GHC/Core/Opt/Arity.hs ===================================== @@ -886,8 +886,14 @@ findRhsArity :: ArityOpts -> RecFlag -> Id -> CoreExpr -- This implements the fixpoint loop for arity analysis -- See Note [Arity analysis] -- --- The Bool is True if the returned arity is greater than (exprArity rhs) --- so the caller should do eta-expansion +-- The Bool is True if +-- the returned arity is greater than (exprArity rhs) +-- so the caller should do eta-expansion +-- NB: `exprArity`, not `manifestArity`: +-- a PAP such as (\x. f x), where f has arity 3, has exprArity 3, +-- so we do not eta-expand it to (\x y z. f x y z) +-- See Note [Do not eta-expand PAPs] in GHC.Core.Opt.Simplify.Utils +-- -- That Bool is never True for join points, which are never eta-expanded -- -- Returns an SafeArityType that is guaranteed trimmed to typeArity of 'bndr' @@ -903,10 +909,11 @@ findRhsArity opts is_rec bndr rhs | otherwise = (arity_increased, non_join_arity_type) - -- arity_increased: eta-expand if we'll get more lambdas - -- to the top of the RHS + -- arity_increased: eta-expand if the analysis finds a greater arity + -- than exprArity, which already takes account of PAPs where - old_arity = exprArity rhs + old_arity = exprArity rhs -- See Note [Do not eta-expand PAPs] + -- in GHC.Core.Opt.Simplify.Utils init_env :: ArityEnv init_env = findRhsArityEnv opts (isJoinId bndr) @@ -2388,6 +2395,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco -- and is SymCo'd in `etaInfoAbs`. Hence the orientation of the visibility -- flags. A bit of a brain-strain (#27557). + {- ************************************************************************ * * @@ -2452,16 +2460,20 @@ perform eta reduction on an expression with n leading lambdas `\xs. e xs` (checked in 'is_eta_reduction_sound' in 'tryEtaReduce', which focuses on the case where `e` is trivial): -(A) It is sound to eta-reduce n arguments as long as n does not exceed the - `exprArity` of `e`. (Needs Arity analysis.) - This criterion exploits information about how `e` is *defined*. +(EtaA) It is sound to eta-reduce n arguments as long as n does not exceed the + `exprArity` of `e`. (Needs Arity analysis.) This criterion exploits information + about how `e` is *defined*. For example: + f = \xy. g x y ===> f = g + This eta-reduction is good only if `g` has arity at least 2, otherwise + f's arity will decrease from 2 to 1. + c.f. Note [Arity robustness] in GHC.Core.Opt.Simplify.Env. - Example: If `e = \x. bot` then we know it won't diverge until it is called - with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`. + Another example: If `e = \x. bot` then we know it won't diverge until it + is called with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`. By contrast, it would be *unsound* to eta-reduce 2 args, `\x y. e x y` to `e`: `e 42` diverges when `(\x y. e x y) 42` does not. -(S) It is sound to eta-reduce n arguments in an evaluation context in which all +(EtaS) It is sound to eta-reduce n arguments in an evaluation context in which all calls happen with at least n arguments. (Needs Strictness analysis.) NB: This treats evaluations like a call with 0 args. NB: This criterion exploits information about how `e` is *used*. @@ -2483,35 +2495,31 @@ case where `e` is trivial): But it is unsound to eta-reduce the arg in `g2 (\x y. e x y)` to `g2 e` when `e = \x. if x then bot else id`, because the latter will diverge when the former would not. Fortunately, the strictness analyser will report - "Not always called with two arguments" for `g2` and we won't eta-expand. + "Not always called with two arguments" for `g2` and we won't eta-reduce. See Note [Eta reduction based on evaluation context] for the implementation details. This criterion is tested extensively in T21261. -(R) Note [Eta reduction in recursive RHSs] tells us that we should not +(EtaR) Note [Eta reduction in recursive RHSs] tells us that we should not eta-reduce `f` in its own RHS and describes our fix. There we have `f = \x. f x` and we should not eta-reduce to `f=f`. Which might change a terminating program (think @f `seq` e@) to a non-terminating one. -(E) (See fun_arity in tryEtaReduce.) As a perhaps special case on the - boundary of (A) and (S), when we know that a fun binder `f` is in - WHNF, we simply assume it has arity 1 and apply (A). Example: +(EtaE) (See fun_arity in tryEtaReduce.) As a perhaps special case on the + boundary of (EtaA) and (EtaS), when we know that a fun binder `f` is in + WHNF, we simply assume it has arity 1 and apply (EtaA). Example: g f = f `seq` \x. f x Here it's sound eta-reduce `\x. f x` to `f`, because `f` can't be bottom after the `seq`. This turned up in #7542. - T. If the binders are all type arguments, it's always safe to eta-reduce, - regardless of the arity of f. - /\a b. f @a @b --> f - -2. Type and dictionary abstraction. Regardless of whether 'f' is a value, it +(EtaT) Type and dictionary abstraction. Regardless of whether 'f' is a value, it is always sound to reduce /type lambdas/, thus: - (/\a -> f a) --> f + (/\a -> f @a) --> f Moreover, we always want to, because it makes RULEs apply more often: - This RULE: `forall g. foldr (build (/\a -> g a))` + This RULE: `forall g. foldr (build (/\a -> g @a))` should match `foldr (build (/\b -> ...something complex...))` - and the simplest way to do so is eta-reduce `/\a -> g a` in the RULE to `g`. + and the simplest way to do so is eta-reduce `/\a -> g @a` in the RULE to `g`. More debatably, we extend this to dictionary arguments too, because the type checker can insert these eta-expanded versions, with both type and dictionary @@ -2523,18 +2531,25 @@ case where `e` is trivial): And here are a few more technical criteria for when it is *not* sound to eta-reduce that are specific to Core and GHC: -(J) We may not undersaturate join points. +(EtaJ) We may not undersaturate join points. See Note [Invariants on join points] in GHC.Core, and #20599. -(B) We may not undersaturate functions with no binding. +(EtaB) We may not undersaturate functions with no binding. See Note [Eta expanding primops]. -(W) We may not undersaturate StrictWorkerIds. +(EtaW) We may not undersaturate StrictWorkerIds. See Note [CBV Function Ids: overview] in GHC.Types.Id.Info. -Here is a list of historic accidents surrounding unsound eta-reduction: -* Consider +Here is a list of historic notes surrounding unsound eta-reduction: + +(EtaMult) We used to disable eta-reduction if performing it would change multiplicity. + For example: + (\x. K x) :: Int -> T but K :: Int %1 -> T + But that (a) inhibits beneficial eta-reduction (b) costs extra work to check, and + now we don't even try. See Note [Linting linearity] in GHC.Core.Lint, esp EXAMPLE 4 + +(EtaBot) Consider f = \x.f x h y = case (case y of { True -> f `seq` True; False -> False }) of True -> ...; False -> ... @@ -2548,16 +2563,6 @@ Here is a list of historic accidents surrounding unsound eta-reduction: Result: seg-fault because the boolean case actually gets a function value. See #1947. -* Never *reduce* arity. For example - f = \xy. g x y - Then if h has arity 1 we don't want to eta-reduce because then - f's arity would decrease, and that is bad - [SG in 2022: I don't understand this point. There is no `h`, perhaps that - should have been `g`. Even then, this proposed eta-reduction is invalid by - criterion (A), which might actually be the point this anecdote is trying to - make. Perhaps the "no arity decrease" idea is also related to - Note [Arity robustness]?] - Note [Do not eta reduce PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I considered eta-reducing if the result is a PAP: @@ -2598,11 +2603,12 @@ This should be eta-reduced to So we need to accumulate a coercion, pushing it inward (past variable arguments only) thus: - f (x |> co_arg) |> co --> (f |> (sym co_arg -> co)) x - f (x:t) |> co --> (f |> (t -> co)) x - f @ a |> co --> (f |> (forall a.co)) @ a - f @ (g:t1~t2) |> co --> (f |> (t1~t2 => co)) @ (g:t1~t2) -These are the equations for ok_arg. +(ECA1) \x. f (x |> co_arg) |> co --> (f |> (sym co_arg -> co)) +(ECA2) \x. f (x:t) |> co --> (f |> (t -> co)) +(ECA3) \x. f (g:t1~#t2) |> co --> (f |> (t1~#t2 => co)) +(ECA4) \x. f @ a |> co --> (f |> (forall a.co)) + +These are implemented by the `go` equations in `tryEtaReduce` Note [Eta reduction with casted function] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -2620,7 +2626,7 @@ eta-expansion may be turned off (by sm_eta_expand). Note [Eta reduction based on evaluation context] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Note [Eta reduction soundness], criterion (S) allows us to eta-reduce +Note [Eta reduction soundness], criterion (EtaS) allows us to eta-reduce `g (\x y. e x y)` to `g e` when we know that `g` always calls its parameter with at least 2 arguments. So how do we read that off `g`'s demand signature? @@ -2713,13 +2719,13 @@ tryEtaReduce :: UnVarSet -> [Var] -> CoreExpr -> SubDemand -> Maybe CoreExpr -- and Note [Eta reduction makes sense] when that is the case. -- and Note [Eta reduction based on evaluation context] for the `eval_sd` arg tryEtaReduce rec_ids bndrs body eval_sd - = go (reverse bndrs) body (mkRepReflCo (exprType body)) + = go (reverse bndrs) body MRefl where - incoming_arity = count isId bndrs -- See Note [Eta reduction makes sense], point (2) + incoming_arity = count isId bndrs -- See (EtaA) in Note [Eta reduction soundness] go :: [Var] -- Binders, innermost first, types [a3,a2,a1] -> CoreExpr -- Of type tr - -> Coercion -- Of type tr ~ ts + -> MCoercion -- Of type tr ~ ts -> Maybe CoreExpr -- Of type a1 -> a2 -> a3 -> ts -- See Note [Eta reduction with casted arguments] -- for why we have an accumulating coercion @@ -2729,19 +2735,37 @@ tryEtaReduce rec_ids bndrs body eval_sd -- See Note [Eta reduction with casted function] go bs (Cast e co1) co2 - = go bs e (co1 `mkTransCo` co2) + = go bs e (co1 `mkTransMCoR` co2) go bs (Tick t e) co | tickishFloatable t = fmap (Tick t) $ go bs e co -- Float app ticks: \x -> Tick t (e x) ==> Tick t e - go (b : bs) (App fun arg) co - | Just (co', ticks) <- ok_arg b arg co (exprType fun) - = fmap (flip (foldr mkTick) ticks) $ go bs fun co' - -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e + -- Implements (ECA4) + go all_bs@(b : bs) all_e@(App fun (Type arg_ty)) mco + | Just tv <- getTyVar_maybe arg_ty + , b == tv + , Just (bndr, body_ty) <- splitForAllForAllTyBinder_maybe (exprType fun) + = go bs fun (mkEtaReduceForAllMCo bndr body_ty tv mco) - go remaining_bndrs fun co + | otherwise + = go_finish all_bs all_e mco + -- Want to go to the finish case; see the call + -- to (all isTyVar remaining_bndrs) there + + -- Implements (ECA1), (ECA2), (ECA3) + go (b : bs) (App fun val_arg) mco + | Just (v, arg_mco, arg_ticks) <- getTrivialHead_maybe val_arg + , b == v + , Just co' <- mkEtaReduceFunCo (exprType fun) arg_mco mco + = fmap (flip (foldr mkTick) arg_ticks) $ + go bs fun co' + -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e + + go bs fun co = go_finish bs fun co + + go_finish remaining_bndrs fun co | all isTyVar remaining_bndrs -- If all the remaining_bnrs are tyvars, then the etad_exp -- will be trivial, which is what we want. @@ -2752,7 +2776,7 @@ tryEtaReduce rec_ids bndrs body eval_sd , remaining_bndrs `ltLength` bndrs -- Only reply Just if /something/ has happened , ok_fun fun - , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfCo co + , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfMCo co reduced_bndrs = mkVarSet (dropList remaining_bndrs bndrs) -- reduced_bndrs are the ones we are eta-reducing away , used_vars `disjointVarSet` reduced_bndrs @@ -2761,10 +2785,10 @@ tryEtaReduce rec_ids bndrs body eval_sd -- See Note [Eta reduction makes sense], intro and point (1) -- NB: don't compute used_vars from exprFreeVars (mkCast fun co) -- because the latter may be ill formed if the guard fails (#21801) - = Just (mkLams (reverse remaining_bndrs) (mkCast fun co)) + = Just (mkLams (reverse remaining_bndrs) (mkCastMCo fun co)) - go _remaining_bndrs _fun _ = -- pprTrace "tER fail" (ppr _fun $$ ppr _remaining_bndrs) $ - Nothing + | otherwise + = Nothing --------------- -- See Note [Eta reduction makes sense], point (1) @@ -2777,18 +2801,18 @@ tryEtaReduce rec_ids bndrs body eval_sd --------------- -- See Note [Eta reduction soundness], this is THE place to check soundness! is_eta_reduction_sound fun - | fun `elemUnVarSet` rec_ids -- Criterion (R) + | fun `elemUnVarSet` rec_ids -- Criterion (EtaR) = False -- Don't eta-reduce in fun in its own recursive RHSs - | cantEtaReduceFun fun -- Criteria (J), (W), (B) + | cantEtaReduceFun fun -- Criteria (EtaJ), (EtaW), (EtaB) = False -- Function can't be eta reduced to arity 0 -- without violating invariants of Core and GHC | otherwise = -- Check that eta-reduction won't make the program stricter... - fun_arity fun >= incoming_arity -- Criterion (A) and (E) - || all_calls_with_arity incoming_arity -- Criterion (S) - || all ok_lam bndrs -- Criterion (T) + fun_arity fun >= incoming_arity -- Criterion (EtaA) and (EtaE) + || all_calls_with_arity incoming_arity -- Criterion (EtaS) + || all ok_lam bndrs -- Criterion (EtaT) all_calls_with_arity n = isStrict (fst $ peelManyCalls n eval_sd) -- See Note [Eta reduction based on evaluation context] @@ -2797,57 +2821,76 @@ tryEtaReduce rec_ids bndrs body eval_sd fun_arity fun | arity > 0 = arity | isEvaldUnfolding (idUnfolding fun) = 1 - -- See Note [Eta reduction soundness], criterion (E) + -- See Note [Eta reduction soundness], criterion (EtaE) | otherwise = 0 where arity = idArity fun --------------- ok_lam v = isTyVar v || isEvId v - -- See Note [Eta reduction makes sense], point (2) - - --------------- - ok_arg :: Var -- Of type bndr_t - -> CoreExpr -- Of type arg_t - -> Coercion -- Of kind (t1~t2) - -> Type -- Type (arg_t -> t1) of the function - -- to which the argument is supplied - -> Maybe (Coercion -- Of type (arg_t -> t1 ~ bndr_t -> t2) - -- (and similarly for tyvars, coercion args) - , [CoreTickish]) - -- See Note [Eta reduction with casted arguments] - ok_arg bndr (Type arg_ty) co fun_ty - | Just tv <- getTyVar_maybe arg_ty - , bndr == tv = case splitForAllForAllTyBinder_maybe fun_ty of - Just (Bndr _ vis, _) -> Just (fco, []) - where !fco = mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co - -- The lambda we are eta-reducing always has visibility - -- 'coreTyLamForAllTyFlag' which may or may not match - -- the visibility on the inner function (#24014) - Nothing -> pprPanic "tryEtaReduce: type arg to non-forall type" - (text "fun:" <+> ppr bndr - $$ text "arg:" <+> ppr arg_ty - $$ text "fun_ty:" <+> ppr fun_ty) - ok_arg bndr (Var v) co fun_ty - | bndr == v - , let mult = idMult bndr - , Just (_af, fun_mult, _, _) <- splitFunTy_maybe fun_ty - , mult `eqType` fun_mult -- There is no change in multiplicity, otherwise we must abort - = Just (mkFunResCo Representational bndr co, []) - ok_arg bndr (Cast e co_arg) co fun_ty - | (ticks, Var v) <- stripTicksTop tickishFloatable e - , Just (_, fun_mult, _, _) <- splitFunTy_maybe fun_ty - , bndr == v - , fun_mult `eqType` idMult bndr - = Just (mkFunCoNoFTF Representational (multToCo fun_mult) (mkSymCo co_arg) co, ticks) - -- The simplifier combines multiple casts into one, - -- so we can have a simple-minded pattern match here - ok_arg bndr (Tick t arg) co fun_ty - | tickishFloatable t, Just (co', ticks) <- ok_arg bndr arg co fun_ty - = Just (co', t:ticks) - - ok_arg _ _ _ _ = Nothing + -- See Note [Eta reduction soundness], point (EtaT) + + +----------------- +getTrivialHead_maybe :: CoreExpr -> Maybe (Id, MCoercion, [CoreTickish]) +-- (getTrivialHead_maybe e) returns (Just (fn, co,ts)) +-- if `e` looks like (Tick ts (fn |> co)) and ts are floatable +-- So co :: fn_ty ~ arg_ty + +getTrivialHead_maybe (Var v) + = Just (v, MRefl, []) + +getTrivialHead_maybe (Cast e co_outer) + = do { (v, mco_inner, ticks) <- getTrivialHead_maybe e + ; return (v, mco_inner `mkTransMCoL` co_outer, ticks) } + +getTrivialHead_maybe (Tick t arg) + | tickishFloatable t + = do { (v, co, ticks) <- getTrivialHead_maybe arg + ; return (v, co, t:ticks) } + +getTrivialHead_maybe _ = Nothing + +----------------- +mkEtaReduceFunCo :: Type -> MCoercion -> MCoercion -> Maybe MCoercion +mkEtaReduceFunCo _ MRefl MRefl + = Just MRefl -- Very common case +mkEtaReduceFunCo fun_ty arg_mco res_mco + | Just (ftf, mult, arg_ty, res_ty) <- splitFunTy_maybe fun_ty + -- fun_ty = arg_ty -> res_ty + -- sym arg_mco : arg_ty ~ inner_arg_ty + -- res_mco : res_ty ~ outer_res_ty + , let arg_co = mCoToCo Representational arg_ty arg_mco + res_co = mCoToCo Representational res_ty res_mco + mult_co = multToCo mult + ftf' = chooseFunTyFlag (coercionLKind arg_co) (coercionRKind res_co) + = Just (MCo (mkFunCo2 Representational ftf ftf' mult_co (mkSymCo arg_co) res_co)) + -- (arg_ty -> res_ty) ~ (inner_arg_ty -> outer_res_ty) + | otherwise + = Nothing +----------------- +mkEtaReduceForAllMCo :: ForAllTyBinder -> Type -> TyVar -> MCoercion -> MCoercion +-- Very similar to mkEtaForAllMCo, but with +-- the visibilities the other way around. Tiresome. +-- mkEtaReduceForAllMCo (forall a[vis]. body_ty) b (co :: ty1 ~ ty2) +-- (where `b` may be free in `ty1` and `ty2`) +-- = ForAllCo b[vis]~[spec]. (co :: ty1 ~ ty2) +-- where `coreTyLamForAllTyFlag` is [spec] +mkEtaReduceForAllMCo (Bndr fun_tv vis) body_ty tv mco + = case mco of + MRefl | isCoreTyLamForAllTyFlag vis + -- The lambda we are eta-reducing always has visibility + -- 'coreTyLamForAllTyFlag' which may or may not match the + -- visibility on the inner function (#24014) + -> MRefl + | otherwise + -> MCo $ mkForAllCo fun_tv vis coreTyLamForAllTyFlag MRefl refl_co + MCo co -> MCo $ mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co + -- Tricky: `fun_tv` scopes over `body_ty` and hence over `refl_co` + -- but: `tv` scopes over `mco` and hence over `co` + where + refl_co = mkRepReflCo body_ty {- ********************************************************************* * * ===================================== compiler/GHC/Core/Opt/OccurAnal.hs ===================================== @@ -42,7 +42,6 @@ import GHC.Core.Utils ( exprIsTrivial, isDefaultAlt, isExpandableApp, import GHC.Core.Opt.Arity ( joinRhsArity, isOneShotBndr ) import GHC.Core.Coercion import GHC.Core.Type -import GHC.Core.TyCo.FVs ( tyCoVarsOfMCo ) import GHC.Data.Maybe( orElse ) import GHC.Data.Graph.Directed ( SCC(..), Node(..) ===================================== compiler/GHC/Core/Opt/Simplify/Env.hs ===================================== @@ -1240,6 +1240,8 @@ out_id so that its arity is visible in its RHS. Examples: Example: `f = \x. f x`. See Note [Eta reduction in recursive RHSs] for how we prevent that. +c.f. (EtaA) in Note [Eta reduction soundness] in GHC.Core.Opt.Arity. + Note [Robust OccInfo] ~~~~~~~~~~~~~~~~~~~~~ It's important that we *do* retain the loop-breaker OccInfo, because ===================================== compiler/GHC/Core/Opt/Simplify/Iteration.hs ===================================== @@ -3143,7 +3143,7 @@ There have been various earlier versions of this patch: case_bndr_evald_next _ = False This patch was part of fixing #7542. See also - Note [Eta reduction soundness], criterion (E) in GHC.Core.Utils.) + Note [Eta reduction soundness], criterion (EtaE) in GHC.Core.Opt.Arity.) Further notes about case elimination ===================================== compiler/GHC/Core/Opt/Simplify/Utils.hs ===================================== @@ -2110,8 +2110,9 @@ tryEtaExpandRhs :: SimplEnv -> BindContext -> OutId -> OutExpr tryEtaExpandRhs env bind_cxt bndr rhs | seEtaExpand env -- If Eta-expansion is on , wantEtaExpansion rhs -- and we'd like to eta-expand e - , do_eta_expand -- and e's manifest arity is lower than - -- what it could be + , do_eta_expand -- and arity analysis finds a greater arity + -- than (exprArity e); NB: not manifestArity + -- See Note [Do not eta-expand PAPs] -- (never true for join points) = -- Do eta-expansion. assertPpr( not (isJoinBC bind_cxt) ) (ppr bndr) $ @@ -2130,7 +2131,8 @@ tryEtaExpandRhs env bind_cxt bndr rhs (do_eta_expand, arity_type) = findRhsArity arity_opts is_rec bndr rhs wantEtaExpansion :: CoreExpr -> Bool --- Mostly True; but False of PAPs which will immediately eta-reduce again +-- Mostly True; but False of trivial RHSs, and of PAPs at the top of the RHS +-- (PAPs under value lambdas are dealt with by findRhsArity) -- See Note [Which RHSs do we eta-expand?] wantEtaExpansion (Cast e _) = wantEtaExpansion e wantEtaExpansion (Tick _ e) = wantEtaExpansion e @@ -2168,7 +2170,22 @@ seems like a Good idea. Note [Do not eta-expand PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We used to have old_arity = manifestArity rhs, which meant that we +We do not eta-expand a RHS that is a partial application (PAP). This +is achieved in two places: + +(DEP1) A PAP at the top of the RHS, such as + f = g d -- g has arity 2 + is rejected by `wantEtaExpansion`. + +(DEP2) A PAP under value lambdas, such as + f = \x. g x -- g has arity 3 + is not eta-expanded because `findRhsArity` asks for eta-expansion + only if the arity it finds is greater than (exprArity rhs), and + `exprArity` takes account of PAPs: here (exprArity rhs) = 3. + Using `manifestArity` (which is 1 here) instead would eta-expand + to f = \x y z. g x y z. + +Up to 2014 we used old_arity = manifestArity rhs, which meant that we would eta-expand even PAPs. But this gives no particular advantage, and can lead to a massive blow-up in code size, exhibited by #9020. Suppose we have a PAP @@ -2184,6 +2201,17 @@ coercions and whatnot that eventually disappear again. For T9020, GHC allocated 6.6G before, and 0.8G afterwards; and residency dropped from 1.8G to 45M. +#27212 tried switching (DEP2) back to manifestArity, with these results: + +* T13960: bytestring's + cstring1 = \(a::Addr#) @r. cstring2 @r a -- cstring2 has arity 4 + was eta-expanded to (\a @r k br s. cstring2 @r a k br s). That bigger + unfolding is inlined at every string literal, adding 6 terms per + literal; compile-time allocation went up by 9%. + +* T13056: a derived-instance method (\ @a d. lvl @a), where `lvl` is + bottoming, was eta-expanded, and then needlessly worker/wrappered. + Moreover, if we eta expand f = g d ==> f = \x. g d x that might in turn make g inline (if it has an inline pragma), which ===================================== compiler/GHC/Core/TyCo/Make.hs ===================================== @@ -58,7 +58,7 @@ module GHC.Core.TyCo.Make ( , mkAxInstCo , mkTransCo, mkTransMCo, mkTransMCoL, mkTransMCoR , mkProofIrrelCo - , coToMCo, kindCoToMKindCo + , coToMCo, kindCoToMKindCo, mCoToCo , mkCoherenceLeftCo, mkCoherenceRightCo, mkCoherenceRightMCo , toPhantomCo, mkPhantomCo , isReflCo, isReflMCo, isReflKindCo, isReflKindMCo, isReflCo_maybe @@ -860,7 +860,7 @@ mkHomoForAllCos vs orig_co = foldr go orig_co vs where go :: ForAllTyBinder -> Coercion -> Coercion - go (Bndr var vis) co = mk_forall_co var vis vis MRefl co + go (Bndr var vis) co = mkForAllCoNonRefl var vis vis MRefl co mkHomoForAllCo :: TyVar -> Coercion -> Coercion -- Specialised for a single TyVar, @@ -869,7 +869,7 @@ mkHomoForAllCo tv orig_co | Just (ty, r) <- isReflCo_maybe orig_co = mkReflCo r (mkForAllTy (Bndr tv vis) ty) | otherwise - = mk_forall_co tv vis vis MRefl orig_co + = mkForAllCoNonRefl tv vis vis MRefl orig_co where vis = coreTyLamForAllTyFlag @@ -892,15 +892,15 @@ mkForAllCo v visL visR kind_co co | Just refl_co <- isReflForAllCo v visL visR kind_co co = refl_co | otherwise - = mk_forall_co v visL visR kind_co co + = mkForAllCoNonRefl v visL visR kind_co co --- | `mk_forall_co` just builds a ForAllCo. +-- | `mkForAllCoNonRefl` just builds a ForAllCo. -- With debug on, it checks invariants (e.g. he kind of the tycovar should -- be the left-hand kind of the kind coercion). -- Callers should have done any isReflCo short-cutting. -mk_forall_co :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag - -> KindMCoercion -> Coercion -> Coercion -mk_forall_co tcv visL visR kind_co co +mkForAllCoNonRefl :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag + -> KindMCoercion -> Coercion -> Coercion +mkForAllCoNonRefl tcv visL visR kind_co co = assertGoodForAllCo tcv visL visR kind_co co $ assertPpr (not (isReflCo co && isReflMCo kind_co && visL `eqForAllVis` visR)) (ppr co) $ ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR @@ -1289,6 +1289,10 @@ coToMCo :: Coercion -> MCoercion coToMCo co | isReflCo co = MRefl | otherwise = MCo co +mCoToCo :: Role -> Type -> MCoercion -> Coercion +mCoToCo role ty MRefl = mkReflCo role ty +mCoToCo _ _ (MCo co) = co + kindCoToMKindCo :: KindCoercion -> KindMCoercion -- Convert a KindCoercion to a KindMCoercion, -- coToMCo doesn't eliminate GRefl, but kindCoToMCo can ===================================== compiler/GHC/Core/Type.hs ===================================== @@ -160,7 +160,7 @@ module GHC.Core.Type ( -- * Type free variables tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeDSet, - coVarsOfType, coVarsOfTypes, + tyCoVarsOfMCo, coVarsOfType, coVarsOfTypes, anyFreeVarsOfType, anyFreeVarsOfTypes, noFreeVarsOfType, ===================================== compiler/GHC/Core/Utils.hs ===================================== @@ -2392,7 +2392,7 @@ canCollectArgsThroughTick id t = tickishFloatable t || cantEtaReduceFun id -- | Can we eta-reduce the given function? --- See Note [Eta reduction soundness], criteria (B), (J), and (W). +-- See Note [Eta reduction soundness], criteria (EtaB), (EtaJ), and (EtaW). cantEtaReduceFun :: Id -> Bool cantEtaReduceFun fun = hasNoBinding fun -- (B) ===================================== testsuite/tests/dmdanal/sigs/T21888a.stderr ===================================== @@ -7,7 +7,7 @@ T21888a.wombat: <S!P(S)>b ==================== Cpr signatures ==================== -T21888a.f: 2 +T21888a.f: T21888a.g: 1 T21888a.wombat: b ===================================== testsuite/tests/printer/T18052a.stderr ===================================== @@ -10,11 +10,11 @@ Dependent packages: [(normal, base-4.23.0.0)] ==================== Tidy Core ==================== Result size of Tidy Core - = {terms: 24, types: 52, coercions: 0, joins: 0/0} + = {terms: 18, types: 46, coercions: 0, joins: 0/0} --- RHS size: {terms: 7, types: 6, coercions: 0, joins: 0/0} +-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0} T18052a.$b:||: :: forall {a} {b}. a -> b -> (a, b) -T18052a.$b:||: = \ (@a) (@b) (x :: a) (y :: b) -> (x, y) +T18052a.$b:||: = GHC.Internal.Tuple.(,) -- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0} (+++) :: forall {a}. [a] -> [a] -> [a] ===================================== testsuite/tests/simplCore/should_compile/T27212.hs ===================================== @@ -0,0 +1,17 @@ +module T27212 where + +import Unsafe.Coerce + +class Given a where given :: a +newtype Gift a r = Gift (Given a => r) + +useIt :: Given Int => Int +useIt = given + 1 +{-# NOINLINE useIt #-} + +foo :: [Int] -> [Int] +foo xs = case unsafeEqualityProof @(Gift Int Int) @(Int -> Int) of + UnsafeRefl -> map (\y -> (Gift useIt :: Gift Int Int) y) xs + -- That (\y. glah y) can eta-reduce to `glah` + -- but doing doing so makes a FunCo coercion that crosses from + -- Type to constraint. Tricky. ===================================== testsuite/tests/simplCore/should_compile/all.T ===================================== @@ -631,3 +631,4 @@ 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']) +test('T27212', normal, compile, ['-O']) View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/d2b9078f4e16715931df93d9dcb62c42... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/d2b9078f4e16715931df93d9dcb62c42... 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