Simon Peyton Jones pushed to branch wip/simpl-clo at Glasgow Haskell Compiler / GHC

Commits:

11 changed files:

Changes:

  • compiler/GHC/Core.hs
    ... ... @@ -1752,6 +1752,44 @@ So unfoldings on lambda binders can never really be trusted when on lambda binde
    1752 1752
     is the chance of the call site to change. So it's easiest to just never attach any
    
    1753 1753
     to lambda binders to begin with, as well as stripping them off if we e.g. float out
    
    1754 1754
     and expression while abstracting over some arguments.
    
    1755
    +
    
    1756
    +See also Note [Lambda and case binders have vanilla IdInfo].
    
    1757
    +
    
    1758
    +Note [Lambda and case binders have vanilla IdInfo]
    
    1759
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1760
    +Invariant: the following binders
    
    1761
    +  * lambda binders                 (\x. e)
    
    1762
    +  * case binders                   case e of x { ... }
    
    1763
    +  * case-alternative binders       case e of _ { K x y -> ... }
    
    1764
    +have none of
    
    1765
    +  (a) RULES
    
    1766
    +  (b) a (non-default) inline pragma, such as INLINE or NOINLINE
    
    1767
    +  (c) a stable unfolding
    
    1768
    +The predicate `GHC.Types.Id.lamBndrInfoOK` checks (a-c), and Core Lint checks
    
    1769
    +it (in `lintIdBndr`).  Moreover lambda binders have no unfolding at all, not
    
    1770
    +even an OtherCon one: see Note [Never put `OtherCon` unfoldings on lambda binders].
    
    1771
    +
    
    1772
    +Why?  RULES, pragmas, and stable unfoldings describe a /let-bound/ Id, whose
    
    1773
    +definition is right there in the binding.  It is far from clear what they would
    
    1774
    +mean for a lambda binder, whose value is supplied by the caller; and we can't
    
    1775
    +easily work out the consequences of allowing them.  It is much simpler just to
    
    1776
    +rule them out.  For example, `preInlineBetaUnconditionally` assumes the
    
    1777
    +invariant, and so does not check the binder's activation or stable unfolding.
    
    1778
    +This is very much in the spirit of #17530, when we stopped adding unfoldings to
    
    1779
    +lambda binders.
    
    1780
    +
    
    1781
    +Why case binders and case-alternative binders?  Because they can become lambda
    
    1782
    +binders, when `mkDupableAlt` abstracts a join point over them.
    
    1783
    +
    
    1784
    +Places that must take care to maintain the invariant (#27965):
    
    1785
    +
    
    1786
    +* The desugarer, when desugaring a strict binding  let !x = rhs in body,
    
    1787
    +  generates  case x of x { DEFAULT -> body }; the case binder must not inherit
    
    1788
    +  x's IdInfo.  See `GHC.HsToCore.Utils.seqVar`.
    
    1789
    +
    
    1790
    +* The Simplifier, when duplicating a StrictBind continuation  let x = <> in b,
    
    1791
    +  makes a join point whose lambda binder must not inherit x's IdInfo.
    
    1792
    +  See (DSB1) in Note [Duplicating StrictBind] in GHC.Core.Opt.Simplify.Iteration.
    
    1755 1793
     -}
    
    1756 1794
     
    
    1757 1795
     -- | Records the /unfolding/ of an identifier, which is approximately the form the
    

  • compiler/GHC/Core/Lint.hs
    ... ... @@ -1858,6 +1858,17 @@ lintIdBndr top_lvl bind_site id thing_inside
    1858 1858
              hang (text "Lambda binder" <+> quotes (ppr id) <+> text "has an unfolding")
    
    1859 1859
                 2 (ppr unf)
    
    1860 1860
     
    
    1861
    +       -- Check that lambda, case, and case-alternative binders have
    
    1862
    +       -- no RULES, no inline pragma, and no stable unfolding
    
    1863
    +       -- See Note [Lambda and case binders have vanilla IdInfo] in GHC.Core
    
    1864
    +       ; checkL (is_let_bind || lamBndrInfoOK id) $
    
    1865
    +         hang (text "Non-let binder" <+> quotes (ppr id)
    
    1866
    +               <+> text "has RULES, an inline pragma, or a stable unfolding")
    
    1867
    +            2 (vcat [ text "Binding site:" <+> text (show_site bind_site)
    
    1868
    +                    , text "Inline pragma:" <+> ppr (idInlinePragma id)
    
    1869
    +                    , text "Rules:" <+> ppr (idCoreRules id)
    
    1870
    +                    , text "Unfolding:" <+> ppr (realIdUnfolding id) ])
    
    1871
    +
    
    1861 1872
            ; addLoc (IdTy id) (lintValueType id_ty)
    
    1862 1873
     
    
    1863 1874
            ; addInScopeId id thing_inside }
    
    ... ... @@ -1869,6 +1880,12 @@ lintIdBndr top_lvl bind_site id thing_inside
    1869 1880
                         LetBind -> True
    
    1870 1881
                         _       -> False
    
    1871 1882
     
    
    1883
    +    show_site :: BindingSite -> String
    
    1884
    +    show_site LambdaBind  = "lambda"
    
    1885
    +    show_site CaseBind    = "case binder"
    
    1886
    +    show_site CasePatBind = "case alternative"
    
    1887
    +    show_site LetBind     = "let"
    
    1888
    +
    
    1872 1889
     {-
    
    1873 1890
     %************************************************************************
    
    1874 1891
     %*                                                                      *
    

  • compiler/GHC/Core/Opt/Simplify/Env.hs
    ... ... @@ -28,7 +28,7 @@ module GHC.Core.Opt.Simplify.Env (
    28 28
             SimplEnvIS,  checkSimplEnvIS, pprBadSimplEnvIS,
    
    29 29
     
    
    30 30
             -- * Substitution results
    
    31
    -        SimplSR(..), substId, lookupRecBndr,
    
    31
    +        SimplClo(..), simplCloExpr, substId, lookupRecBndr,
    
    32 32
     
    
    33 33
             -- * Simplifying 'Id' binders
    
    34 34
             simplNonRecBndr, simplNonRecJoinBndr, simplRecBndrs, simplRecJoinBndrs,
    
    ... ... @@ -61,7 +61,7 @@ import GHC.Core.Opt.Simplify.Monad
    61 61
     import GHC.Core.Rules.Config ( RuleOpts(..) )
    
    62 62
     import GHC.Core
    
    63 63
     import GHC.Core.Utils
    
    64
    -import GHC.Core.Subst( substExprSC )
    
    64
    +import GHC.Core.Subst( substExpr, substExprSC )
    
    65 65
     import GHC.Core.Unfold
    
    66 66
     import GHC.Core.TyCo.Subst (emptyIdSubstEnv, mkSubst)
    
    67 67
     import GHC.Core.Multiplicity( Scaled(..), mkMultMul )
    
    ... ... @@ -470,11 +470,16 @@ pprSimplEnv env
    470 470
        ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
    
    471 471
                  | otherwise = ppr v
    
    472 472
     
    
    473
    -type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
    
    473
    +type SimplIdSubst = IdEnv SimplClo -- IdId |--> OutExpr
    
    474 474
             -- See Note [Extending the IdSubstEnv] in GHC.Core.Subst
    
    475 475
     
    
    476
    --- | A substitution result.
    
    477
    -data SimplSR
    
    476
    +-- | A "closure" used in the Simplifier.  It is used
    
    477
    +--     * as the range of the substitution, 'SimplIdSubst'
    
    478
    +--     * as the argument in an 'ApplyToVal' continuation
    
    479
    +-- Roughly: either an (InExpr, StaticEnv) pair for an
    
    480
    +--                 as-yet-unsimplified expression
    
    481
    +--          or     an OutExpr, for an already-simplified one
    
    482
    +data SimplClo
    
    478 483
       = DoneEx OutExpr JoinPointHood
    
    479 484
            -- If  x :-> DoneEx e ja   is in the SimplIdSubst
    
    480 485
            -- then replace occurrences of x by e
    
    ... ... @@ -490,11 +495,11 @@ data SimplSR
    490 495
     
    
    491 496
       | ContEx SimplEnv
    
    492 497
                InExpr
    
    493
    -           MOutCoercion  -- See Note [The sc_cast field of ApplyToVal]
    
    498
    +           MOutCoercion  -- See Note [The MOutCoercion field of ContEx]
    
    494 499
           -- If   x :-> ContEx static_env e mco   is in the SimplISubst
    
    495 500
           -- then replace occurrences of x by (subst static_env e) |> mco
    
    496 501
     
    
    497
    -instance Outputable SimplSR where
    
    502
    +instance Outputable SimplClo where
    
    498 503
       ppr (DoneId v)    = text "DoneId" <+> ppr v
    
    499 504
       ppr (DoneEx e mj) = text "DoneEx" <> pp_mj <+> ppr e
    
    500 505
         where
    
    ... ... @@ -637,7 +642,7 @@ reSimplifying :: SimplEnv -> Bool
    637 642
     reSimplifying (SimplEnv { seInlineDepth = n }) = n>0
    
    638 643
     
    
    639 644
     ---------------------
    
    640
    -extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
    
    645
    +extendIdSubst :: SimplEnv -> Id -> SimplClo -> SimplEnv
    
    641 646
     extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
    
    642 647
       = assertPpr (isId var && not (isCoVar var)) (ppr var) $
    
    643 648
         env { seIdSubst = extendVarEnv subst var res }
    
    ... ... @@ -1032,7 +1037,7 @@ So we want to look up the inner X.g_34 in the substitution, where we'll
    1032 1037
     find that it has been substituted by b.  (Or conceivably cloned.)
    
    1033 1038
     -}
    
    1034 1039
     
    
    1035
    -substId :: SimplEnv -> InId -> SimplSR
    
    1040
    +substId :: SimplEnv -> InId -> SimplClo
    
    1036 1041
     -- Returns DoneEx only on a non-Var expression
    
    1037 1042
     substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
    
    1038 1043
       = case lookupVarEnv ids v of  -- Note [Global Ids in the substitution]
    
    ... ... @@ -1366,7 +1371,7 @@ getFullSubst :: InScopeSet -> SimplEnv -> Subst
    1366 1371
     getFullSubst in_scope (SimplEnv { seIdSubst = id_env, seTvSubst = tv_env, seCvSubst = cv_env })
    
    1367 1372
       = mkSubst in_scope (mapVarEnv to_expr id_env) tv_env cv_env
    
    1368 1373
       where
    
    1369
    -    to_expr :: SimplSR -> CoreExpr
    
    1374
    +    to_expr :: SimplClo -> CoreExpr
    
    1370 1375
         -- A tiresome impedence-matcher
    
    1371 1376
         to_expr (DoneEx e _)       = e
    
    1372 1377
         to_expr (DoneId v)         = Var v
    
    ... ... @@ -1374,6 +1379,17 @@ getFullSubst in_scope (SimplEnv { seIdSubst = id_env, seTvSubst = tv_env, seCvSu
    1374 1379
           where
    
    1375 1380
             e' = GHC.Core.Subst.substExprSC (getFullSubst in_scope env) e
    
    1376 1381
     
    
    1382
    +simplCloExpr :: InScopeSet -> SimplClo -> OutExpr
    
    1383
    +-- Turn a SimplClo into an OutExpr, by applying the substitution
    
    1384
    +-- (if any) and the pending cast (if any)
    
    1385
    +simplCloExpr _        (DoneEx e _)       = e
    
    1386
    +simplCloExpr _        (DoneId v)         = Var v
    
    1387
    +simplCloExpr in_scope (ContEx env e mco) = mkCastMCo e' mco
    
    1388
    +  where
    
    1389
    +    e' = GHC.Core.Subst.substExpr (getFullSubst in_scope env) e
    
    1390
    +    -- NB: we use substExpr, not substExprSC: we want to get the benefit of
    
    1391
    +    --     knowing what is evaluated etc, via the in-scope set
    
    1392
    +
    
    1377 1393
     substTy :: HasDebugCallStack => SimplEnv -> Type -> Type
    
    1378 1394
     substTy env ty = Type.substTy (getTCvSubst env) ty
    
    1379 1395
     
    

  • compiler/GHC/Core/Opt/Simplify/Iteration.hs
    ... ... @@ -285,8 +285,8 @@ simplRecOrTopPair :: SimplEnv
    285 285
                       -> SimplM (SimplFloats, SimplEnv)
    
    286 286
     
    
    287 287
     simplRecOrTopPair env bind_cxt old_bndr new_bndr rhs
    
    288
    -  | Just env' <- preInlineUnconditionally env (bindContextLevel bind_cxt)
    
    289
    -                                          old_bndr (UnSimplified env) rhs MRefl
    
    288
    +  | Just env' <- preInlineLetUnconditionally env (bindContextLevel bind_cxt)
    
    289
    +                                             old_bndr rhs env
    
    290 290
       = {-#SCC "simplRecOrTopPair-pre-inline-uncond" #-}
    
    291 291
         simplTrace "SimplBindr:inline-uncond1" (ppr old_bndr) $
    
    292 292
         do { tick (PreInlineUnconditionally old_bndr)
    
    ... ... @@ -1264,9 +1264,9 @@ simplExprF1 env (App fun arg) cont
    1264 1264
               -- observed the quadratic behavior, so this extra entanglement
    
    1265 1265
               -- seems not worthwhile.
    
    1266 1266
             simplExprF env fun $
    
    1267
    -        ApplyToVal { sc_arg = arg, sc_env = UnSimplified env
    
    1267
    +        ApplyToVal { sc_arg = ContEx env arg MRefl, sc_dup = NoDup
    
    1268 1268
                        , sc_hole_ty = substTy env (exprType fun)
    
    1269
    -                   , sc_cast = MRefl, sc_cont = cont }
    
    1269
    +                   , sc_cont = cont }
    
    1270 1270
     
    
    1271 1271
     simplExprF1 env expr@(Lam {}) cont
    
    1272 1272
       = {-#SCC "simplExprF1-Lam" #-}
    
    ... ... @@ -1301,7 +1301,7 @@ simplExprF1 env (Let (NonRec bndr rhs) body) cont
    1301 1301
         do { ty' <- simplType env ty
    
    1302 1302
            ; simplExprF (extendTvSubst env bndr ty') body cont }
    
    1303 1303
     
    
    1304
    -  | Just env' <- preInlineUnconditionally env NotTopLevel bndr (UnSimplified env) rhs MRefl
    
    1304
    +  | Just env' <- preInlineLetUnconditionally env NotTopLevel bndr rhs env
    
    1305 1305
         -- Because of the let-can-float invariant, it's ok to
    
    1306 1306
         -- inline freely, or to drop the binding if it is dead.
    
    1307 1307
       = do { simplTrace "SimplBindr:inline-uncond2" (ppr bndr) $
    
    ... ... @@ -1637,9 +1637,8 @@ rebuild_go env expr cont
    1637 1637
           ApplyToTy  { sc_arg_ty = ty, sc_cont = cont}
    
    1638 1638
             -> rebuild_go env (App expr (Type ty)) cont
    
    1639 1639
     
    
    1640
    -      ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
    
    1641
    -                 , sc_cont = cont, sc_hole_ty = fun_ty }
    
    1642
    -        -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
    
    1640
    +      ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = fun_ty }
    
    1641
    +        -> do { arg' <- simplArg env Nothing fun_ty arg
    
    1643 1642
                   ; rebuild_go env (App expr arg') cont }
    
    1644 1643
     
    
    1645 1644
     completeBindX :: SimplEnv
    
    ... ... @@ -1653,6 +1652,8 @@ completeBindX env from_what bndr rhs body cont
    1653 1652
       | FromBeta arg_levity <- from_what
    
    1654 1653
       , needsCaseBindingL arg_levity rhs -- Enforcing the let-can-float-invariant
    
    1655 1654
       = do { (env1, bndr1)   <- simplNonRecBndr env bndr  -- Lambda binders don't have rules
    
    1655
    +                                                      -- See Note [Lambda and case binders have
    
    1656
    +                                                      --      vanilla IdInfo] in GHC.Core
    
    1656 1657
            ; (floats, expr') <- simplNonRecBody env1 from_what body cont
    
    1657 1658
            -- Do not float floats past the Case binder below
    
    1658 1659
            ; let expr'' = wrapFloats floats expr'
    
    ... ... @@ -1747,7 +1748,7 @@ on each successive composition -- that's at least quadratic. So:
    1747 1748
       duplicating a CastIt, optimise the coercion. Otherwise we'll end up
    
    1748 1749
       optimising it separately in the duplicate copies.
    
    1749 1750
     
    
    1750
    -* See also Note [The sc_cast field of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
    
    1751
    +* See also Note [The MOutCoercion field of ContEx] in GHC.Core.Opt.Simplify.Utils.
    
    1751 1752
     -}
    
    1752 1753
     
    
    1753 1754
     simplArg :: SimplEnvIS              -- ^ Used only for its InScopeSet
    
    ... ... @@ -1756,15 +1757,12 @@ simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
    1756 1757
                                         --   how `f` uses `ai`, affecting the Stop
    
    1757 1758
                                         --   continuation passed to 'simplExprC'
    
    1758 1759
              -> OutType                 -- ^ Type of the function applied to this arg
    
    1759
    -         -> StaticEnv -> CoreExpr   -- ^ Expression with its static envt
    
    1760
    -         -> MOutCoercion            -- Wrap this around the result
    
    1760
    +         -> SimplClo                -- ^ The argument
    
    1761 1761
              -> SimplM OutExpr
    
    1762
    -simplArg _ _ _ (Simplified {}) arg mco
    
    1763
    -  = -- See Note [Avoid repeated simplification]
    
    1764
    -    case mco of
    
    1765
    -       MRefl  -> return arg       -- Vastly common case
    
    1766
    -       MCo co -> return (mkCast arg co)
    
    1767
    -simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
    
    1762
    +-- See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils
    
    1763
    +simplArg _ _ _ (DoneEx arg _) = return arg  -- See Note [Avoid repeated simplification]
    
    1764
    +simplArg _ _ _ (DoneId v)     = return (Var v)
    
    1765
    +simplArg env mb_arg_info fun_ty (ContEx arg_se arg mco)
    
    1768 1766
       = do { let arg_env' = arg_se `setInScopeFromE` env
    
    1769 1767
                  arg_ty   = funArgTy fun_ty
    
    1770 1768
                  stop     = case mb_arg_info of
    
    ... ... @@ -1806,13 +1804,9 @@ simpl_lam env bndr body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
    1806 1804
     
    
    1807 1805
     -- Value beta-reduction
    
    1808 1806
     -- This works for /coercion/ lambdas too
    
    1809
    -simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
    
    1810
    -                                    , sc_cast = arg_mco, sc_cont = cont
    
    1807
    +simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_cont = cont
    
    1811 1808
                                         , sc_hole_ty = fun_ty})
    
    1812
    -  | Just env' <- preInlineUnconditionally env NotTopLevel bndr arg_se arg arg_mco
    
    1813
    -  , not (needsCaseBindingL arg_levity arg)
    
    1814
    -              -- Ok to test arg::InExpr in needsCaseBinding because
    
    1815
    -              -- exprOkForSpeculation is stable under simplification
    
    1809
    +  | Just env' <- preInlineBetaUnconditionally env arg_levity bndr arg
    
    1816 1810
       = simplTrace "SimplBindr:inline-uncond3"
    
    1817 1811
              (ppr bndr <+> text ":=" <+> ppr arg) $
    
    1818 1812
         do { tick (BetaReduction bndr)
    
    ... ... @@ -1823,14 +1817,14 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
    1823 1817
       = do { tick (BetaReduction bndr)
    
    1824 1818
            ; let from_what = FromBeta arg_levity
    
    1825 1819
     
    
    1826
    -       ; case (arg_se, arg_mco) of
    
    1827
    -           (UnSimplified arg_env, MRefl)
    
    1820
    +       ; case arg of
    
    1821
    +           ContEx arg_env arg_expr MRefl
    
    1828 1822
                  -- Optimisation: when there is no wrapping coercion use simplNonRecE
    
    1829 1823
                  -- so that the clever floating out of let-bindings can take place
    
    1830 1824
                  -- in this round of the Simplifier
    
    1831
    -             -> simplNonRecE env from_what bndr (arg, arg_env) body cont
    
    1825
    +             -> simplNonRecE env from_what bndr (arg_expr, arg_env) body cont
    
    1832 1826
     
    
    1833
    -           _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
    
    1827
    +           _ -> do { arg' <- simplArg env Nothing fun_ty arg
    
    1834 1828
                        ; completeBindX env from_what bndr arg' body cont }
    
    1835 1829
            }
    
    1836 1830
       where
    
    ... ... @@ -2262,11 +2256,14 @@ simplOutId env fun cont
    2262 2256
       | fun `hasKey` runRWKey
    
    2263 2257
       , ApplyToTy  { sc_cont = cont1 } <- cont
    
    2264 2258
       , ApplyToTy  { sc_cont = cont2, sc_arg_ty = hole_ty } <- cont1
    
    2265
    -  , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_cast = arg_mco
    
    2266
    -               , sc_env = arg_se, sc_hole_ty = fun_ty } <- cont2
    
    2259
    +  , ApplyToVal { sc_cont = cont3, sc_arg = arg_clo, sc_hole_ty = fun_ty } <- cont2
    
    2267 2260
       -- Do this even if (contIsStop cont), or if seCaseCase is off.
    
    2268 2261
       -- See Note [No eta-expansion in runRW#]
    
    2269
    -  = do { let (_saf,arg_env) = mkAltEnv env arg_se
    
    2262
    +  = do { let (arg_env, arg, arg_mco)
    
    2263
    +                = case arg_clo of
    
    2264
    +                    ContEx se e mco -> (se `setInScopeFromE` env, e, mco)
    
    2265
    +                    DoneEx e _      -> (env, e,     MRefl)
    
    2266
    +                    DoneId v        -> (env, Var v, MRefl)
    
    2270 2267
     
    
    2271 2268
                  overall_res_ty = contResultType cont3
    
    2272 2269
                  -- hole_ty is the type of the current runRW# application
    
    ... ... @@ -2281,23 +2278,32 @@ simplOutId env fun cont
    2281 2278
            --    * If we don't do this we get a beta-redex every time, so the
    
    2282 2279
            --      simplifier keeps doing more iterations.
    
    2283 2280
            --    * Even more important: see Note [No eta-expansion in runRW#]
    
    2281
    +       --
    
    2282
    +       -- But only if there is no pending cast on the argument (#27962);
    
    2283
    +       -- if there is, the general case below deals with it properly
    
    2284 2284
            ; arg' <- case arg of
    
    2285
    -           Lam s body -> do { (env', s') <- simplBinder arg_env s
    
    2286
    -                            ; body' <- simplExprC env' body inner_cont
    
    2287
    -                            ; return (Lam s' body') }
    
    2288
    -                            -- Important: do not try to eta-expand this lambda
    
    2289
    -                            -- See Note [No eta-expansion in runRW#]
    
    2285
    +           Lam s body
    
    2286
    +             | MRefl <- arg_mco
    
    2287
    +             -> do { (env', s') <- simplBinder arg_env s
    
    2288
    +                   ; body' <- simplExprC env' body inner_cont
    
    2289
    +                   ; return (Lam s' body') }
    
    2290
    +                   -- Important: do not try to eta-expand this lambda
    
    2291
    +                   -- See Note [No eta-expansion in runRW#]
    
    2290 2292
     
    
    2291 2293
                _ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
    
    2292 2294
                        ; let (m,_,_) = splitFunTy fun_ty
    
    2293 2295
                              env'  = arg_env `addNewInScopeIds` [s']
    
    2294 2296
                              hole_ty = mkVisFunTy m realWorldStatePrimTy new_runrw_res_ty
    
    2295 2297
                              cont' = pushCastMCo env' arg_mco $
    
    2296
    -                                 ApplyToVal { sc_arg = Var s', sc_cast = MRefl
    
    2297
    -                                            , sc_env = Simplified OkDup
    
    2298
    +                                 ApplyToVal { sc_arg = DoneEx (Var s') NotJoinPoint
    
    2299
    +                                            , sc_dup = dup
    
    2298 2300
                                                 , sc_cont = inner_cont
    
    2299 2301
                                                 , sc_hole_ty = hole_ty }
    
    2300 2302
                                      -- cont' applies to s', then K
    
    2303
    +                         -- The argument (Var s') is small, but inner_cont may not be
    
    2304
    +                         -- dupable; see (AV2) in Note [The argument of ApplyToVal]
    
    2305
    +                         dup | contIsDupable inner_cont = OkDup
    
    2306
    +                             | otherwise                = NoDup
    
    2301 2307
                        ; body' <- simplExprC env' arg cont'
    
    2302 2308
                        ; return (Lam s' body') }
    
    2303 2309
     
    
    ... ... @@ -2364,13 +2370,12 @@ rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_c
    2364 2370
     
    
    2365 2371
     ---------- Simplify value arguments --------------------
    
    2366 2372
     rebuildCall env fun_info
    
    2367
    -            (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
    
    2368
    -                        , sc_hole_ty = fun_ty, sc_cont = cont })
    
    2369
    -  | UnSimplified arg_env <- arg_se
    
    2373
    +            (ApplyToVal { sc_arg = arg, sc_hole_ty = fun_ty, sc_cont = cont })
    
    2374
    +  | ContEx arg_env arg_expr arg_mco <- arg
    
    2370 2375
       , isStrictArgInfo fun_info  -- Strict arguments
    
    2371 2376
       , seCaseCase env            -- But only when case-of-case is on.
    
    2372 2377
                                   -- See Note [Case-of-case and full laziness]
    
    2373
    -  = simplExprF (arg_env `setInScopeFromE` env) arg $
    
    2378
    +  = simplExprF (arg_env `setInScopeFromE` env) arg_expr $
    
    2374 2379
         addCastMCo arg_mco $
    
    2375 2380
         StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
    
    2376 2381
                   , sc_dup = NoDup
    
    ... ... @@ -2382,7 +2387,7 @@ rebuildCall env fun_info
    2382 2387
       -- There is no benefit (unlike in a let-binding), and we'd
    
    2383 2388
       -- have to be very careful about bogus strictness through
    
    2384 2389
       -- floating a demanded let.
    
    2385
    -  = do  { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
    
    2390
    +  = do  { arg' <- simplArg env (Just fun_info) fun_ty arg
    
    2386 2391
             ; rebuildCall env (addValArgTo fun_info  arg' fun_ty) cont }
    
    2387 2392
     
    
    2388 2393
     ---------- No further useful info, revert to generic rebuild ------------
    
    ... ... @@ -2530,11 +2535,11 @@ Then
    2530 2535
      * We simplify BIG before trying the rule; but the rule does not fire
    
    2531 2536
        (forcing this simplification is why we have the RULE in this example)
    
    2532 2537
      * We inline f = \x. g x, in `simpl_lam`
    
    2533
    - * So if `simpl_lam` did preInlineUnconditionally we get (g BIG)
    
    2538
    + * So if `simpl_lam` did preInlineBetaUnconditionally we get (g BIG)
    
    2534 2539
      * Now if g has a RULE we'll simplify BIG again, and this whole thing can
    
    2535 2540
        iterate.
    
    2536 2541
      * However, if `f` did not have a RULE, so that BIG has /not/ already been
    
    2537
    -   simplified, we /want/ to do preInlineUnconditionally in simpl_lam.
    
    2542
    +   simplified, we /want/ to do preInlineBetaUnconditionally in simpl_lam.
    
    2538 2543
     
    
    2539 2544
     So we go to some effort to avoid repeatedly simplifying the same thing.
    
    2540 2545
     Suppose we are in the Plan (AFTER) case of rule application, for a rule
    
    ... ... @@ -2543,8 +2548,9 @@ and a call
    2543 2548
           f (e1,e2)
    
    2544 2549
     Then:
    
    2545 2550
     
    
    2546
    -* The (sc_env :: StaticEnv) field of ApplyToVal records if the argument
    
    2547
    -  has been evaluated.  See Note [StaticEnv] in GHC.Core.Opt.Simplify.Utils.
    
    2551
    +* The (sc_arg :: SimplClo) field of ApplyToVal records if the argument
    
    2552
    +  has been simplified: it is a DoneEx if so, and a ContEx if not.
    
    2553
    +  See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
    
    2548 2554
     
    
    2549 2555
     * The rule fires returning
    
    2550 2556
          RuleMatch { rm_rhs = (\x y. ...x..), rm_args = [ e1, e2 ] }
    
    ... ... @@ -2557,17 +2563,17 @@ Then:
    2557 2563
       is the reason that `RuleMatch` separates the two.
    
    2558 2564
     
    
    2559 2565
     * `fireRuleAFTER` uses `pushOutArgs` to push [ e1, e2 ] back onto the
    
    2560
    -  continuation with sc_env=Simplified NoDup.
    
    2566
    +  continuation as (DoneEx e1) and (DoneEx e2).
    
    2561 2567
     
    
    2562 2568
     * Beta-reduction fires (in `simpl_lam`) for the \x.
    
    2563 2569
     
    
    2564 2570
     * Suppose `x` occurs many times.  Then we want to behave like `let x=e1 in ..`,
    
    2565
    -  but we use `simplArg`, which in turn uses that `sc_env` flag to avoid
    
    2571
    +  but we use `simplArg`, which in turn uses the DoneEx to avoid
    
    2566 2572
       re-simplifying `e1`.
    
    2567 2573
     
    
    2568 2574
     * Suppose `x` occurs just once or not at all; then the call to
    
    2569
    -  `preInlineUnconditionally` in `simpl_lam` will fire, and extend the
    
    2570
    -  substitution with
    
    2575
    +  `preInlineBetaUnconditionally` in `simpl_lam` will fire, and extend the
    
    2576
    +  substitution with the very same SimplClo
    
    2571 2577
           x :-> DoneEx e1
    
    2572 2578
     
    
    2573 2579
     * At the /occurrence/ of `x`, the function `simplInId` calls `simplOutExpr`
    
    ... ... @@ -2774,8 +2780,7 @@ trySeqRules in_env scrut rhs cont
    2774 2780
                      , ValArg { as_arg = no_cast_scrut
    
    2775 2781
                               , as_dmd = seqDmd
    
    2776 2782
                               , as_hole_ty = res3_ty } ]
    
    2777
    -    rule_cont = ApplyToVal { sc_env = UnSimplified in_env, sc_arg = rhs
    
    2778
    -                           , sc_cast = MRefl
    
    2783
    +    rule_cont = ApplyToVal { sc_arg = ContEx in_env rhs MRefl, sc_dup = NoDup
    
    2779 2784
                                , sc_cont = cont, sc_hole_ty = res4_ty }
    
    2780 2785
     
    
    2781 2786
         out_args = [Type rhs_rep, Type scrut_ty, Type rhs_ty, no_cast_scrut]
    
    ... ... @@ -3879,8 +3884,8 @@ knownCon env scrut dc dc_args case_bndr alt_bndrs rhs cont
    3879 3884
             return ( emptyFloats env
    
    3880 3885
                    , extendIdSubst env case_bndr (DoneEx scrut NotJoinPoint))
    
    3881 3886
     
    
    3882
    -      | Just env' <- preInlineUnconditionally env NotTopLevel case_bndr
    
    3883
    -                            (UnSimplified env) con_app MRefl
    
    3887
    +      | Just env' <- preInlineLetUnconditionally env NotTopLevel case_bndr
    
    3888
    +                                                 con_app env
    
    3884 3889
           = return (emptyFloats env', env')
    
    3885 3890
     
    
    3886 3891
           | otherwise
    
    ... ... @@ -4060,7 +4065,15 @@ mkDupableContWithDmds env _
    4060 4065
            ; let join_body = wrapFloats floats1 join_inner
    
    4061 4066
                  res_ty    = contResultType cont
    
    4062 4067
     
    
    4063
    -       ; mkDupableStrictBind env bndr' join_body res_ty }
    
    4068
    +       -- If bndr' has IdInfo that a lambda binder must not have,
    
    4069
    +       -- use a fresh lambda binder; see (DSB1) in Note [Duplicating StrictBind]
    
    4070
    +       ; (arg_bndr, join_body')
    
    4071
    +           <- if lamBndrInfoOK bndr'
    
    4072
    +              then return (bndr', join_body)
    
    4073
    +              else do { arg_bndr <- newId (fsLit "x") (idMult bndr') (idType bndr')
    
    4074
    +                      ; return (arg_bndr, Let (NonRec bndr' (Var arg_bndr)) join_body) }
    
    4075
    +
    
    4076
    +       ; mkDupableStrictBind env arg_bndr join_body' res_ty }
    
    4064 4077
     
    
    4065 4078
     mkDupableContWithDmds env _
    
    4066 4079
         (StrictArg { sc_fun = fun, sc_cont = cont
    
    ... ... @@ -4111,8 +4124,7 @@ mkDupableContWithDmds env dmds
    4111 4124
                                         , sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) }
    
    4112 4125
     
    
    4113 4126
     mkDupableContWithDmds env dmds
    
    4114
    -    (ApplyToVal { sc_arg = arg, sc_env = se, sc_cast = arg_mco
    
    4115
    -                , sc_cont = cont, sc_hole_ty = hole_ty })
    
    4127
    +    (ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = hole_ty })
    
    4116 4128
       =     -- e.g.         [...hole...] (...arg...)
    
    4117 4129
             --      ==>
    
    4118 4130
             --              let a = ...arg...
    
    ... ... @@ -4124,12 +4136,12 @@ mkDupableContWithDmds env dmds
    4124 4136
                     expectNonEmpty dmds
    
    4125 4137
             ; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
    
    4126 4138
             ; let env' = env `setInScopeFromF` floats1
    
    4127
    -        ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
    
    4139
    +        ; arg' <- simplArg env' Nothing hole_ty arg
    
    4128 4140
             ; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
    
    4129 4141
             ; let all_floats = floats1 `addLetFloats` let_floats2
    
    4130 4142
             ; return ( all_floats
    
    4131
    -                 , ApplyToVal { sc_arg = triv_arg, sc_env = Simplified OkDup
    
    4132
    -                              , sc_cast = MRefl, sc_cont = cont', sc_hole_ty = hole_ty }) }
    
    4143
    +                 , ApplyToVal { sc_arg = DoneEx triv_arg NotJoinPoint, sc_dup = OkDup
    
    4144
    +                              , sc_cont = cont', sc_hole_ty = hole_ty }) }
    
    4133 4145
     
    
    4134 4146
     mkDupableContWithDmds env _
    
    4135 4147
         (Select { sc_bndr = case_bndr, sc_alts = alts, sc_env = se, sc_cont = cont })
    
    ... ... @@ -4253,7 +4265,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
    4253 4265
                              | otherwise = v
    
    4254 4266
     
    
    4255 4267
                   -- No lambda binder has an unfolding, but (currently) case binders can,
    
    4256
    -              -- so we must zap them here.
    
    4268
    +              -- so we must zap them here.  But case binders never have a pragma,
    
    4269
    +              -- stable unfolding or RULES, so there is no need to zap those.
    
    4270
    +              -- See Note [Lambda and case binders have vanilla IdInfo] in GHC.Core
    
    4257 4271
                   join_rhs   = mkLams (map zapIdUnfolding final_bndrs) rhs_with_seqs
    
    4258 4272
     
    
    4259 4273
             ; join_bndr <- newJoinId filtered_binders rhs_ty'
    
    ... ... @@ -4660,6 +4674,20 @@ So we potentially make a join-point for the body, thus:
    4660 4674
     
    
    4661 4675
     Just like StrictArg in fact -- and indeed they share code.
    
    4662 4676
     
    
    4677
    +(DSB1) Lambda binders must not have a (non-default) inline pragma, a stable
    
    4678
    +  unfolding, or RULES; see Note [Lambda and case binders have vanilla IdInfo]
    
    4679
    +  in GHC.Core, and #27965.  But the let-binder `x` may well
    
    4680
    +  have them; e.g. in GHC.Internal.Control.Monad.ST.Lazy.Imp we have
    
    4681
    +       {-# NOINLINE res1 #-}
    
    4682
    +       !res1 = unST fm s
    
    4683
    +  So if `x` has such IdInfo, we use a fresh binder `x'` for the join point,
    
    4684
    +  and keep `x` as a let-binder, retaining all its IdInfo:
    
    4685
    +     let x = <> in b   ==>   join j x' = let x = x' in b
    
    4686
    +                             in j <>
    
    4687
    +  The hole is evaluated before the jump, so `x'` is a value, and `let x = x'`
    
    4688
    +  is just an alias.  We do this only when necessary, to avoid leaving an
    
    4689
    +  alias in the common case.
    
    4690
    +
    
    4663 4691
     Note [Join point abstraction]  Historical note
    
    4664 4692
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    4665 4693
     NB: This note is now historical, describing how (in the past) we used
    

  • compiler/GHC/Core/Opt/Simplify/Utils.hs
    ... ... @@ -12,7 +12,8 @@ module GHC.Core.Opt.Simplify.Utils (
    12 12
             tryEtaExpandRhs, wantEtaExpansion,
    
    13 13
     
    
    14 14
             -- Inlining,
    
    15
    -        preInlineUnconditionally, postInlineUnconditionally,
    
    15
    +        preInlineLetUnconditionally, preInlineBetaUnconditionally,
    
    16
    +        postInlineUnconditionally,
    
    16 17
             activeRule,
    
    17 18
             getUnfoldingInRuleMatch,
    
    18 19
             updModeForStableUnfoldings, updModeForRuleLHS, updModeForRuleRHS,
    
    ... ... @@ -180,10 +181,9 @@ data SimplCont
    180 181
       | ApplyToVal         -- (ApplyToVal arg K)[e] = K[ e arg ]
    
    181 182
           { sc_hole_ty :: OutType    -- Type of the function, presumably (forall a. blah)
    
    182 183
                                      -- See Note [The hole type in ApplyToTy]
    
    183
    -      , sc_env  :: StaticEnv     -- See Note [StaticEnv]
    
    184
    -      , sc_arg  :: CoreExpr      -- The argument
    
    185
    -      , sc_cast :: MOutCoercion  -- Wrap this OutCoercion around the (simplified) argument
    
    186
    -                                 -- See Note [The sc_cast field of ApplyToVal]
    
    184
    +      , sc_dup  :: DupFlag       -- See Note [The argument of ApplyToVal]
    
    185
    +      , sc_arg  :: SimplClo      -- The argument
    
    186
    +                                 -- Invariant: if sc_arg is a ContEx, then sc_dup = NoDup
    
    187 187
           , sc_cont :: SimplCont }
    
    188 188
     
    
    189 189
       | ApplyToTy          -- (ApplyToTy ty K)[e] = K[ e ty ]
    
    ... ... @@ -252,49 +252,85 @@ perhapsSubstTy (UnSimplified env) ty = substTy env ty
    252 252
     
    
    253 253
     {- Note [StaticEnv]
    
    254 254
     ~~~~~~~~~~~~~~~~~~~
    
    255
    -Consider ApplyToVal, which has
    
    256
    -    sc_env :: StaticEnv
    
    257
    -    sc_arg :: CoreExpr
    
    258
    -Initially, `sc_arg` is an un-simplified InExpr, and `sc_env` is (UnSimplified env),
    
    259
    -where `env` gives meaning to the free variables of `sc_arg`; in particular, `env`
    
    260
    -may have substitutions that must apply to the argument.
    
    261
    -
    
    262
    -But sometimes we simplify the argument, and in that case, `sc_arg` is an OutExpr,
    
    263
    -the simplified argument, and `sc_env` is (Simplified NoDup) or (Simplified OkDup).
    
    264
    -The former is the safe, conservative option, but in `mkDupableCont` we want to make
    
    265
    -the continuation duplicable, so we make the argument small and tag it with
    
    266
    -(Simplified OkDup).
    
    267
    -
    
    268
    -We later simplify the argument, e.g. in `simplArg`.  Then
    
    269
    -  * If sc_env is Simplified, it's a no-op
    
    270
    -  * If sc_env is (UnSimplified arg_env) we simplify `sc_arg` with
    
    271
    -     - Its captured envt `arg_env`
    
    255
    +Consider Select, which has
    
    256
    +    sc_env  :: StaticEnv
    
    257
    +    sc_bndr :: Id
    
    258
    +    sc_alts :: [CoreAlt]
    
    259
    +Initially, `sc_bndr` and `sc_alts` are un-simplified InThings, and `sc_env` is
    
    260
    +(UnSimplified env), where `env` gives meaning to their free variables; in
    
    261
    +particular, `env` may have substitutions that must apply to them.
    
    262
    +
    
    263
    +But sometimes (notably in `mkDupableCont`) we simplify them, and in that case
    
    264
    +`sc_bndr` and `sc_alts` are OutThings, and `sc_env` is (Simplified dup).
    
    265
    +
    
    266
    +When we finally simplify the alternatives (see `mkAltEnv`)
    
    267
    +  * If sc_env is Simplified, there is nothing to do
    
    268
    +  * If sc_env is (UnSimplified alt_env) we simplify them with
    
    269
    +     - Their captured envt `alt_env`
    
    272 270
          - but overriding its InScopeSet with the larger one at the
    
    273 271
            simplification point.
    
    274 272
         Why override the InScopeSet?  Example:
    
    275
    -          (let y = ey in f) ex
    
    276
    -    By the time we simplify ex, 'y' will be in scope.
    
    277
    -  All this is done in `simplArg`.
    
    273
    +          case (let y = ey in f) of alts
    
    274
    +    By the time we simplify alts, 'y' will be in scope.
    
    278 275
     
    
    279 276
     Note that:
    
    280 277
     
    
    281 278
     * In the Simplified case there is no environment, because the substitution has
    
    282 279
       already been applied.
    
    283 280
     
    
    284
    -* We say sc_arg :: CoreExpr, rather than sc_arg :: InExpr or sc_arg :: OutExpr,
    
    285
    -  because whether it is InExpr or OutExpr depends on `sc_env`
    
    281
    +* We say sc_alts :: [CoreAlt], rather than [InAlt] or [OutAlt],
    
    282
    +  because whether they are InAlts or OutAlts depends on `sc_env`
    
    286 283
     
    
    287
    -* Same deal for Select, and StrictBind, but the StaticEnv scopes over
    
    288
    -    * sc_bndr and sc_alts (for Select)
    
    289
    -    * sc_bndr and sc_body (for StrictBind)
    
    284
    +* Same deal for StrictBind, where the StaticEnv scopes over sc_bndr and sc_body.
    
    290 285
     
    
    291
    -* Even though the InScopeSet of an (UnSimplified se) is overridden in `simplArg`,
    
    292
    -  that InScopeSet is not irrelevant: it should include all the free vars of
    
    293
    -  applying the substitution to the InExpr. Reason: contHoleType uses perhapsSubstTy
    
    294
    -  to apply the substitution to the expression, and that (rightly) gives ASSERT
    
    295
    -  failures if the InScopeSet isn't big enough.
    
    286
    +* ApplyToVal is similar, but simpler: it uses a SimplClo instead.
    
    287
    +  See Note [The argument of ApplyToVal].
    
    288
    +
    
    289
    +* Even though the InScopeSet of an (UnSimplified se) is overridden, that
    
    290
    +  InScopeSet is not irrelevant: it should include all the free vars of
    
    291
    +  applying the substitution to the InThing. Reason: contHoleType uses
    
    292
    +  perhapsSubstTy to apply the substitution to the binder, and that
    
    293
    +  (rightly) gives ASSERT failures if the InScopeSet isn't big enough.
    
    296 294
     
    
    297 295
     (SE1) If dup = OkToDup, then continuation k is also ok-to-dup
    
    296
    +
    
    297
    +Note [The argument of ApplyToVal]
    
    298
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    299
    +ApplyToVal has
    
    300
    +    sc_dup :: DupFlag
    
    301
    +    sc_arg :: SimplClo
    
    302
    +
    
    303
    +Initially, `sc_arg` is (ContEx env arg MRefl), where `arg` is the un-simplified
    
    304
    +InExpr, and `env` gives meaning to the free variables of `arg`; in particular,
    
    305
    +`env` may have substitutions that must apply to the argument.
    
    306
    +
    
    307
    +But sometimes we simplify the argument, and in that case, `sc_arg` is
    
    308
    +(DoneEx arg' NotJoinPoint), where `arg'` is the simplified argument.
    
    309
    +
    
    310
    +The `sc_dup` flag says whether the continuation can be duplicated.  NoDup is
    
    311
    +the safe, conservative option, but in `mkDupableCont` we want to make the
    
    312
    +continuation duplicable, so we make the argument small (and hence a DoneEx)
    
    313
    +and set `sc_dup` to OkDup.  Invariants:
    
    314
    +
    
    315
    +  (AV1) If `sc_arg` is a ContEx, then `sc_dup` is NoDup.
    
    316
    +
    
    317
    +  (AV2) If `sc_dup` is OkDup then `sc_cont` is also ok-to-dup; see (SE1)
    
    318
    +        in Note [StaticEnv].
    
    319
    +
    
    320
    +We later simplify the argument, in `simplArg`.  Then
    
    321
    +  * If `sc_arg` is a DoneEx (or DoneId), it's a no-op
    
    322
    +  * If `sc_arg` is (ContEx arg_env arg mco) we simplify `arg` with
    
    323
    +     - Its captured envt `arg_env`
    
    324
    +     - but overriding its InScopeSet with the larger one at the
    
    325
    +       simplification point.
    
    326
    +    Why override the InScopeSet?  Example:
    
    327
    +          (let y = ey in f) ex
    
    328
    +    By the time we simplify ex, 'y' will be in scope.
    
    329
    +    Then we wrap the cast `mco` around the result.
    
    330
    +    See Note [The MOutCoercion field of ContEx].
    
    331
    +
    
    332
    +Using a SimplClo for the argument means that it can be substituted for a lambda
    
    333
    +binder, in `preInlineBetaUnconditionally`, without further ado.
    
    298 334
     -}
    
    299 335
     
    
    300 336
     instance Outputable DupFlag where
    
    ... ... @@ -312,9 +348,9 @@ instance Outputable SimplCont where
    312 348
         = (text "TickIt" <+> ppr t) $$ ppr cont
    
    313 349
       ppr (ApplyToTy  { sc_arg_ty = ty, sc_cont = cont })
    
    314 350
         = (text "ApplyToTy" <+> pprParendType ty) $$ ppr cont
    
    315
    -  ppr (ApplyToVal { sc_arg = arg, sc_env = env, sc_cont = cont, sc_hole_ty = hole_ty })
    
    316
    -    = (hang (text "ApplyToVal" <> braces (ppr env) <+> text "hole-ty:" <+> pprParendType hole_ty)
    
    317
    -          2 (pprParendExpr arg))
    
    351
    +  ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont, sc_hole_ty = hole_ty })
    
    352
    +    = (hang (text "ApplyToVal" <> braces (ppr dup) <+> text "hole-ty:" <+> pprParendType hole_ty)
    
    353
    +          2 (ppr arg))
    
    318 354
           $$ ppr cont
    
    319 355
       ppr (StrictBind { sc_bndr = b, sc_cont = cont })
    
    320 356
         = (text "StrictBind" <+> ppr b) $$ ppr cont
    
    ... ... @@ -433,8 +469,8 @@ pushOutArgs fun_ty (arg:args) cont
    433 469
       = ApplyToTy { sc_hole_ty = fun_ty, sc_arg_ty = ty
    
    434 470
                   , sc_cont = pushOutArgs (piResultTy fun_ty ty) args cont }
    
    435 471
       | otherwise
    
    436
    -  = ApplyToVal { sc_hole_ty = fun_ty, sc_cast = MRefl
    
    437
    -               , sc_arg = arg, sc_env = Simplified NoDup
    
    472
    +  = ApplyToVal { sc_hole_ty = fun_ty
    
    473
    +               , sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
    
    438 474
                    , sc_cont = pushOutArgs (funResultTy fun_ty) args  cont}
    
    439 475
     
    
    440 476
     pushArgSpecs :: [ArgSpec]   -- In normal, forward order
    
    ... ... @@ -445,7 +481,7 @@ pushArgSpec :: ArgSpec -> SimplCont -> SimplCont
    445 481
     pushArgSpec (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }) cont
    
    446 482
       = ApplyToTy  { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont }
    
    447 483
     pushArgSpec (ValArg { as_arg = arg, as_hole_ty = hole_ty }) cont
    
    448
    -  = ApplyToVal { sc_arg = arg, sc_env = Simplified NoDup, sc_cast = MRefl
    
    484
    +  = ApplyToVal { sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
    
    449 485
                    , sc_hole_ty = hole_ty, sc_cont = cont }
    
    450 486
     
    
    451 487
     argSpecArg :: ArgSpec -> OutExpr
    
    ... ... @@ -496,7 +532,12 @@ contIsStop _ = False
    496 532
     contIsDupable :: SimplCont -> Bool
    
    497 533
     contIsDupable (Stop {})                    = True
    
    498 534
     contIsDupable (ApplyToTy  { sc_cont = k }) = contIsDupable k
    
    499
    -contIsDupable (ApplyToVal { sc_env = se }) = okToDupSE se -- See (SE1) in Note [StaticEnv]
    
    535
    +contIsDupable (ApplyToVal { sc_dup = dup, sc_arg = arg })
    
    536
    +  = assertPpr (not (okToDup dup && is_cont_ex arg)) (ppr arg) $
    
    537
    +    okToDup dup -- See (AV1,AV2) in Note [The argument of ApplyToVal]
    
    538
    +  where
    
    539
    +    is_cont_ex (ContEx {}) = True
    
    540
    +    is_cont_ex _           = False
    
    500 541
     contIsDupable (Select { sc_env = se })     = okToDupSE se -- ...ditto...
    
    501 542
     contIsDupable (StrictBind { sc_env = se }) = okToDupSE se -- ...ditto...
    
    502 543
     contIsDupable (StrictArg { sc_dup = dup }) = okToDup dup  -- ...ditto...
    
    ... ... @@ -605,8 +646,8 @@ contArgs env cont
    605 646
         lone (CastIt {})     = False  --     stops it being "lone"
    
    606 647
         lone _               = True
    
    607 648
     
    
    608
    -    go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k })
    
    609
    -                                        = go (interestingArg env se arg : args) k
    
    649
    +    go args (ApplyToVal { sc_arg = arg, sc_cont = k })
    
    650
    +                                        = go (interestingArg env arg : args) k
    
    610 651
         go args (ApplyToTy { sc_cont = k }) = go args k
    
    611 652
         go args (CastIt { sc_cont = k })    = go args k
    
    612 653
         go args k                           = (False, reverse args, k)
    
    ... ... @@ -621,15 +662,13 @@ contOutArgs env cont
    621 662
         go (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
    
    622 663
           = Type ty : go cont
    
    623 664
     
    
    624
    -    go (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = cont })
    
    625
    -      = case se of
    
    626
    -          Simplified {}    -> arg : go cont
    
    627
    -          UnSimplified env -> GHC.Core.Subst.substExpr (getFullSubst in_scope env) arg : go cont
    
    628
    -        -- Make sure we apply the static environment `sc_env` as a substitution
    
    665
    +    go (ApplyToVal { sc_arg = arg, sc_cont = cont })
    
    666
    +      = simplCloExpr in_scope arg : go cont
    
    667
    +        -- Make sure we apply the static environment of a ContEx as a substitution
    
    629 668
             --   to get an OutExpr.  See (BF1) in Note [tryRules: plan (BEFORE)]
    
    630 669
             --   in GHC.Core.Opt.Simplify.Iteration
    
    631
    -        -- NB: we use substExpr, not substExprSC: we want to get the benefit of
    
    632
    -        --     knowing what is evaluated etc, via the in-scope set
    
    670
    +        -- simplCloExpr also wraps the pending cast (if any) around the argument;
    
    671
    +        --   omitting it can make a rule fail to match (#27963)
    
    633 672
     
    
    634 673
         -- No more arguments
    
    635 674
         go _ = []
    
    ... ... @@ -826,19 +865,27 @@ make use of the strictness info for the function.
    826 865
     *                                                                      *
    
    827 866
     ********************************************************************* -}
    
    828 867
     
    
    829
    -{- Note [The sc_cast field of ApplyToVal]
    
    830
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    868
    +{- Note [The MOutCoercion field of ContEx]
    
    869
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    831 870
     In the `ApplyToVal` case of `pushCast` we want to push an `OutCoercion` into the
    
    832
    -argument.  But the argument may or may not have been simplified (see Note [StaticEnv])
    
    833
    -so we definitely can't just wrap the cast around the argument. Instead we store it
    
    834
    -in the `sc_cast` field -- this is the whole reason for the `sc_cast` field.
    
    871
    +argument.  But the argument may or may not have been simplified (see Note [The
    
    872
    +argument of ApplyToVal]):
    
    873
    +
    
    874
    +* If it has been simplified, it is (DoneEx arg' _), and we can simply wrap the
    
    875
    +  cast around `arg'`.
    
    876
    +
    
    877
    +* If it has not, it is (ContEx env arg mco), and we definitely can't just wrap
    
    878
    +  the (Out)cast around the InExpr `arg`. Instead we compose it with `mco` --
    
    879
    +  this is the whole reason for the MOutCoercion field of `ContEx`.
    
    880
    +
    
    881
    +All this is done by `mkCloCastMCo`.
    
    835 882
     
    
    836 883
     We deal with that pending cast mainly in `simplArg`.
    
    837 884
     
    
    838 885
     But we /also/ sometimes want to substitute that argument for a lambda-binder, in
    
    839
    -`preInlineUnconditionally`.  So we also have to put that pending cast into
    
    840
    -`ContEx`; hence the MOutCoercion field of `ContEx`.  Then we deal with it
    
    841
    -appropriately when /applying/ the substitution in `simplInId`.
    
    886
    +`preInlineBetaUnconditionally`; and since the substitution maps an Id to a SimplClo,
    
    887
    +the pending cast comes along for free.  Then we deal with it appropriately when
    
    888
    +/applying/ the substitution in `simplInId`.
    
    842 889
     -}
    
    843 890
     
    
    844 891
     optOutCoercion :: SimplEnvIS -> OutCoercion -> Bool -> OutCoercion
    
    ... ... @@ -886,21 +933,17 @@ pushCast env co cont
    886 933
         -- where   co :: (s1->s2) ~ (t1->t2)
    
    887 934
         --         co1 :: t1 ~ s1
    
    888 935
         --         co2 :: s2 ~ t2
    
    889
    -    go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_env = arg_se
    
    890
    -                                     , sc_cast = arg_mco, sc_cont = tail })
    
    936
    +    go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_cont = tail })
    
    891 937
           | not co_is_opt
    
    892 938
           = -- pushCoValArg duplicates the coercion, so optimise first
    
    893 939
             go (optOutCoercion (zapSubstEnv env) co co_is_opt) True cont
    
    894 940
     
    
    895 941
           | Just (tyL, m_co1, m_co2) <- pushCoValArg co
    
    896 942
           = {-#SCC "addCoerce-pushCoValArg" #-}
    
    897
    -        -- Dealing with m_co1 is the entire reason for the sc_cast field
    
    898
    -        -- of ApplyToVal; see Note [The sc_cast field of ApplyToVal]
    
    899
    -        ApplyToVal { sc_arg  = arg
    
    900
    -                   , sc_env  = arg_se
    
    901
    -                   , sc_cast = arg_mco `mkTransMCo` m_co1
    
    902
    -                   , sc_cont = go_mco m_co2 True tail
    
    903
    -                   , sc_hole_ty = tyL }
    
    943
    +        -- See Note [The MOutCoercion field of ContEx]
    
    944
    +        cont { sc_arg     = mkCloCastMCo arg m_co1
    
    945
    +             , sc_cont    = go_mco m_co2 True tail
    
    946
    +             , sc_hole_ty = tyL }
    
    904 947
     
    
    905 948
         go co co_is_opt cont
    
    906 949
           | isReflCo co = cont  -- Having this at the end makes a huge
    
    ... ... @@ -914,6 +957,13 @@ pushCast env co cont
    914 957
         go_mco MRefl    _   cont = cont
    
    915 958
         go_mco (MCo co) opt cont = go co opt cont
    
    916 959
     
    
    960
    +mkCloCastMCo :: SimplClo -> MOutCoercion -> SimplClo
    
    961
    +-- See Note [The MOutCoercion field of ContEx]
    
    962
    +mkCloCastMCo clo               MRefl    = clo
    
    963
    +mkCloCastMCo (DoneId v)        (MCo co) = DoneEx (mkCast (Var v) co) NotJoinPoint
    
    964
    +mkCloCastMCo (DoneEx e _)      (MCo co) = DoneEx (mkCast e co)       NotJoinPoint
    
    965
    +mkCloCastMCo (ContEx se e mco) (MCo co) = ContEx se e (mco `mkTransMCo` MCo co)
    
    966
    +
    
    917 967
     
    
    918 968
     {-
    
    919 969
     ************************************************************************
    
    ... ... @@ -1227,19 +1277,17 @@ Wrinkles:
    1227 1277
     
    
    1228 1278
     -}
    
    1229 1279
     
    
    1230
    -interestingArg :: SimplEnv -> StaticEnv -> CoreExpr -> ArgSummary
    
    1280
    +interestingArg :: SimplEnv -> SimplClo -> ArgSummary
    
    1231 1281
     -- See Note [Interesting arguments]
    
    1232
    -interestingArg env se e
    
    1233
    -  = case se of
    
    1234
    -      Simplified {}           -> go env                                0 e
    
    1235
    -      UnSimplified static_env -> go (static_env `setInScopeFromE` env) 0 e
    
    1282
    +interestingArg env clo
    
    1283
    +  = go_clo env 0 clo
    
    1236 1284
       where
    
    1285
    +    go_clo _   n (DoneId v)       = go_var n v
    
    1286
    +    go_clo env n (DoneEx e _)     = go (zapSubstEnv env)          n e
    
    1287
    +    go_clo env n (ContEx se e _)  = go (se `setInScopeFromE` env) n e
    
    1288
    +
    
    1237 1289
         -- n is # value args to which the expression is applied
    
    1238
    -    go env n (Var v)
    
    1239
    -       = case substId env v of
    
    1240
    -           DoneId v'            -> go_var n v'
    
    1241
    -           DoneEx e _           -> go (zapSubstEnv env)          n e
    
    1242
    -           ContEx se e _mco     -> go (se `setInScopeFromE` env) n e
    
    1290
    +    go env n (Var v) = go_clo env n (substId env v)
    
    1243 1291
     
    
    1244 1292
         go _   _ (Lit l)
    
    1245 1293
            | isLitRubbish l        = NonTrivArg -- See (IA3) in Note [Interesting arguments]
    
    ... ... @@ -1738,15 +1786,15 @@ is a term (not a coercion) so we can't necessarily inline the latter in
    1738 1786
     the former.
    
    1739 1787
     -}
    
    1740 1788
     
    
    1741
    -preInlineUnconditionally
    
    1789
    +preInlineLetUnconditionally
    
    1742 1790
         :: SimplEnv -> TopLevelFlag -> InId
    
    1743
    -    -> StaticEnv -> CoreExpr -> MOutCoercion  -- The argument
    
    1791
    +    -> InExpr -> SimplEnv   -- These two go together
    
    1744 1792
         -> Maybe SimplEnv       -- Returned env has extended substitution
    
    1745 1793
     -- Precondition: rhs satisfies the let-can-float invariant
    
    1746 1794
     -- See Note [Core let-can-float invariant] in GHC.Core
    
    1747 1795
     -- Reason: we don't want to inline single uses, or discard dead bindings,
    
    1748 1796
     --         for unlifted, side-effect-ful bindings
    
    1749
    -preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
    
    1797
    +preInlineLetUnconditionally env top_lvl bndr rhs rhs_env
    
    1750 1798
       | not pre_inline_unconditionally           = Nothing
    
    1751 1799
       | not active                               = Nothing
    
    1752 1800
       | isTopLevel top_lvl && isDeadEndId bndr   = Nothing -- Note [Top-level bottoming Ids]
    
    ... ... @@ -1758,26 +1806,15 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
    1758 1806
     
    
    1759 1807
       -- See Note [Stable unfoldings and preInlineUnconditionally]
    
    1760 1808
       | not (isInlinePragma inline_prag)
    
    1761
    -  , Just inl <- maybeUnfoldingTemplate unf   = assertPpr (isReflMCo rhs_mco) (ppr bndr) $
    
    1762
    -                                               Just $! (extend_subst_with inl)
    
    1809
    +  , Just inl <- maybeUnfoldingTemplate unf   = Just $! (extend_subst_with inl)
    
    1763 1810
     
    
    1764 1811
       | otherwise                                = Nothing
    
    1765 1812
       where
    
    1766 1813
         unf = idUnfolding bndr
    
    1767 1814
     
    
    1768
    -    -- If the rhs is /not/ already simplified, extend the envt with ContEx, which captures
    
    1769
    -    --    the the lexical environment for us to restore in `simplInId`.
    
    1770
    -    -- If the rhs /is/ already simplified, then extend the envt with DoneEx;
    
    1771
    -    --    That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
    
    1772
    -    --    the RHS.
    
    1773
    -    -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
    
    1774
    -    extend_subst_with inl_rhs
    
    1775
    -      = extendIdSubst env bndr $!
    
    1776
    -        case rhs_se of
    
    1777
    -          Simplified _ -> case rhs_mco of
    
    1778
    -                             MRefl  -> DoneEx inl_rhs NotJoinPoint -- Common case
    
    1779
    -                             MCo co -> DoneEx (mkCast inl_rhs co) NotJoinPoint
    
    1780
    -          UnSimplified rhs_env -> ContEx rhs_env inl_rhs rhs_mco
    
    1815
    +    -- The rhs is not yet simplified, so extend the envt with ContEx, which
    
    1816
    +    -- captures the lexical environment for us to restore in `simplInId`.
    
    1817
    +    extend_subst_with inl_rhs = extendIdSubst env bndr $! ContEx rhs_env inl_rhs MRefl
    
    1781 1818
     
    
    1782 1819
         one_occ IAmDead = True -- Happens in ((\x.1) v)
    
    1783 1820
         one_occ OneOcc{ occ_n_br   = 1
    
    ... ... @@ -1793,39 +1830,6 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
    1793 1830
                  -- See Note [pre/postInlineUnconditionally in gentle mode]
    
    1794 1831
         inline_prag = idInlinePragma bndr
    
    1795 1832
     
    
    1796
    --- Be very careful before inlining inside a lambda, because (a) we must not
    
    1797
    --- invalidate occurrence information, and (b) we want to avoid pushing a
    
    1798
    --- single allocation (here) into multiple allocations (inside lambda).
    
    1799
    --- Inlining a *function* with a single *saturated* call would be ok, mind you.
    
    1800
    ---      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
    
    1801
    ---      where
    
    1802
    ---              is_cheap = exprIsCheap rhs
    
    1803
    ---              ok = is_cheap && int_cxt
    
    1804
    -
    
    1805
    -        --      int_cxt         The context isn't totally boring
    
    1806
    -        -- E.g. let f = \ab.BIG in \y. map f xs
    
    1807
    -        --      Don't want to substitute for f, because then we allocate
    
    1808
    -        --      its closure every time the \y is called
    
    1809
    -        -- But: let f = \ab.BIG in \y. map (f y) xs
    
    1810
    -        --      Now we do want to substitute for f, even though it's not
    
    1811
    -        --      saturated, because we're going to allocate a closure for
    
    1812
    -        --      (f y) every time round the loop anyhow.
    
    1813
    -
    
    1814
    -        -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
    
    1815
    -        -- so substituting rhs inside a lambda doesn't change the occ info.
    
    1816
    -        -- Sadly, not quite the same as exprIsHNF.
    
    1817
    -    canInlineInLam (Lit _)    = True
    
    1818
    -    canInlineInLam (Cast e _) = canInlineInLam e
    
    1819
    -    canInlineInLam (Lam b e)  = isRuntimeVar b || canInlineInLam e
    
    1820
    -    canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
    
    1821
    -    canInlineInLam (Var v)    = case idOccInfo v of
    
    1822
    -                                  OneOcc { occ_in_lam = IsInsideLam } -> True
    
    1823
    -                                  ManyOccs {}                         -> True
    
    1824
    -                                  _                                   -> False
    
    1825
    -    canInlineInLam _          = False
    
    1826
    -      -- not ticks.  Counting ticks cannot be duplicated, and non-counting
    
    1827
    -      -- ticks around a Lam will disappear anyway.
    
    1828
    -
    
    1829 1833
         early_phase =
    
    1830 1834
           case sePhase env of
    
    1831 1835
             SimplPhase p -> p /= FinalPhase
    
    ... ... @@ -1856,6 +1860,90 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
    1856 1860
         -- (Nor can we check for `exprIsExpandable rhs`, because that needs to look
    
    1857 1861
         -- at the non-existent unfolding for the `I# 2#` which is also floated out.)
    
    1858 1862
     
    
    1863
    +preInlineBetaUnconditionally
    
    1864
    +    :: SimplEnv -> Levity -> InId
    
    1865
    +    -> SimplClo             -- The argument
    
    1866
    +    -> Maybe SimplEnv       -- Returned env has extended substitution
    
    1867
    +-- Like preInlineLetUnconditionally, but for a beta-redex (\bndr. body) arg
    
    1868
    +-- The argument may or may not be already simplified (DoneEx or ContEx)
    
    1869
    +--
    
    1870
    +-- Compared to preInlineLetUnconditionally we omit some checks:
    
    1871
    +--   * The binder is never top-level, so no need for the
    
    1872
    +--     Note [Top-level bottoming Ids] check, nor for `early_phase`
    
    1873
    +--   * A lambda binder is never a join point, so no need for the
    
    1874
    +--     Note [Do not inline exit join points] check
    
    1875
    +--   * A lambda binder never has an inline pragma, a stable unfolding, or RULES
    
    1876
    +--     (see `lamBndrInfoOK`), so no need to check activation, nor for
    
    1877
    +--     Note [Stable unfoldings and preInlineUnconditionally]
    
    1878
    +preInlineBetaUnconditionally env levity bndr arg
    
    1879
    +  | assertPpr (lamBndrInfoOK bndr) (ppr bndr) $
    
    1880
    +    not pre_inline_unconditionally           = Nothing
    
    1881
    +  | isCoVar bndr                             = Nothing -- Note [Do not inline CoVars unconditionally]
    
    1882
    +  | not (one_occ (idOccInfo bndr))           = Nothing
    
    1883
    +  | needs_case_binding                       = Nothing
    
    1884
    +  | otherwise                                = Just $! extendIdSubst env bndr arg
    
    1885
    +    -- If the arg is not yet simplified, it is a ContEx, which captures the
    
    1886
    +    --    lexical environment for us to restore in `simplInId`.
    
    1887
    +    -- If the arg is already simplified, then it is a DoneEx;
    
    1888
    +    --    That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
    
    1889
    +    --    the arg.
    
    1890
    +    -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
    
    1891
    +  where
    
    1892
    +    pre_inline_unconditionally = sePreInline env
    
    1893
    +
    
    1894
    +    one_occ IAmDead = True -- Happens in ((\x.1) v)
    
    1895
    +    one_occ OneOcc{ occ_n_br   = 1
    
    1896
    +                  , occ_in_lam = NotInsideLam }   = True
    
    1897
    +    one_occ OneOcc{ occ_n_br   = 1
    
    1898
    +                  , occ_in_lam = IsInsideLam
    
    1899
    +                  , occ_int_cxt = IsInteresting } = case arg of
    
    1900
    +                                                      ContEx _ e _ -> canInlineInLam e
    
    1901
    +                                                      DoneEx e _   -> canInlineInLam e
    
    1902
    +                                                      DoneId v     -> canInlineInLam (Var v)
    
    1903
    +    one_occ _                                     = False
    
    1904
    +
    
    1905
    +    -- Enforce the let-can-float invariant
    
    1906
    +    -- Ok to test an InExpr in needsCaseBinding because
    
    1907
    +    -- exprOkForSpeculation is stable under simplification
    
    1908
    +    needs_case_binding = case arg of
    
    1909
    +                           ContEx _ e _ -> needsCaseBindingL levity e
    
    1910
    +                           DoneEx e _   -> needsCaseBindingL levity e
    
    1911
    +                           DoneId v     -> needsCaseBindingL levity (Var v)
    
    1912
    +
    
    1913
    +canInlineInLam :: CoreExpr -> Bool
    
    1914
    +-- Be very careful before inlining inside a lambda, because (a) we must not
    
    1915
    +-- invalidate occurrence information, and (b) we want to avoid pushing a
    
    1916
    +-- single allocation (here) into multiple allocations (inside lambda).
    
    1917
    +-- Inlining a *function* with a single *saturated* call would be ok, mind you.
    
    1918
    +--      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
    
    1919
    +--      where
    
    1920
    +--              is_cheap = exprIsCheap rhs
    
    1921
    +--              ok = is_cheap && int_cxt
    
    1922
    +
    
    1923
    +        --      int_cxt         The context isn't totally boring
    
    1924
    +        -- E.g. let f = \ab.BIG in \y. map f xs
    
    1925
    +        --      Don't want to substitute for f, because then we allocate
    
    1926
    +        --      its closure every time the \y is called
    
    1927
    +        -- But: let f = \ab.BIG in \y. map (f y) xs
    
    1928
    +        --      Now we do want to substitute for f, even though it's not
    
    1929
    +        --      saturated, because we're going to allocate a closure for
    
    1930
    +        --      (f y) every time round the loop anyhow.
    
    1931
    +
    
    1932
    +        -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
    
    1933
    +        -- so substituting rhs inside a lambda doesn't change the occ info.
    
    1934
    +        -- Sadly, not quite the same as exprIsHNF.
    
    1935
    +canInlineInLam (Lit _)    = True
    
    1936
    +canInlineInLam (Cast e _) = canInlineInLam e
    
    1937
    +canInlineInLam (Lam b e)  = isRuntimeVar b || canInlineInLam e
    
    1938
    +canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
    
    1939
    +canInlineInLam (Var v)    = case idOccInfo v of
    
    1940
    +                              OneOcc { occ_in_lam = IsInsideLam } -> True
    
    1941
    +                              ManyOccs {}                         -> True
    
    1942
    +                              _                                   -> False
    
    1943
    +canInlineInLam _          = False
    
    1944
    +  -- not ticks.  Counting ticks cannot be duplicated, and non-counting
    
    1945
    +  -- ticks around a Lam will disappear anyway.
    
    1946
    +
    
    1859 1947
     {-
    
    1860 1948
     ************************************************************************
    
    1861 1949
     *                                                                      *
    

  • compiler/GHC/HsToCore/Utils.hs
    ... ... @@ -57,6 +57,7 @@ import GHC.Core.Make
    57 57
     import GHC.Core.Make.Box ( boxTy )
    
    58 58
     import GHC.Core.Make.BigTuple
    
    59 59
     import GHC.Types.Id
    
    60
    +import GHC.Types.Id.Info ( vanillaIdInfo )
    
    60 61
     import GHC.Types.Literal
    
    61 62
     import GHC.Core.TyCon
    
    62 63
     import GHC.Core.DataCon
    
    ... ... @@ -264,8 +265,14 @@ bindMatchId new mid body
    264 265
     -- Used to force variables when desugaring strict binders. It's crucial that the
    
    265 266
     -- variable is shadowed by the case binder. See Wrinkle 1 in
    
    266 267
     -- Note [Desugar Strict binds] in GHC.HsToCore.Binds.
    
    268
    +--
    
    269
    +-- The case binder has the same Name (and hence Unique), type and multiplicity
    
    270
    +-- as `var`, but vanilla IdInfo: `var` may have, say, a NOINLINE pragma, but a
    
    271
    +-- case binder must not; see Note [Lambda and case binders have vanilla IdInfo]
    
    272
    +-- in GHC.Core, and #27965.  E.g. `res1` in GHC.Internal.Control.Monad.ST.Lazy.Imp
    
    273
    +-- has a NOINLINE pragma.
    
    267 274
     seqVar :: Var -> CoreExpr -> CoreExpr
    
    268
    -seqVar var body = mkDefaultCase (Var var) var body
    
    275
    +seqVar var body = mkDefaultCase (Var var) (var `setIdInfo` vanillaIdInfo) body
    
    269 276
     
    
    270 277
     mkCoLetMatchResult :: HasDebugCallStack => CoreBind -> MatchResult CoreExpr -> MatchResult CoreExpr
    
    271 278
     mkCoLetMatchResult bind = fmap (mkCoreLet bind)
    

  • compiler/GHC/Types/Id.hs
    ... ... @@ -94,6 +94,7 @@ module GHC.Types.Id (
    94 94
             idArity,
    
    95 95
             idCallArity, idFunRepArity,
    
    96 96
             idSpecialisation, idCoreRules, idHasRules,
    
    97
    +        lamBndrInfoOK,
    
    97 98
             idCafInfo, idLFInfo_maybe,
    
    98 99
             idOneShotInfo,
    
    99 100
             idOccInfo,
    
    ... ... @@ -905,6 +906,16 @@ idCoreRules id = ruleInfoRules (idSpecialisation id)
    905 906
     idHasRules :: Id -> Bool
    
    906 907
     idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
    
    907 908
     
    
    909
    +-- | True <=> the Id has no (non-default) inline pragma, no stable unfolding,
    
    910
    +-- and no RULES.  Lambda binders, case binders, and case-alternative binders
    
    911
    +-- must all satisfy this.
    
    912
    +-- See Note [Lambda and case binders have vanilla IdInfo] in GHC.Core
    
    913
    +lamBndrInfoOK :: Id -> Bool
    
    914
    +lamBndrInfoOK id
    
    915
    +  =  isDefaultInlinePragma (idInlinePragma id)
    
    916
    +  && not (isStableUnfolding (realIdUnfolding id))
    
    917
    +  && not (idHasRules id)
    
    918
    +
    
    908 919
     setIdSpecialisation :: Id -> RuleInfo -> Id
    
    909 920
     setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
    
    910 921
     
    

  • testsuite/tests/simplCore/should_compile/T27962.hs
    1
    +{-# LANGUAGE MagicHash #-}
    
    2
    +
    
    3
    +module T27962 where
    
    4
    +
    
    5
    +import GHC.Exts
    
    6
    +
    
    7
    +newtype N = MkN Int
    
    8
    +
    
    9
    +-- After inlining myRun, we get  (runRW# @LiftedRep @Int |> co) (\_ -> ...)
    
    10
    +-- and the simplifier pushes co into the argument of runRW#.
    
    11
    +-- #27962: the simplifier dropped that cast, yielding ill-typed Core
    
    12
    +myRun :: (State# RealWorld -> N) -> N
    
    13
    +myRun = coerce (runRW# :: (State# RealWorld -> Int) -> Int)
    
    14
    +{-# INLINE myRun #-}
    
    15
    +
    
    16
    +foo x = myRun (\_ -> MkN (x+1))

  • testsuite/tests/simplCore/should_compile/T27963.hs
    1
    +{-# OPTIONS_GHC -Wno-inline-rule-shadowing #-}
    
    2
    +
    
    3
    +module T27963 where
    
    4
    +
    
    5
    +-- This test is pretty delicate because it relies on a function
    
    6
    +-- that has BOTH a rule AND an INLINE pragma
    
    7
    +--
    
    8
    +-- See #27963 for some discussion
    
    9
    +--
    
    10
    +-- Still, it should (just) work
    
    11
    +
    
    12
    +import GHC.Exts
    
    13
    +
    
    14
    +newtype N = MkN Int
    
    15
    +
    
    16
    +f x = x
    
    17
    +{-# INLINE f #-}
    
    18
    +{-# RULES "f/42" forall x. f x = 42::Int #-}
    
    19
    +
    
    20
    +-- The rule "f/42" should fire in both h1 and h2
    
    21
    +h1,h2 :: N -> Int
    
    22
    +h1 n = f (coerce n) + 0
    
    23
    +h2 n = (coerce f) n + 0   -- #27963: the rule did not fire here

  • testsuite/tests/simplCore/should_compile/T27963.stderr
    1
    +Rule fired: f/42 (T27963)
    
    2
    +Rule fired: f/42 (T27963)

  • testsuite/tests/simplCore/should_compile/all.T
    ... ... @@ -629,3 +629,6 @@ test('T27749',
    629 629
     test('T27629', only_ways(['optasm']), makefile_test, ['T27629'])
    
    630 630
     
    
    631 631
     test('T27936', normal, compile, [''])
    
    632
    +test('T27962', normal, compile, [''])
    
    633
    +test('T27962a', [extra_files(['T27962.hs'])], multimod_compile, ['T27962', '-v0 -O'])
    
    634
    +test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])