Simon Peyton Jones pushed to branch wip/T27737 at Glasgow Haskell Compiler / GHC

Commits:

15 changed files:

Changes:

  • compiler/GHC/Core.hs
    ... ... @@ -490,7 +490,7 @@ This is a well-kinded type, in an environment-based scheme. But `typeKind`
    490 490
     will panic, because the kind of the body of a forall must not mention
    
    491 491
     the forall'd variable (and the inner forall's body appears to do so).
    
    492 492
     
    
    493
    -It might be possible to make `exprType` and `typeKind`` more complicated, so that
    
    493
    +It might be possible to make `exprType` and `typeKind` more complicated, so that
    
    494 494
     they do renaming on the fly.  But instead we impose
    
    495 495
     
    
    496 496
     INVARIANT (NoTypeShadowing):
    
    ... ... @@ -1720,10 +1720,19 @@ isEmptyFloatBinds = isNilOL
    1720 1720
     
    
    1721 1721
     data FloatBind
    
    1722 1722
       = FloatLet  CoreBind
    
    1723
    +      -- let(rec) x = e
    
    1724
    +      -- Invariant: satisfies the let-can-float invariant
    
    1725
    +
    
    1723 1726
       | FloatCase CoreExpr CoreBndr AltCon [CoreBndr]
    
    1724 1727
           -- case e of y { C ys -> ... }
    
    1725 1728
           -- See Note [Floating single-alternative cases] in GHC.Core.Opt.SetLevels
    
    1729
    +
    
    1726 1730
       | FloatTick CoreTickish
    
    1731
    +      -- tick<t> ...
    
    1732
    +      -- Invariant: the tick is always soft-scoped (tickishHasSoftScope holds)
    
    1733
    +      -- Why? We are floating these FloatBinds outwards, bringing more code under
    
    1734
    +      -- the bindigns; that is only OK for soft-scoped ticks.
    
    1735
    +      -- See Note [Scoping ticks and counting ticks] in GHC.Types.Tickish
    
    1727 1736
     
    
    1728 1737
     floatsBinders :: FloatBinds -> [Var]
    
    1729 1738
     floatsBinders fs = foldr ((++) . floatBinders) [] fs
    

  • compiler/GHC/Core/Opt/Simplify/Env.hs
    ... ... @@ -38,14 +38,13 @@ module GHC.Core.Opt.Simplify.Env (
    38 38
     
    
    39 39
             -- * Floats
    
    40 40
             SimplFloats(..), emptyFloats, isEmptyFloats, mkRecFloats,
    
    41
    -        mkFloatBind, addLetFloats, addJoinFloats, addFloats,
    
    42
    -        extendFloats, wrapFloats,
    
    43
    -        isEmptyJoinFloats, isEmptyLetFloats,
    
    44
    -        doFloatFromRhs, getTopFloatBinds,
    
    41
    +        mkFloatBind, addLetFloat, addLetFloats, addCaseFloat, mkLetSimplFloats,
    
    42
    +        addJoinFloats, addFloats, addFloatBindsF,
    
    43
    +        extendFloats, isEmptyJoinFloats,
    
    44
    +        doFloatFromRhs, getTopFloatBinds, onlyLazyLetFloats, doCaseToLet,
    
    45 45
     
    
    46 46
             -- * LetFloats
    
    47
    -        LetFloats, FloatEnable(..), letFloatBinds, emptyLetFloats, unitLetFloat,
    
    48
    -        addLetFlts,  mapLetFloats,
    
    47
    +        LetFloats, FloatEnable(..), emptyLetFloats, mapLetFloats,
    
    49 48
     
    
    50 49
             -- * JoinFloats
    
    51 50
             JoinFloat, JoinFloats, emptyJoinFloats,
    
    ... ... @@ -65,7 +64,7 @@ import GHC.Core.Subst( substExprSC )
    65 64
     import GHC.Core.Unfold
    
    66 65
     import GHC.Core.TyCo.Subst (emptyIdSubstEnv, mkSubst)
    
    67 66
     import GHC.Core.Multiplicity( Scaled(..), mkMultMul )
    
    68
    -import GHC.Core.Make            ( mkWildValBinder, mkCoreLet )
    
    67
    +import GHC.Core.Make            ( mkWildValBinder )
    
    69 68
     import GHC.Core.Type hiding     ( substTy, substTyVar, substTyVarBndr, substCo
    
    70 69
                                     , extendTvSubst, extendCvSubst )
    
    71 70
     import qualified GHC.Core.Coercion as Coercion
    
    ... ... @@ -78,6 +77,7 @@ import GHC.Types.Var.Set
    78 77
     import GHC.Types.Id as Id
    
    79 78
     import GHC.Types.InlinePragma ( ActivationGhc, CompilerPhase, isActiveInPhase )
    
    80 79
     import GHC.Types.Basic
    
    80
    +import GHC.Types.Tickish ( tickishHasSoftScope )
    
    81 81
     import GHC.Types.Unique.FM      ( pprUniqFM )
    
    82 82
     
    
    83 83
     import GHC.Data.OrdList
    
    ... ... @@ -418,9 +418,10 @@ see GHC.Core.Opt.FloatOut.
    418 418
     
    
    419 419
     data SimplFloats
    
    420 420
       = SimplFloats
    
    421
    -      { -- Ordinary let bindings
    
    422
    -        sfLetFloats  :: LetFloats
    
    421
    +      { -- Ordinary let bindings, case-floats and tick-floats
    
    422
    +        sfLetFloats  :: FloatBinds
    
    423 423
                     -- See Note [LetFloats]
    
    424
    +                -- Invariant: every FloatLet satisfies the let-can-float invariant
    
    424 425
     
    
    425 426
             -- Join points
    
    426 427
           , sfJoinFloats :: JoinFloats
    
    ... ... @@ -438,19 +439,19 @@ data SimplFloats
    438 439
     instance Outputable SimplFloats where
    
    439 440
       ppr (SimplFloats { sfLetFloats = lf, sfJoinFloats = jf, sfInScope = is })
    
    440 441
         = text "SimplFloats"
    
    441
    -      <+> braces (vcat [ text "lets: " <+> ppr lf
    
    442
    +      <+> braces (vcat [ text "lets: " <+> ppr (fromOL lf)
    
    442 443
                            , text "joins:" <+> ppr jf
    
    443 444
                            , text "in_scope:" <+> ppr is ])
    
    444 445
     
    
    445 446
     emptyFloats :: SimplEnvIS -> SimplFloats
    
    446 447
     emptyFloats env
    
    447
    -  = SimplFloats { sfLetFloats  = emptyLetFloats
    
    448
    +  = SimplFloats { sfLetFloats  = nilOL
    
    448 449
                     , sfJoinFloats = emptyJoinFloats
    
    449 450
                     , sfInScope    = seInScope env }
    
    450 451
     
    
    451 452
     isEmptyFloats :: SimplFloats -> Bool
    
    452 453
     -- Precondition: used only when sfJoinFloats is empty
    
    453
    -isEmptyFloats (SimplFloats { sfLetFloats  = LetFloats fs _
    
    454
    +isEmptyFloats (SimplFloats { sfLetFloats  = fs
    
    454 455
                                , sfJoinFloats = js })
    
    455 456
       = assertPpr (isNilOL js) (ppr js ) $
    
    456 457
         isNilOL fs
    
    ... ... @@ -744,26 +745,159 @@ setSubstEnv env tvs cvs ids = env { seTvSubst = tvs, seCvSubst = cvs, seIdSubst
    744 745
     
    
    745 746
     Note [LetFloats]
    
    746 747
     ~~~~~~~~~~~~~~~~
    
    747
    -The LetFloats is a bunch of bindings, classified by a FloatFlag.
    
    748
    -
    
    749
    -The `FloatFlag` contains summary information about the bindings, see the data
    
    750
    -type declaration of `FloatFlag`
    
    751
    -
    
    748
    +The `sfLetFloats` field of SimplFloats is a bunch of FloatBinds.  A FloatBind
    
    749
    +can take one of three forms: FloatLet, FloatCase, and FloatTick; see
    
    750
    +Note [Case-floats] and Note [Tick-floats].
    
    751
    +
    
    752
    +In contrast, the type `LetFloats` (= OrdList OutBind) has let-bindings only.
    
    753
    +It is what prepareBinding, prepareRhs and makeTrivial return: they never
    
    754
    +produce case-floats or tick-floats.  See Note [prepareBinding] in
    
    755
    +GHC.Core.Opt.Simplify.Iteration.
    
    756
    +
    
    757
    +When prepareBinding decides whether to float some let-bindings out of a RHS,
    
    758
    +doFloatFromRhs classifies them with a FloatFlag; see the data type declaration
    
    759
    +of `FloatFlag`, and Note [FloatFlag for FloatLet].  Case-floats and tick-floats
    
    760
    +have no FloatFlag, because prepareBinding never floats them out of a RHS.
    
    761
    +
    
    762
    +Why do we have FloatCase at all, rather than just let-bindings?
    
    763
    +
    
    764
    +(LF1) exprIsConApp_maybe looks through single-alternative cases (and lets
    
    765
    +  and ticks) and returns what it looked through as a [FloatBind].  The
    
    766
    +  case-of-known-constructor code wants to add these straight to the
    
    767
    +  Simplifier's floats, so the floats must be able to hold a case.
    
    768
    +
    
    769
    +(LF2) A single-alternative case is returned as a FloatCase by
    
    770
    +  rebuildSingleAltCase rather than as an expression, so that the lets in
    
    771
    +  its alternative are not trapped inside it.  Example, with case-of-case
    
    772
    +  switched off (e.g. in the Gentle phase):
    
    773
    +     case (case f x s of (# s1, a #) ->
    
    774
    +           let b = g a in
    
    775
    +           let c = h b in
    
    776
    +           (# s1, c #))
    
    777
    +     of (# s2, r #) -> body
    
    778
    +  We simplify the inner case with an empty continuation (see
    
    779
    +  splitContForNoCaseCase), and get back
    
    780
    +     floats: [case f x s of (# s1, a #), b = g a, c = h b]
    
    781
    +     result: (# s1, c #)
    
    782
    +  Now rebuildWithFloats can do case-of-known-constructor on the result
    
    783
    +  directly, giving
    
    784
    +     case f x s of (# s1, a #) ->
    
    785
    +     let b = g a in
    
    786
    +     let c = h b in
    
    787
    +     body[s1/s2, c/r]
    
    788
    +  If instead the inner case came back as a single expression, then
    
    789
    +  exprIsConApp_maybe would have to walk down through the case and all the
    
    790
    +  lets to find the (# s1, c #).  With a long chain of such nested binds
    
    791
    +  (e.g. state-passing code, as in T18223) the scrutinee at each level
    
    792
    +  contains all the lets from the levels inside it, so the repeated walks
    
    793
    +  are quadratic (#27737).
    
    794
    +  See Note [Floating single-alternative cases] in GHC.Core.Opt.Simplify.Iteration.
    
    795
    +
    
    796
    +Note [FloatFlag for FloatLet]  -- see `getFF_Let`
    
    797
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    752 798
     Examples
    
    753 799
     
    
    754
    -  NonRec x (y:ys)       FltLifted
    
    755
    -  Rec [(x,rhs)]         FltLifted
    
    756
    -
    
    757
    -  NonRec x* (p:q)       FltOKSpec   -- RHS is WHNF.  Question: why not FltLifted?
    
    758
    -  NonRec x# (y +# 3)    FltOkSpec   -- Unboxed, but ok-for-spec'n
    
    759
    -
    
    760
    -  NonRec x* (f y)       FltCareful  -- Strict binding; might fail or diverge
    
    761
    -  NonRec x# (a /# b)    FltCareful  -- Might fail; does not satisfy let-can-float invariant
    
    762
    -  NonRec x# (f y)       FltCareful  -- Might diverge; does not satisfy let-can-float invariant
    
    800
    +    NonRec x (y:ys)       FltLifted
    
    801
    +    Rec [(x,rhs)]         FltLifted
    
    802
    +
    
    803
    +    NonRec x* (p:q)       FltOKSpec   -- RHS is WHNF.  Question: why not FltLifted?
    
    804
    +    NonRec x# (y +# 3)    FltOkSpec   -- Unboxed, but ok-for-spec'n
    
    805
    +
    
    806
    +    NonRec x* (f y)       FltCareful  -- Strict binding; might fail or diverge
    
    807
    +    NonRec x# (a /# b)    FltCareful  -- Might fail; does not satisfy let-can-float invariant
    
    808
    +    NonRec x# (f y)       FltCareful  -- Might diverge; does not satisfy let-can-float invariant
    
    809
    +
    
    810
    +    NonRec s "foo"#       FltLifted   -- Literal string can go to top level
    
    811
    +
    
    812
    +* (FFL1) Note that a FloatLet can still be FltCareful: the first FltCareful example
    
    813
    +  above, NonRec x* (f y), where x* is lifted but has a strict demand
    
    814
    +  (isStrUsedDmd).  That is a perfectly valid (lazy) let-binding, but its demand
    
    815
    +  info is valid only where it is.  If we floated it out of the RHS of a lazy
    
    816
    +  binding
    
    817
    +       let v = let x* = f y in x*+1 in body
    
    818
    +   ==> let x* = f y; v = x*+1 in body
    
    819
    +  then x's demand info would be a lie, and CorePrep, which case-binds a let
    
    820
    +  whose binder has a strict demand, would evaluate (f y) eagerly.  Hence
    
    821
    +  FltCareful.  prepareBinding never floats a FltCareful binding out of a RHS,
    
    822
    +  even the RHS of a strict binding; see onlyLazyLetFloats.
    
    823
    +
    
    824
    +* (FFL2) A literal-string binding is marked FltLifted (a bit of a mis-nomer
    
    825
    +  because it's not a lifted type) because it can go to top level.
    
    826
    +  See Note [Core top-level string literals] in GHC.Core.
    
    827
    +
    
    828
    +* A binding that does not satisfy the let-can-float invariant (the last two
    
    829
    +  examples above) is represented by a FloatCase, not a FloatLet:
    
    830
    +    FloatCase (a /# b) x# DEFAULT []
    
    831
    +  That is done once and for all by `addLetFloat`, so a FloatLet in sfLetFloats
    
    832
    +  is always a valid let-binding, and `simplWrapFloats` does not need to check.
    
    833
    +  Such bindings used to arise from `makeTrivial`, because an argument need not
    
    834
    +  satisfy the let-can-float invariant; but now makeTrivial declines to bind such
    
    835
    +  an argument (see Note [Cannot trivialise] in GHC.Core.Opt.Simplify.Iteration).
    
    836
    +  They can also arise because
    
    837
    +  exprOkForSpeculation is conservative: e.g. it says False for (# s, x #)
    
    838
    +  where x is lifted, because it checks the arguments against the
    
    839
    +  (representation-polymorphic) type of the unboxed-tuple worker.
    
    840
    +
    
    841
    +Note [Case-floats]
    
    842
    +~~~~~~~~~~~~~~~~~~
    
    843
    +As well as let-bindings, sfLetFloats can contain single-alternative case
    
    844
    +floats (FloatCase), for example
    
    845
    +  case e of b { (# a, c #) -> <hole> }
    
    846
    +A case-float never floats out of the RHS of a let-binding: prepareBinding
    
    847
    +floats only let-bindings.  See Note [prepareBinding] in
    
    848
    +GHC.Core.Opt.Simplify.Iteration, which also describes an opportunity that
    
    849
    +we lose as a result.
    
    850
    +
    
    851
    +(FFC1) Invariant: a DEFAULT FloatCase never has a scrutinee for which doCaseToLet
    
    852
    +  holds.  Such a case-float
    
    853
    +       FloatCase e b DEFAULT []      -- where doCaseToLet e b
    
    854
    +  should instead be the let-float  (b = e), which satisfies the let-can-float
    
    855
    +  invariant.  It would not actually be /wrong/ to use the FloatCase, just less
    
    856
    +  good: a let-float can be inlined, and can float out of the RHS of a let-binding
    
    857
    +  (see Note [prepareBinding]).
    
    858
    +
    
    859
    +  doCaseToLet is the same test that rebuildCase uses to turn a case into a let:
    
    860
    +  roughly, the scrutinee is ok-for-speculation (if unlifted) or a HNF (if lifted).
    
    861
    +  But it says No if `b` is a coercion variable, because a coercion variable can
    
    862
    +  be let-bound only to a Coercion (Note [Core type and coercion invariant] in
    
    863
    +  GHC.Core); so  FloatCase (eq_sel @k @t1 @t2 d) co DEFAULT []  is fine.
    
    864
    +
    
    865
    +  We maintain the invariant thus:
    
    866
    +    * addLetFloat makes a FloatCase only for a binding that needsCaseBinding,
    
    867
    +      i.e. an unlifted one whose RHS is not ok-for-speculation.
    
    868
    +    * rebuildCase turns  case e of b { DEFAULT -> body }  into a let when
    
    869
    +      doCaseToLet holds.
    
    870
    +    * But rebuildCase looks at the alternatives before prepareAlts prunes away
    
    871
    +      impossible ones; e.g.  case x# of b { 1# -> e1; DEFAULT -> e2 }  may be
    
    872
    +      pruned to a single DEFAULT alternative.  So rebuildSingleAltCase makes a
    
    873
    +      let-float, rather than a case-float, for a DEFAULT alternative when
    
    874
    +      doCaseToLet holds.
    
    875
    +    * exprIsConApp_maybe makes DEFAULT case-floats (in GHC.Core.SimpleOpt) only
    
    876
    +      for an unlifted argument that needsCaseBinding, or for a strict field
    
    877
    +      whose argument is not a HNF (mkFieldSeqFloats).
    
    878
    +  We check the invariant, with `okCaseFloat`, in addCaseFloat and addFloatBindsF.
    
    879
    +
    
    880
    +  This invariant is only about DEFAULT case-floats.  A case-float with pattern
    
    881
    +  binders, such as  case addIntC# x y of (# r, c #) -> <hole>,  cannot be a
    
    882
    +  let-float even when its scrutinee is ok-for-speculation.
    
    883
    +
    
    884
    +Note [Tick-floats]
    
    885
    +~~~~~~~~~~~~~~~~~~
    
    886
    +sfLetFloats can contain a FloatTick for soft-scoped ticks (only -- see the
    
    887
    +invariant on FloatTick in GHC.Core); see simplTick.
    
    888
    +
    
    889
    +Like a case-float, a tick-float never floats out of the RHS of a let-binding,
    
    890
    +because prepareBinding floats only let-bindings.  For a /counting/ tick (e.g.
    
    891
    +an HPC tick) that is essential: floating it out of a lazy RHS would change when
    
    892
    +(and how often) it is counted, namely when the let is executed rather than when
    
    893
    +the binder is evaluated.  For a /non-counting/ tick (e.g. a source note) it
    
    894
    +would be fine, but we don't bother.
    
    763 895
     -}
    
    764 896
     
    
    765
    -data LetFloats = LetFloats (OrdList OutBind) FloatFlag
    
    766
    -                 -- See Note [LetFloats]
    
    897
    +type LetFloats = OrdList OutBind
    
    898
    +  -- Let-bindings only: no case-floats or tick-floats
    
    899
    +  -- Invariant: every binding satisfies the let-can-float invariant
    
    900
    +  -- See Note [LetFloats]
    
    767 901
     
    
    768 902
     type JoinFloat  = OutBind
    
    769 903
     type JoinFloats = OrdList JoinFloat
    
    ... ... @@ -780,17 +914,14 @@ data FloatFlag
    780 914
                     --        *and* ok-for-speculation
    
    781 915
                     -- Hence ok to float out of the RHS
    
    782 916
                     -- of a lazy non-recursive let binding
    
    783
    -                -- (but not to top level, or into a rec group)
    
    917
    +                -- (but /not/ to top level, or into a rec group)
    
    784 918
                     -- NB: consequence: all bindings satisfy let-can-float invariant
    
    785 919
     
    
    786 920
       | FltCareful  -- At least one binding is strict (or unlifted)
    
    787 921
                     --      and not guaranteed cheap
    
    788
    -                -- Do not float these bindings out of a lazy let!
    
    922
    +                -- Never float these bindings out of a RHS
    
    789 923
                     -- NB: some bindings may not satisfy let-can-float
    
    790 924
     
    
    791
    -instance Outputable LetFloats where
    
    792
    -  ppr (LetFloats binds ff) = ppr ff $$ ppr (fromOL binds)
    
    793
    -
    
    794 925
     instance Outputable FloatFlag where
    
    795 926
       ppr FltLifted  = text "FltLifted"
    
    796 927
       ppr FltOkSpec  = text "FltOkSpec"
    
    ... ... @@ -803,9 +934,13 @@ andFF FltOkSpec _ = FltOkSpec
    803 934
     andFF FltLifted  flt        = flt
    
    804 935
     
    
    805 936
     
    
    806
    -doFloatFromRhs :: FloatEnable -> TopLevelFlag -> RecFlag -> Bool -> SimplFloats -> OutExpr -> Bool
    
    937
    +doFloatFromRhs :: FloatEnable -> TopLevelFlag -> RecFlag
    
    938
    +               -> LetFloats -> FloatFlag   -- The let-bindings and their FloatFlag,
    
    939
    +                                           --   from onlyLazyLetFloats
    
    940
    +               -> OutExpr -> Bool
    
    807 941
     -- If you change this function look also at FloatIn.noFloatIntoRhs
    
    808
    -doFloatFromRhs fe lvl rec strict_bind (SimplFloats { sfLetFloats = LetFloats fs ff }) rhs
    
    942
    +-- See Note [Floating a prefix of the floats] for a possible improvement
    
    943
    +doFloatFromRhs fe lvl rec fs ff rhs
    
    809 944
       = floatEnabled lvl fe
    
    810 945
           && not (isNilOL fs)
    
    811 946
           && want_to_float
    
    ... ... @@ -817,7 +952,7 @@ doFloatFromRhs fe lvl rec strict_bind (SimplFloats { sfLetFloats = LetFloats fs
    817 952
          can_float = case ff of
    
    818 953
                        FltLifted  -> True
    
    819 954
                        FltOkSpec  -> isNotTopLevel lvl && isNonRec rec
    
    820
    -                   FltCareful -> isNotTopLevel lvl && isNonRec rec && strict_bind
    
    955
    +                   FltCareful -> False   -- onlyLazyLetFloats never returns FltCareful
    
    821 956
     
    
    822 957
          -- Whether any floating is allowed by flags.
    
    823 958
          floatEnabled :: TopLevelFlag -> FloatEnable -> Bool
    
    ... ... @@ -825,6 +960,38 @@ doFloatFromRhs fe lvl rec strict_bind (SimplFloats { sfLetFloats = LetFloats fs
    825 960
          floatEnabled lvl FloatNestedOnly = not (isTopLevel lvl)
    
    826 961
          floatEnabled _ FloatEnabled = True
    
    827 962
     
    
    963
    +{- Note [Floating a prefix of the floats]
    
    964
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    965
    +prepareBinding floats all of the floats from a RHS, or none of them.  It floats
    
    966
    +none if any of them is a case-float or tick-float (see Note [prepareBinding] in
    
    967
    +GHC.Core.Opt.Simplify.Iteration), or if doFloatFromRhs says no; and doFloatFromRhs
    
    968
    +gives a single FloatFlag to the whole group.  Consider (T5321FD)
    
    969
    +     x = let v1 = \ds -> ... in
    
    970
    +         ...
    
    971
    +         let v200 = \ds -> ... in
    
    972
    +         case sampleData of (a :* b) -> ...
    
    973
    +where the single-alternative case has become a FloatCase; see
    
    974
    +Note [Floating single-alternative cases] in GHC.Core.Opt.Simplify.Iteration.
    
    975
    +Because of the FloatCase, none of these floats go to top level, even though the
    
    976
    +lets in front of the case are all FltLifted.
    
    977
    +
    
    978
    +Opportunity: when the group cannot float as a whole, float the longest prefix
    
    979
    +of let-bindings that can, and wrap the rest back around the RHS.  Taking a
    
    980
    +prefix is always fine, because later floats may mention the binders of earlier
    
    981
    +ones, but not vice versa.  To keep the common path cheap, do the linear
    
    982
    +traversal only when the group cannot float as a whole.
    
    983
    +
    
    984
    +We tried this (#27737).  It did restore the top-level floating in T5321FD, but
    
    985
    +made little difference to compile time, so we did not keep it.  If you try it
    
    986
    +again, beware: the sfInScope of the floats describes the scope /inside/ all of
    
    987
    +them, which is wrong for the prefix alone.  In T5321FD, inside the trapped
    
    988
    +     case sampleData of (x :* xs) -> ...
    
    989
    +binder-swap gives sampleData the unfolding (x :* xs); keeping that sfInScope
    
    990
    +let the refined sampleData escape to top level, taking x and xs with it.  The
    
    991
    +fix is to rebuild sfInScope from the in-scope set outside the RHS, extended
    
    992
    +with the binders of the prefix.
    
    993
    +-}
    
    994
    +
    
    828 995
     {- Note [Float when expandable]
    
    829 996
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    830 997
     We float when that would leave us with a RHS that is /expandable/ (#26854).
    
    ... ... @@ -851,10 +1018,7 @@ End of historial aside
    851 1018
     -}
    
    852 1019
     
    
    853 1020
     emptyLetFloats :: LetFloats
    
    854
    -emptyLetFloats = LetFloats nilOL FltLifted
    
    855
    -
    
    856
    -isEmptyLetFloats :: LetFloats -> Bool
    
    857
    -isEmptyLetFloats (LetFloats fs _) = isNilOL fs
    
    1021
    +emptyLetFloats = nilOL
    
    858 1022
     
    
    859 1023
     emptyJoinFloats :: JoinFloats
    
    860 1024
     emptyJoinFloats = nilOL
    
    ... ... @@ -862,19 +1026,83 @@ emptyJoinFloats = nilOL
    862 1026
     isEmptyJoinFloats :: JoinFloats -> Bool
    
    863 1027
     isEmptyJoinFloats = isNilOL
    
    864 1028
     
    
    865
    -unitLetFloat :: OutBind -> LetFloats
    
    866
    --- This key function constructs a singleton float with the right form
    
    867
    -unitLetFloat bind = assert (all (not . isJoinId) (bindersOf bind)) $
    
    868
    -                    LetFloats (unitOL bind) (flag bind)
    
    1029
    +getFF_Let :: CoreBind -> FloatFlag
    
    1030
    +-- See Note [FloatFlag for FloatLet]
    
    1031
    +getFF_Let (Rec {})        = FltLifted
    
    1032
    +getFF_Let (NonRec bndr rhs)
    
    1033
    +  | not (isStrictId bndr)    = FltLifted   -- Lazy lifted let
    
    1034
    +  | exprIsTickedString rhs   = FltLifted   -- See (FFL2)
    
    1035
    +  | exprOkForSpeculation rhs = FltOkSpec   -- Unlifted, or strict lifted, and ok-for-spec (e.g. HNF)
    
    1036
    +  | otherwise                = FltCareful  -- See (FFL1) Strict, e.g. let x* = factorial y
    
    1037
    +
    
    1038
    +addLetFloat :: SimplFloats -> OutBind -> SimplFloats
    
    1039
    +-- Add a non-join binding to the let-floats, and extend the in-scope set.
    
    1040
    +-- If the binding does not satisfy the let-can-float invariant, it
    
    1041
    +-- makes a FloatCase. See Note [LetFloats]
    
    1042
    +addLetFloat floats bind
    
    1043
    +  | NonRec bndr rhs <- bind
    
    1044
    +  , needsCaseBinding (idType bndr) rhs
    
    1045
    +  = -- This should never happen, but currently does because of #27910
    
    1046
    +    add_float floats (FloatCase rhs bndr DEFAULT [])
    
    1047
    +
    
    1048
    +  | otherwise
    
    1049
    +  = assert (all (not . isJoinId) (bindersOf bind)) $
    
    1050
    +    add_float floats (FloatLet bind)
    
    1051
    +
    
    1052
    +addCaseFloat :: SimplFloats -> OutExpr -> OutId -> AltCon -> [OutVar] -> SimplFloats
    
    1053
    +-- Add a single-alternative case float
    
    1054
    +--   case scrut of bndr { con bndrs -> <hole> }
    
    1055
    +-- and extend the in-scope set.  See Note [LetFloats]
    
    1056
    +addCaseFloat floats scrut bndr con bndrs
    
    1057
    +  = assertPpr (okCaseFloat flt) (ppr flt) $
    
    1058
    +    add_float floats flt
    
    869 1059
       where
    
    870
    -    flag (Rec {})                = FltLifted
    
    871
    -    flag (NonRec bndr rhs)
    
    872
    -      | not (isStrictId bndr)    = FltLifted
    
    873
    -      | exprIsTickedString rhs   = FltLifted
    
    874
    -          -- String literals can be floated freely.
    
    875
    -          -- See Note [Core top-level string literals] in GHC.Core.
    
    876
    -      | exprOkForSpeculation rhs = FltOkSpec  -- Unlifted, and lifted but ok-for-spec (eg HNF)
    
    877
    -      | otherwise                = FltCareful
    
    1060
    +    flt = FloatCase scrut bndr con bndrs
    
    1061
    +
    
    1062
    +add_float :: SimplFloats -> FloatBind -> SimplFloats
    
    1063
    +-- Add the float /inside/ the existing let-floats
    
    1064
    +add_float floats@(SimplFloats { sfLetFloats = fs, sfInScope = in_scope }) flt
    
    1065
    +  = floats { sfLetFloats = fs `snocOL` flt
    
    1066
    +           , sfInScope   = in_scope `extendInScopeFromFB` unitOL flt }
    
    1067
    +
    
    1068
    +okLetFloat :: OutBind -> Bool
    
    1069
    +-- Checks the let-can-float invariant; used only in assertions
    
    1070
    +okLetFloat (NonRec b r)
    
    1071
    +  | isId b, not (isCoVar b) = not (needsCaseBinding (idType b) r)
    
    1072
    +okLetFloat _                = True
    
    1073
    +
    
    1074
    +okCaseFloat :: FloatBind -> Bool
    
    1075
    +-- Checks invariant (FFC1) in Note [Case-floats]
    
    1076
    +-- Used only in assertions
    
    1077
    +okCaseFloat (FloatCase scrut b DEFAULT _) = not (doCaseToLet scrut b)
    
    1078
    +okCaseFloat _                             = True
    
    1079
    +
    
    1080
    +doCaseToLet :: OutExpr          -- Scrutinee
    
    1081
    +            -> Id               -- Case binder; can be InId or OutId
    
    1082
    +            -> Bool
    
    1083
    +-- The situation is         case scrut of b { DEFAULT -> body }
    
    1084
    +-- Can we transform thus?   let { b = scrut } in body
    
    1085
    +-- See also (FFC1) in Note [Case-floats]
    
    1086
    +doCaseToLet scrut case_bndr
    
    1087
    +  | isTyCoVar case_bndr    -- Respect GHC.Core
    
    1088
    +  = isTyCoArg scrut        -- Note [Core type and coercion invariant]
    
    1089
    +
    
    1090
    +  | isUnliftedType (exprType scrut)
    
    1091
    +    -- We can call isUnliftedType here: scrutinees always have a fixed RuntimeRep (see FRRCase).
    
    1092
    +    -- Note however that we must check 'scrut' (which is an 'OutExpr') and not 'case_bndr'
    
    1093
    +    -- (which may be an 'InId'): see Note [Dark corner with representation polymorphism]
    
    1094
    +    -- in GHC.Core.Opt.Simplify.Iteration.
    
    1095
    +    -- Using `exprType` is typically cheap because `scrut` is typically a variable.
    
    1096
    +    -- We could instead use mightBeUnliftedType (idType case_bndr), but that hurts
    
    1097
    +    -- the brain more.  Consider that if this test ever turns out to be a perf
    
    1098
    +    -- problem (which seems unlikely).
    
    1099
    +  = exprOkForSpeculation scrut
    
    1100
    +
    
    1101
    +  | otherwise  -- Scrut has a lifted type
    
    1102
    +  = exprIsHNF scrut
    
    1103
    +       --    || isStrUsedDmd (idDemandInfo case_bndr)
    
    1104
    +       -- We no longer look at the demand on the case binder
    
    1105
    +       -- See Note [Case-to-let for strictly-used binders] in GHC.Core.Opt.Simplify.Iteration
    
    878 1106
     
    
    879 1107
     unitJoinFloat :: OutBind -> JoinFloats
    
    880 1108
     unitJoinFloat bind = assert (all isJoinId (bindersOf bind)) $
    
    ... ... @@ -886,50 +1114,65 @@ mkFloatBind :: SimplEnv -> OutBind -> (SimplFloats, SimplEnv)
    886 1114
     -- These binders may already be in the in-scope set,
    
    887 1115
     -- but may have by now been augmented with more IdInfo
    
    888 1116
     mkFloatBind env bind
    
    889
    -  = (floats, env { seInScope = in_scope' })
    
    1117
    +  = (floats, env { seInScope = sfInScope floats })
    
    890 1118
       where
    
    891
    -    floats
    
    892
    -      | isJoinBind bind
    
    893
    -      = SimplFloats { sfLetFloats  = emptyLetFloats
    
    894
    -                    , sfJoinFloats = unitJoinFloat bind
    
    895
    -                    , sfInScope    = in_scope' }
    
    896
    -      | otherwise
    
    897
    -      = SimplFloats { sfLetFloats  = unitLetFloat bind
    
    898
    -                    , sfJoinFloats = emptyJoinFloats
    
    899
    -                    , sfInScope    = in_scope' }
    
    900 1119
         -- See Note [Bangs in the Simplifier]
    
    901
    -    !in_scope' = seInScope env `extendInScopeSetBind` bind
    
    1120
    +    !floats = emptyFloats env `extendFloats` bind
    
    902 1121
     
    
    903 1122
     extendFloats :: SimplFloats -> OutBind -> SimplFloats
    
    904
    --- Add this binding to the floats, and extend the in-scope env too
    
    905
    -extendFloats (SimplFloats { sfLetFloats  = floats
    
    906
    -                          , sfJoinFloats = jfloats
    
    907
    -                          , sfInScope    = in_scope })
    
    908
    -             bind
    
    1123
    +-- Add this binding (join point or not) to the floats,
    
    1124
    +-- and extend the in-scope env too
    
    1125
    +extendFloats floats@(SimplFloats { sfJoinFloats = jfloats, sfInScope = in_scope }) bind
    
    909 1126
       | isJoinBind bind
    
    910
    -  = SimplFloats { sfInScope    = in_scope'
    
    911
    -                , sfLetFloats  = floats
    
    912
    -                , sfJoinFloats = jfloats' }
    
    1127
    +  = floats { sfJoinFloats = jfloats `addJoinFlts` unitJoinFloat bind
    
    1128
    +           , sfInScope    = in_scope `extendInScopeSetBind` bind }
    
    913 1129
       | otherwise
    
    914
    -  = SimplFloats { sfInScope    = in_scope'
    
    915
    -                , sfLetFloats  = floats'
    
    916
    -                , sfJoinFloats = jfloats }
    
    917
    -  where
    
    918
    -    in_scope' = in_scope `extendInScopeSetBind` bind
    
    919
    -    floats'   = floats  `addLetFlts`  unitLetFloat bind
    
    920
    -    jfloats'  = jfloats `addJoinFlts` unitJoinFloat bind
    
    1130
    +  = floats `addLetFloat` bind
    
    921 1131
     
    
    922
    -addLetFloats :: SimplFloats -> LetFloats -> SimplFloats
    
    923
    --- Add the let-floats for env2 to env1;
    
    924
    --- *plus* the in-scope set for env2, which is bigger
    
    925
    --- than that for env1
    
    926
    -addLetFloats floats let_floats
    
    927
    -  = floats { sfLetFloats = sfLetFloats floats `addLetFlts` let_floats
    
    928
    -           , sfInScope   = sfInScope floats `extendInScopeFromLF` let_floats }
    
    1132
    +mkLetSimplFloats :: InScopeSet -> LetFloats -> SimplFloats
    
    1133
    +-- Make SimplFloats from some let-bindings.
    
    1134
    +-- Precondition: the InScopeSet already includes the binders of the let-bindings
    
    1135
    +mkLetSimplFloats in_scope binds
    
    1136
    +  = SimplFloats { sfLetFloats  = fmap FloatLet binds
    
    1137
    +                , sfJoinFloats = emptyJoinFloats
    
    1138
    +                , sfInScope    = in_scope }
    
    929 1139
     
    
    930
    -extendInScopeFromLF :: InScopeSet -> LetFloats -> InScopeSet
    
    931
    -extendInScopeFromLF in_scope (LetFloats binds _)
    
    932
    -  = foldlOL extendInScopeSetBind in_scope binds
    
    1140
    +addLetFloats :: SimplFloats -> LetFloats -> SimplFloats
    
    1141
    +-- Add the let-bindings /inside/ the existing floats,
    
    1142
    +-- and extend the in-scope set
    
    1143
    +-- No need for addLetFloat's needsCaseBinding test: LetFloats satisfy the
    
    1144
    +-- let-can-float invariant (see the declaration of LetFloats)
    
    1145
    +addLetFloats floats binds = foldlOL add floats binds
    
    1146
    +  where
    
    1147
    +    add fs bind = assertPpr (okLetFloat bind) (ppr bind) $
    
    1148
    +                  add_float fs (FloatLet bind)
    
    1149
    +
    
    1150
    +addFloatBindsF :: FloatBinds -> SimplFloats -> SimplFloats
    
    1151
    +-- (addFloatBindsF new_fbs floats) adds `new_fbs` /outside/ `floats`;
    
    1152
    +-- i.e. `new_fbs` scope over `floats`
    
    1153
    +-- Precondition: every FloatLet in `new_fbs` satisfies the let-can-float
    
    1154
    +-- invariant (see the FloatBind declaration in GHC.Core), so we can add
    
    1155
    +-- them directly; see Note [LetFloats]
    
    1156
    +addFloatBindsF new_fbs floats@(SimplFloats { sfLetFloats = lf_fbs, sfInScope = in_scope })
    
    1157
    +  | isNilOL new_fbs
    
    1158
    +  = floats
    
    1159
    +  | otherwise
    
    1160
    +  = assertPpr (all ok_float new_fbs) (ppr new_fbs) $
    
    1161
    +    floats { sfLetFloats = new_fbs `appOL` lf_fbs
    
    1162
    +           , sfInScope   = in_scope `extendInScopeFromFB` new_fbs }
    
    1163
    +  where
    
    1164
    +    -- Check the invariants on FloatBind; see its declaration in GHC.Core
    
    1165
    +    ok_float (FloatLet bind)    = okLetFloat bind
    
    1166
    +    ok_float (FloatTick t)      = tickishHasSoftScope t
    
    1167
    +    ok_float flt@(FloatCase {}) = okCaseFloat flt
    
    1168
    +
    
    1169
    +extendInScopeFromFB :: InScopeSet -> FloatBinds -> InScopeSet
    
    1170
    +extendInScopeFromFB in_scope binds
    
    1171
    +  = foldlOL extend in_scope binds
    
    1172
    +  where
    
    1173
    +    extend in_scope (FloatLet bind)        = in_scope `extendInScopeSetBind` bind
    
    1174
    +    extend in_scope (FloatCase _ b _ bs)   = in_scope `extendInScopeSetList` (b:bs)
    
    1175
    +    extend in_scope (FloatTick {})         = in_scope
    
    933 1176
     
    
    934 1177
     addJoinFloats :: SimplFloats -> JoinFloats -> SimplFloats
    
    935 1178
     addJoinFloats floats join_floats
    
    ... ... @@ -943,16 +1186,46 @@ addFloats :: SimplFloats -> SimplFloats -> SimplFloats
    943 1186
     -- than that for env1
    
    944 1187
     addFloats (SimplFloats { sfLetFloats = lf1, sfJoinFloats = jf1 })
    
    945 1188
               (SimplFloats { sfLetFloats = lf2, sfJoinFloats = jf2, sfInScope = in_scope })
    
    946
    -  = SimplFloats { sfLetFloats  = lf1 `addLetFlts` lf2
    
    1189
    +  = SimplFloats { sfLetFloats  = lf1 `appOL` lf2
    
    947 1190
                     , sfJoinFloats = jf1 `addJoinFlts` jf2
    
    948 1191
                     , sfInScope    = in_scope }
    
    949 1192
     
    
    950
    -addLetFlts :: LetFloats -> LetFloats -> LetFloats
    
    951
    -addLetFlts (LetFloats bs1 l1) (LetFloats bs2 l2)
    
    952
    -  = LetFloats (bs1 `appOL` bs2) (l1 `andFF` l2)
    
    1193
    +onlyLazyLetFloats :: SimplFloats -> LetFloats -> Maybe (LetFloats, FloatFlag)
    
    1194
    +-- (onlyLazyLetFloats floats extra_binds) returns (Just (binds, ff)) if all the
    
    1195
    +-- let-floats in `floats`, followed by `extra_binds`, are let-bindings that we are
    
    1196
    +-- prepared to float out of a RHS: no case-floats or tick-floats, and no
    
    1197
    +-- FltCareful bindings.  The FloatFlag `ff` combines the flags of the `binds`,
    
    1198
    +-- so it is FltLifted or FltOkSpec.
    
    1199
    +-- Precondition: there are no join floats
    
    1200
    +-- See Note [prepareBinding] in GHC.Core.Opt.Simplify.Iteration
    
    1201
    +onlyLazyLetFloats (SimplFloats { sfLetFloats = fs, sfJoinFloats = jfs }) extra_binds
    
    1202
    +  = assertPpr (isNilOL jfs) (ppr jfs) $
    
    1203
    +    go FltLifted nilOL (fromOL fs)
    
    1204
    +  where
    
    1205
    +    go ff binds []                    = foldlOL add_extra (Just (binds, ff)) extra_binds
    
    1206
    +    go ff binds (FloatLet bind : rest)
    
    1207
    +      | FltCareful <- bind_ff         = Nothing
    
    1208
    +      | otherwise                     = go (ff `andFF` bind_ff) (binds `snocOL` bind) rest
    
    1209
    +      where
    
    1210
    +        bind_ff = getFF_Let bind     -- See Note [FloatFlag for FloatLet]
    
    1211
    +    go _ _ _                          = Nothing    -- Case-float or tick-float
    
    953 1212
     
    
    954
    -letFloatBinds :: LetFloats -> [CoreBind]
    
    955
    -letFloatBinds (LetFloats bs _) = fromOL bs
    
    1213
    +    add_extra Nothing            _    = Nothing
    
    1214
    +    add_extra (Just (binds, ff)) bind
    
    1215
    +      | FltCareful <- bind_ff         = Nothing
    
    1216
    +      | otherwise                     = Just (binds `snocOL` bind, ff `andFF` bind_ff)
    
    1217
    +      where
    
    1218
    +        bind_ff = getFF_Let bind
    
    1219
    +
    
    1220
    +letFloatBinds :: SimplFloats -> [OutBind]
    
    1221
    +-- The let-floats, as bindings
    
    1222
    +-- Precondition: there are no case-floats or tick-floats; true, for example,
    
    1223
    +--               for floats that have come out of a recursive or top-level RHS
    
    1224
    +--               (see Note [prepareBinding] in GHC.Core.Opt.Simplify.Iteration)
    
    1225
    +letFloatBinds (SimplFloats { sfLetFloats = fs }) = map get_bind (fromOL fs)
    
    1226
    +  where
    
    1227
    +    get_bind (FloatLet bind) = bind
    
    1228
    +    get_bind flt             = pprPanic "letFloatBinds" (ppr flt)
    
    956 1229
     
    
    957 1230
     addJoinFlts :: JoinFloats -> JoinFloats -> JoinFloats
    
    958 1231
     addJoinFlts = appOL
    
    ... ... @@ -960,7 +1233,7 @@ addJoinFlts = appOL
    960 1233
     mkRecFloats :: SimplFloats -> SimplFloats
    
    961 1234
     -- Flattens the floats into a single Rec group,
    
    962 1235
     -- They must either all be lifted LetFloats or all JoinFloats
    
    963
    -mkRecFloats floats@(SimplFloats { sfLetFloats  = LetFloats bs _ff
    
    1236
    +mkRecFloats floats@(SimplFloats { sfLetFloats  = bs
    
    964 1237
                                     , sfJoinFloats = jbs
    
    965 1238
                                     , sfInScope    = in_scope })
    
    966 1239
       = assertPpr (isNilOL bs || isNilOL jbs) (ppr floats) $
    
    ... ... @@ -969,22 +1242,11 @@ mkRecFloats floats@(SimplFloats { sfLetFloats = LetFloats bs _ff
    969 1242
                     , sfInScope    = in_scope }
    
    970 1243
       where
    
    971 1244
         -- See Note [Bangs in the Simplifier]
    
    972
    -    !floats'  | isNilOL bs  = emptyLetFloats
    
    973
    -              | otherwise   = unitLetFloat (Rec (flattenBinds (fromOL bs)))
    
    1245
    +    !floats'  | isNilOL bs  = nilOL
    
    1246
    +              | otherwise   = unitOL (FloatLet (Rec (flattenBinds (letFloatBinds floats))))
    
    974 1247
         !jfloats' | isNilOL jbs = emptyJoinFloats
    
    975 1248
                   | otherwise   = unitJoinFloat (Rec (flattenBinds (fromOL jbs)))
    
    976 1249
     
    
    977
    -wrapFloats :: SimplFloats -> OutExpr -> OutExpr
    
    978
    --- Wrap the floats around the expression
    
    979
    -wrapFloats (SimplFloats { sfLetFloats  = LetFloats bs flag
    
    980
    -                        , sfJoinFloats = jbs }) body
    
    981
    -  = foldrOL mk_let (wrapJoinFloats jbs body) bs
    
    982
    -     -- Note: Always safe to put the joins on the inside
    
    983
    -     -- since the values can't refer to them
    
    984
    -  where
    
    985
    -    mk_let | FltCareful <- flag = mkCoreLet -- need to enforce let-can-float-invariant
    
    986
    -           | otherwise          = Let       -- let-can-float invariant hold
    
    987
    -
    
    988 1250
     wrapJoinFloatsX :: SimplFloats -> OutExpr -> (SimplFloats, OutExpr)
    
    989 1251
     -- Wrap the sfJoinFloats of the env around the expression,
    
    990 1252
     -- and take them out of the SimplEnv
    
    ... ... @@ -999,19 +1261,18 @@ wrapJoinFloats join_floats body
    999 1261
       = foldrOL Let body join_floats
    
    1000 1262
     
    
    1001 1263
     getTopFloatBinds :: SimplFloats -> [CoreBind]
    
    1002
    -getTopFloatBinds (SimplFloats { sfLetFloats  = lbs
    
    1003
    -                              , sfJoinFloats = jbs})
    
    1264
    +getTopFloatBinds floats@(SimplFloats { sfJoinFloats = jbs })
    
    1004 1265
       = assert (isNilOL jbs) $  -- Can't be any top-level join bindings
    
    1005
    -    letFloatBinds lbs
    
    1266
    +    letFloatBinds floats
    
    1006 1267
     
    
    1007 1268
     {-# INLINE mapLetFloats #-}
    
    1008 1269
     mapLetFloats :: LetFloats -> ((Id,CoreExpr) -> (Id,CoreExpr)) -> LetFloats
    
    1009
    -mapLetFloats (LetFloats fs ff) fun
    
    1010
    -   = LetFloats fs1 ff
    
    1270
    +mapLetFloats binds fun
    
    1271
    +   = binds1
    
    1011 1272
        where
    
    1012 1273
         app (NonRec b e) = case fun (b,e) of (b',e') -> NonRec b' e'
    
    1013 1274
         app (Rec bs)     = Rec (strictMap fun bs)
    
    1014
    -    !fs1 = (mapOL' app fs) -- See Note [Bangs in the Simplifier]
    
    1275
    +    !binds1 = mapOL' app binds -- See Note [Bangs in the Simplifier]
    
    1015 1276
     
    
    1016 1277
     {-
    
    1017 1278
     ************************************************************************
    

  • compiler/GHC/Core/Opt/Simplify/Iteration.hs
    ... ... @@ -22,8 +22,7 @@ import GHC.Core.Opt.Simplify.Env
    22 22
     import GHC.Core.Opt.Simplify.Inline
    
    23 23
     import GHC.Core.Opt.Simplify.Utils
    
    24 24
     import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr, zapLambdaBndrs )
    
    25
    -import GHC.Core.Make hiding( wrapFloats )
    
    26
    -import qualified GHC.Core.Make
    
    25
    +import GHC.Core.Make
    
    27 26
     import GHC.Core.Coercion hiding ( substCo, substCoVar )
    
    28 27
     import qualified GHC.Core.Coercion as Coercion
    
    29 28
     import GHC.Core.Reduction
    
    ... ... @@ -40,7 +39,7 @@ import GHC.Core.Utils
    40 39
     import GHC.Core.Opt.Arity ( ArityType, exprArity, arityTypeBotSigs_maybe
    
    41 40
                               , pushCoTyArg, pushCoValArg, exprIsDeadEnd
    
    42 41
                               , typeArity, arityTypeArity, etaExpandAT )
    
    43
    -import GHC.Core.SimpleOpt ( exprIsConApp_maybe, joinPointBinding_maybe, joinPointBindings_maybe )
    
    42
    +import GHC.Core.SimpleOpt ( exprIsConApp_maybe, joinPointBind_maybe )
    
    44 43
     import GHC.Core.FVs     ( mkRuleInfo {- exprsFreeIds -} )
    
    45 44
     import GHC.Core.Rules   ( lookupRule, getRules )
    
    46 45
     import GHC.Core.Multiplicity
    
    ... ... @@ -57,7 +56,6 @@ import GHC.Types.Demand
    57 56
     import GHC.Types.Unique ( hasKey )
    
    58 57
     import GHC.Types.Basic
    
    59 58
     import GHC.Types.Tickish
    
    60
    -import GHC.Types.Var    ( isTyCoVar )
    
    61 59
     
    
    62 60
     import GHC.Builtin.WiredIn.Prim( realWorldStatePrimTy )
    
    63 61
     import GHC.Builtin.KnownKeys( runRWKey, seqHashKey )
    
    ... ... @@ -66,6 +64,8 @@ import GHC.Builtin.WiredIn.Ids( seqId )
    66 64
     import qualified GHC.Data.List.Infinite as Inf
    
    67 65
     import GHC.Data.Maybe   ( isNothing, orElse, mapMaybe )
    
    68 66
     import GHC.Data.FastString
    
    67
    +import GHC.Data.OrdList ( unitOL, isNilOL, appOL, snocOL, foldlOL )
    
    68
    +import GHC.Types.Var.Env ( InScopeSet )
    
    69 69
     import GHC.Unit.Module ( moduleName )
    
    70 70
     import GHC.Utils.Outputable
    
    71 71
     import GHC.Utils.Panic
    
    ... ... @@ -255,6 +255,8 @@ simplRecBind env0 bind_cxt pairs0
    255 255
             ; let new_bndrs = map sndOf3 triples
    
    256 256
             ; (rec_floats, env2) <- enterRecGroupRHSs env1 new_bndrs $ \env ->
    
    257 257
                                     go env triples
    
    258
    +
    
    259
    +           -- In rec_floats, all the `sfLetFloats` bindings are `FltLifted`
    
    258 260
             ; return (mkRecFloats rec_floats, env2) }
    
    259 261
       where
    
    260 262
         add_rules :: SimplEnv -> (InBndr,InExpr) -> SimplM (SimplEnv, (InBndr, OutBndr, InExpr))
    
    ... ... @@ -283,7 +285,8 @@ simplRecOrTopPair :: SimplEnv
    283 285
                       -> BindContext
    
    284 286
                       -> InId -> OutBndr -> InExpr  -- Binder and rhs
    
    285 287
                       -> SimplM (SimplFloats, SimplEnv)
    
    286
    -
    
    288
    +-- Invariant: in the returned SimplFloats,
    
    289
    +--            all the `sfLetFloats` bindings are `FltLifted`
    
    287 290
     simplRecOrTopPair env bind_cxt old_bndr new_bndr rhs
    
    288 291
       | Just env' <- preInlineUnconditionally env (bindContextLevel bind_cxt)
    
    289 292
                                               old_bndr (UnSimplified env) rhs MRefl
    
    ... ... @@ -348,25 +351,27 @@ simplLazyBind top_lvl is_rec (bndr,unf_se) (bndr1,env) (rhs,rhs_se)
    348 351
             ; (body_floats0, body0) <- {-#SCC "simplExprF" #-} simplExprF body_env body rhs_cont
    
    349 352
     
    
    350 353
             -- ANF-ise a constructor or PAP rhs
    
    351
    -        ; (body_floats2, body2) <- {-#SCC "prepareBinding" #-}
    
    352
    -                                   prepareBinding env top_lvl is_rec
    
    353
    -                                                  False  -- Not strict; this is simplLazyBind
    
    354
    -                                                  bndr1 body_floats0 body0
    
    354
    +        ; (body_lets, lets_in_scope, body2)
    
    355
    +              <- {-#SCC "prepareBinding" #-}
    
    356
    +                 prepareBinding env top_lvl is_rec
    
    357
    +                                               bndr1 (contResultType rhs_cont)
    
    358
    +                                               body_floats0 body0
    
    355 359
               -- Subtle point: we do not need or want tvs' in the InScope set
    
    356 360
               -- of body_floats2, so we pass in 'env' not 'body_env'.
    
    357 361
               -- Don't want: if tvs' are in-scope in the scope of this let-binding, we may do
    
    358 362
               -- more renaming than necessary => extra work (see !7777 and test T16577).
    
    359 363
               -- Don't need: we wrap tvs' around the RHS anyway.
    
    360 364
     
    
    365
    +        ; let body_floats2 = mkLetSimplFloats lets_in_scope body_lets
    
    361 366
             ; (rhs_floats, body3)
    
    362
    -            <-  if isEmptyFloats body_floats2 || null tvs then   -- Simple floating
    
    367
    +            <-  if isNilOL body_lets || null tvs then   -- Simple floating
    
    363 368
                          {-#SCC "simplLazyBind-simple-floating" #-}
    
    364 369
                          return (body_floats2, body2)
    
    365 370
     
    
    366 371
                     else -- Non-empty floats, and non-empty tyvars: do type-abstraction first
    
    367 372
                          {-#SCC "simplLazyBind-type-abstraction-first" #-}
    
    368
    -                     do { (poly_binds, body3) <- abstractFloats (seUnfoldingOpts env) top_lvl
    
    369
    -                                                                tvs' body_floats2 body2
    
    373
    +                     do { (poly_binds, body3) <- abstractFloats (seUnfoldingOpts env) top_lvl tvs'
    
    374
    +                                                                lets_in_scope body_lets body2
    
    370 375
                             ; let poly_floats = foldl' extendFloats (emptyFloats env) poly_binds
    
    371 376
                             ; return (poly_floats, body3) }
    
    372 377
     
    
    ... ... @@ -426,7 +431,7 @@ simplAuxBind (saf,env) bndr new_rhs
    426 431
       = do  { -- ANF-ise the RHS
    
    427 432
               let !occ_fs = getOccFS bndr
    
    428 433
             ; (anf_floats, rhs1) <- prepareRhs env NotTopLevel occ_fs new_rhs
    
    429
    -        ; unless (isEmptyLetFloats anf_floats) (tick LetFloatFromLet)
    
    434
    +        ; unless (isNilOL anf_floats) (tick LetFloatFromLet)
    
    430 435
             ; let rhs_floats = emptyFloats env `addLetFloats` anf_floats
    
    431 436
     
    
    432 437
               -- Simplify the binder and complete the binding
    
    ... ... @@ -628,15 +633,14 @@ tryCastWorkerWrapper env bind_cxt old_bndr bndr (Cast rhs co)
    628 633
       = do  { uniq <- getUniqueM
    
    629 634
             ; let work_name = mkSystemVarName uniq occ_fs
    
    630 635
                   work_id   = mkLocalIdWithInfo work_name ManyTy work_ty work_info
    
    631
    -              is_strict = isStrictId bndr
    
    632 636
     
    
    633
    -        ; (rhs_floats, work_rhs) <- prepareBinding env top_lvl is_rec is_strict
    
    634
    -                                                   work_id (emptyFloats env) rhs
    
    637
    +        ; (rhs_lets, lets_in_scope, work_rhs)
    
    638
    +              <- prepareBinding env top_lvl is_rec work_id work_ty (emptyFloats env) rhs
    
    635 639
     
    
    636 640
             ; work_unf <- mk_worker_unfolding top_lvl work_id work_rhs
    
    637 641
             ; let  work_id_w_unf = work_id `setIdUnfolding` work_unf
    
    638
    -               floats   = rhs_floats `addLetFloats`
    
    639
    -                          unitLetFloat (NonRec work_id_w_unf work_rhs)
    
    642
    +               floats   = mkLetSimplFloats lets_in_scope rhs_lets `addLetFloat`
    
    643
    +                          NonRec work_id_w_unf work_rhs
    
    640 644
     
    
    641 645
                    triv_rhs = Cast (Var work_id_w_unf) co
    
    642 646
     
    
    ... ... @@ -714,10 +718,12 @@ mkCastWrapperInlinePrag prag = prag
    714 718
     *                                                                      *
    
    715 719
     ********************************************************************* -}
    
    716 720
     
    
    717
    -prepareBinding :: SimplEnv -> TopLevelFlag -> RecFlag -> Bool
    
    718
    -               -> Id   -- Used only for its OccName; can be InId or OutId
    
    721
    +prepareBinding :: SimplEnv -> TopLevelFlag -> RecFlag
    
    722
    +               -> Id       -- Used only for its OccName; can be InId or OutId
    
    723
    +               -> OutType  -- The type of the RHS
    
    719 724
                    -> SimplFloats -> OutExpr
    
    720
    -               -> SimplM (SimplFloats, OutExpr)
    
    725
    +               -> SimplM (LetFloats, InScopeSet, OutExpr)
    
    726
    +                  -- The InScopeSet includes the binders of the LetFloats
    
    721 727
     -- In (prepareBinding ... bndr floats rhs), the binding is really just
    
    722 728
     --    bndr = let floats in rhs
    
    723 729
     -- Maybe we can ANF-ise this binding and float out; e.g.
    
    ... ... @@ -728,8 +734,8 @@ prepareBinding :: SimplEnv -> TopLevelFlag -> RecFlag -> Bool
    728 734
     --    bndr = K a a tmp
    
    729 735
     -- That's what prepareBinding does
    
    730 736
     -- Precondition: binder is not a JoinId
    
    731
    --- Postcondition: the returned SimplFloats contains only let-floats
    
    732
    -prepareBinding env top_lvl is_rec strict_bind bndr rhs_floats rhs
    
    737
    +-- Postcondition: returns only let-bindings; see Note [prepareBinding]
    
    738
    +prepareBinding env top_lvl is_rec bndr rhs_ty rhs_floats rhs
    
    733 739
       = do { -- Never float join-floats out of a non-join let-binding (which this is)
    
    734 740
              -- So wrap the body in the join-floats right now
    
    735 741
              -- Hence: rhs_floats1 consists only of let-floats
    
    ... ... @@ -745,16 +751,73 @@ prepareBinding env top_lvl is_rec strict_bind bndr rhs_floats rhs
    745 751
            ; (anf_floats, rhs2) <- prepareRhs rhs_env top_lvl occ_fs rhs1
    
    746 752
     
    
    747 753
            -- Finally, decide whether or not to float
    
    748
    -       ; let all_floats = rhs_floats1 `addLetFloats` anf_floats
    
    749
    -       ; if doFloatFromRhs (seFloatEnable env) top_lvl is_rec strict_bind all_floats rhs2
    
    750
    -         then -- Float!
    
    751
    -              do { tick LetFloatFromLet
    
    752
    -                 ; return (all_floats, rhs2) }
    
    753
    -
    
    754
    -         else -- Abandon floating altogether; revert to original rhs
    
    755
    -              -- Since we have already built rhs1, we just need to add
    
    756
    -              -- rhs_floats1 to it
    
    757
    -              return (emptyFloats env, wrapFloats rhs_floats1 rhs1) }
    
    754
    +       -- The anf_floats are already let-bindings, so we need not add them
    
    755
    +       -- to rhs_floats1 (and its in-scope set) just to check them
    
    756
    +       ; case onlyLazyLetFloats rhs_floats1 anf_floats of
    
    757
    +           Just (all_lets, ff)   -- Float only lazy or ok-for-spec let-bindings
    
    758
    +                                 -- See Note [prepareBinding]
    
    759
    +             | doFloatFromRhs (seFloatEnable env) top_lvl is_rec all_lets ff rhs2
    
    760
    +             -> do { tick LetFloatFromLet
    
    761
    +                   ; let !in_scope = foldlOL extendInScopeSetBind
    
    762
    +                                             (sfInScope rhs_floats1) anf_floats
    
    763
    +                           -- rhs_floats1 already has the binders of its own floats
    
    764
    +                   ; return (all_lets, in_scope, rhs2) }
    
    765
    +
    
    766
    +           _ -> -- Abandon floating altogether; revert to original rhs
    
    767
    +                -- Since we have already built rhs1, we just need to add
    
    768
    +                -- rhs_floats1 to it
    
    769
    +                do { rhs' <- simplWrapFloats (seMode env) rhs_floats1 rhs1 rhs_ty
    
    770
    +                   ; return (emptyLetFloats, seInScope env, rhs') } }
    
    771
    +
    
    772
    +{- Note [prepareBinding]
    
    773
    +~~~~~~~~~~~~~~~~~~~~~~~~~
    
    774
    +In (prepareBinding ... bndr floats rhs), the binding is really
    
    775
    +   bndr = let floats in rhs
    
    776
    +and prepareBinding decides whether to float the floats out, so that we get
    
    777
    +   floats; bndr = rhs
    
    778
    +using doFloatFromRhs to make the decision.  First it ANF-ises the RHS with
    
    779
    +prepareRhs, which may add more floats.
    
    780
    +
    
    781
    +prepareBinding floats only let-bindings, and only lazy or ok-for-speculation
    
    782
    +ones (FltLifted or FltOkSpec): if any of the floats is a case-float, a tick-float,
    
    783
    +or a FltCareful let-binding, it floats nothing.  So it returns just let-bindings
    
    784
    +(LetFloats), and doFloatFromRhs is concerned only with let-bindings.  All this is
    
    785
    +done by onlyLazyLetFloats, in a single pass over the floats.
    
    786
    +
    
    787
    +We never float a FltCareful let-binding (a strict one whose RHS is not
    
    788
    +ok-for-speculation), even out of the RHS of a strict binding: we just don't
    
    789
    +think it is worth it.  See (FFL1) in Note [FloatFlag for FloatLet] in
    
    790
    +GHC.Core.Opt.Simplify.Env.
    
    791
    +
    
    792
    +Why not float case-floats and tick-floats too?
    
    793
    +
    
    794
    +(PB1) If the RHS of a lazy binding is  /\tvs. body  (with no value lambda),
    
    795
    +  simplLazyBind strips off the type lambdas, simplifies the body, and calls
    
    796
    +  prepareBinding on the body.  If prepareBinding floats anything, simplLazyBind
    
    797
    +  must then abstract those floats over the `tvs`, with abstractFloats; see
    
    798
    +  Note [Floating and type abstraction] in GHC.Core.Opt.Simplify.Utils.  But
    
    799
    +  abstractFloats can only deal with let-bindings: a case-float binds pattern
    
    800
    +  variables strictly, and cannot be abstracted over the `tvs`.  T27737a was a
    
    801
    +  panic arising from a case-float reaching abstractFloats.
    
    802
    +
    
    803
    +(PB2) For a tick-float, see Note [Tick-floats] in GHC.Core.Opt.Simplify.Env.
    
    804
    +
    
    805
    +(PB3) It is simple, and before case-floats existed, a case simply stayed in the
    
    806
    +  RHS, so we lose nothing compared to that.
    
    807
    +
    
    808
    +(PB4) Lost opportunity.  Consider
    
    809
    +     x = case addIntC# a b of (# r, c #) -> K r c
    
    810
    +  The scrutinee is ok-for-speculation, so we /could/ float the case-float out,
    
    811
    +  to get
    
    812
    +     case addIntC# a b of (# r, c #) -> let x = K r c in ...
    
    813
    +  Now x is bound to a value, so case-of-known-constructor can see through it.
    
    814
    +  That is just what we do for a strict let with an ok-for-speculation RHS (which
    
    815
    +  is FltOkSpec).  But we would need to classify case-floats with a FloatFlag
    
    816
    +  (FltOkSpec if the scrutinee is ok-for-speculation, otherwise FltCareful), and
    
    817
    +  to avoid floating them when they must be abstracted over type variables (PB1).
    
    818
    +  We do not currently do this; the simplicity of returning only let-bindings
    
    819
    +  seems to be worth more.
    
    820
    +-}
    
    758 821
     
    
    759 822
     {- Note [prepareRhs]
    
    760 823
     ~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -813,7 +876,7 @@ prepareRhs env top_lvl occ rhs0
    813 876
         anfise (App fun arg)
    
    814 877
             = do { (floats1, fun') <- anfise fun
    
    815 878
                  ; (floats2, arg') <- makeTrivial env top_lvl topDmd occ arg
    
    816
    -             ; return (floats1 `addLetFlts` floats2, App fun' arg') }
    
    879
    +             ; return (floats1 `appOL` floats2, App fun' arg') }
    
    817 880
         anfise (Var fun)
    
    818 881
             = return (emptyLetFloats, Var fun)
    
    819 882
     
    
    ... ... @@ -879,43 +942,69 @@ makeTrivial env top_lvl dmd occ_fs expr
    879 942
                   bind     = NonRec final_id expr2
    
    880 943
     
    
    881 944
             ; traceSmpl "makeTrivial" (vcat [text "final_id" <+> ppr final_id, text "rhs" <+> ppr expr2 ])
    
    882
    -        ; return ( floats `addLetFlts` unitLetFloat bind, Var final_id ) }
    
    945
    +        ; return ( assertPpr (not (needsCaseBinding expr_ty expr2)) (ppr bind) $
    
    946
    +                         -- See bindingOk and Note [Cannot trivialise]
    
    947
    +                   floats `snocOL` bind, Var final_id ) }
    
    883 948
       where
    
    884 949
         id_info = vanillaIdInfo `setDemandInfo` dmd
    
    885 950
         expr_ty = exprType expr
    
    886 951
     
    
    887 952
     bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
    
    888
    --- True iff we can have a binding of this expression at this level
    
    953
    +-- True iff we can have a let-binding of this expression at this level
    
    889 954
     -- Precondition: the type is the type of the expression
    
    955
    +-- See Note [Cannot trivialise]
    
    890 956
     bindingOk top_lvl expr expr_ty
    
    891 957
       | isTopLevel top_lvl = exprIsTopLevelBindable expr expr_ty
    
    892
    -  | otherwise          = True
    
    958
    +  | otherwise          = not (needsCaseBinding expr_ty expr)
    
    893 959
     
    
    894 960
     {- Note [Cannot trivialise]
    
    895 961
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    896
    -Consider:
    
    897
    -   f :: Int -> Addr#
    
    962
    +The goal of makeTrivial (when called from prepareRhs) is to transform
    
    963
    +    x = Just (f y)
    
    964
    +into
    
    965
    +    x = let z = f y in Just z
    
    966
    +and thence, by floating, into
    
    967
    +    z = f y
    
    968
    +    x = Just z
    
    969
    +so that x is bound to a value.  It returns only let-bindings (LetFloats), so
    
    970
    +sometimes it cannot trivialise its argument, and must return it unchanged.
    
    971
    +
    
    972
    +(CT1) Nested bindings.  Suppose that (f y) had type Int#, with a different data
    
    973
    +  constructor Just' :: Int# -> T.  Then we cannot let-bind (f y), because that
    
    974
    +  would violate the let-can-float invariant (unless (f y) is ok-for-speculation).
    
    975
    +  We could case-bind it instead, to get
    
    976
    +       x = case f y of r -> Just' r
    
    977
    +  but there is no point: x is no more of a value than it was before.  So we
    
    978
    +  lose nothing by not trivialising (f y); CorePrep will case-bind it anyway.
    
    979
    +  Hence the needsCaseBinding test in bindingOk.  (See also #27910.)
    
    980
    +
    
    981
    +  makeTrivialArg, called from mkDupableCont, may therefore return a non-trivial
    
    982
    +  argument, which may then be duplicated into several branches.  That duplicates
    
    983
    +  code but not work, since only one branch is executed.
    
    898 984
     
    
    899
    -   foo :: Bar
    
    900
    -   foo = Bar (f 3)
    
    985
    +(CT2) Top-level bindings.  Consider:
    
    986
    +     f :: Int -> Addr#
    
    901 987
     
    
    902
    -Then we can't ANF-ise foo, even though we'd like to, because
    
    903
    -we can't make a top-level binding for the Addr# (f 3). And if
    
    904
    -so we don't want to turn it into
    
    905
    -   foo = let x = f 3 in Bar x
    
    906
    -because we'll just end up inlining x back, and that makes the
    
    907
    -simplifier loop.  Better not to ANF-ise it at all.
    
    988
    +     foo :: Bar
    
    989
    +     foo = Bar (f 3)
    
    908 990
     
    
    909
    -Literal strings are an exception.
    
    991
    +  Then we can't ANF-ise foo, even though we'd like to, because
    
    992
    +  we can't make a top-level binding for the Addr# (f 3). And if
    
    993
    +  so we don't want to turn it into
    
    994
    +     foo = let x = f 3 in Bar x
    
    995
    +  because we'll just end up inlining x back, and that makes the
    
    996
    +  simplifier loop.  Better not to ANF-ise it at all.
    
    910 997
     
    
    911
    -   foo = Ptr "blob"#
    
    998
    +  Literal strings are an exception.
    
    912 999
     
    
    913
    -We want to turn this into:
    
    1000
    +     foo = Ptr "blob"#
    
    914 1001
     
    
    915
    -   foo1 = "blob"#
    
    916
    -   foo = Ptr foo1
    
    1002
    +  We want to turn this into:
    
    917 1003
     
    
    918
    -See Note [Core top-level string literals] in GHC.Core.
    
    1004
    +     foo1 = "blob"#
    
    1005
    +     foo = Ptr foo1
    
    1006
    +
    
    1007
    +  See Note [Core top-level string literals] in GHC.Core.
    
    919 1008
     
    
    920 1009
     ************************************************************************
    
    921 1010
     *                                                                      *
    
    ... ... @@ -1191,7 +1280,7 @@ simplExprC env expr cont
    1191 1280
             ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
    
    1192 1281
               -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
    
    1193 1282
               -- pprTrace "simplExprC ret4" (ppr (seLetFloats env')) $
    
    1194
    -          return (wrapFloats floats expr') }
    
    1283
    +          simplWrapFloats (seMode env) floats expr' (contResultType cont) }
    
    1195 1284
     
    
    1196 1285
     --------------------------------------------------
    
    1197 1286
     simplExprF :: SimplEnv
    
    ... ... @@ -1282,18 +1371,20 @@ simplExprF1 env expr@(Lam {}) cont
    1282 1371
             -- NB: countArgs counts all the args (incl type args)
    
    1283 1372
             -- and likewise drop counts all binders (incl type lambdas)
    
    1284 1373
     
    
    1285
    -simplExprF1 env (Case scrut bndr _ alts) cont
    
    1374
    +simplExprF1 env expr@(Case scrut bndr _ alts) cont
    
    1375
    +  | Just (inner, outer) <- splitContForNoCaseCase env cont
    
    1376
    +       -- See (COC-INV) in Note [sm_case_case: switching off case continuations]
    
    1377
    +  = do { (floats, expr') <- simplExprF env expr inner
    
    1378
    +       ; rebuildWithFloats env floats expr' outer }
    
    1379
    +
    
    1380
    +  | otherwise
    
    1286 1381
       = {-#SCC "simplExprF1-Case" #-}
    
    1287 1382
         simplExprF env scrut (Select { sc_bndr = bndr, sc_alts = alts
    
    1288 1383
                                      , sc_env = UnSimplified env, sc_cont = cont })
    
    1289 1384
     
    
    1290
    -simplExprF1 env (Let (Rec pairs) body) cont
    
    1291
    -  | Just pairs' <- joinPointBindings_maybe pairs
    
    1292
    -  = {-#SCC "simplRecJoinPoin" #-} simplRecJoinPoint env pairs' body cont
    
    1293
    -
    
    1294
    -  | otherwise
    
    1295
    -  = {-#SCC "simplRecE" #-} simplRecE env pairs body cont
    
    1385
    +-- Let-expressions
    
    1296 1386
     
    
    1387
    +-- Try to eiminate the let altogether
    
    1297 1388
     simplExprF1 env (Let (NonRec bndr rhs) body) cont
    
    1298 1389
       | Type ty <- rhs    -- First deal with type lets (let a = Type ty in e)
    
    1299 1390
       = {-#SCC "simplExprF1-NonRecLet-Type" #-}
    
    ... ... @@ -1308,18 +1399,42 @@ simplExprF1 env (Let (NonRec bndr rhs) body) cont
    1308 1399
              tick (PreInlineUnconditionally bndr)
    
    1309 1400
            ; simplExprF env' body cont }
    
    1310 1401
     
    
    1311
    -  -- Now check for a join point.  It's better to do the preInlineUnconditionally
    
    1312
    -  -- test first, because joinPointBinding_maybe has to eta-expand, so a trivial
    
    1313
    -  -- binding like { j = j2 |> co } would first be eta-expanded and then inlined
    
    1314
    -  -- Better to test preInlineUnconditionally first.
    
    1315
    -  | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
    
    1316
    -  = {-#SCC "simplNonRecJoinPoint" #-}
    
    1317
    -    simplNonRecJoinPoint env bndr' rhs' body cont
    
    1402
    +simplExprF1 env expr@(Let {}) cont
    
    1403
    +  | Just (inner, outer) <- splitContForNoCaseCase env cont
    
    1404
    +       -- See (COC-INV) in Note [sm_case_case: switching off case continuations]
    
    1405
    +  = do { (floats, expr') <- simplExprF env expr inner
    
    1406
    +       ; rebuildWithFloats env floats expr' outer }
    
    1318 1407
     
    
    1319
    -  | otherwise
    
    1408
    +-- Now check for a join point.  It's better to do the preInlineUnconditionally
    
    1409
    +-- test first, because joinPointBinding_maybe has to eta-expand, so a trivial
    
    1410
    +-- binding like { j = j2 |> co } would first be eta-expanded and then inlined
    
    1411
    +-- Better to test preInlineUnconditionally first.
    
    1412
    +--
    
    1413
    +-- Must be after the seCaseCase stuff:  todo: explain why
    
    1414
    +--   Example GHC.Internal.Debug
    
    1415
    +simplExprF1 env (Let bind body) cont
    
    1416
    +  | Just bind' <- joinPointBind_maybe bind
    
    1417
    +  = simplJoinPointBind env bind' body cont
    
    1418
    +
    
    1419
    +-- Non-recursive let
    
    1420
    +simplExprF1 env (Let (NonRec bndr rhs) body) cont
    
    1320 1421
       = {-#SCC "simplNonRecE" #-}
    
    1321 1422
         simplNonRecE env FromLet bndr (rhs, env) body cont
    
    1322 1423
     
    
    1424
    +-- Recursive let
    
    1425
    +simplExprF1 env (Let (Rec pairs) body) cont
    
    1426
    +  = {-#SCC "simplRecE" #-}
    
    1427
    +    simplRecE env pairs body cont
    
    1428
    +
    
    1429
    +
    
    1430
    +splitContForNoCaseCase :: SimplEnv -> SimplCont
    
    1431
    +                       -> Maybe (SimplCont, SimplCont)
    
    1432
    +-- When seCaseCase is off, this function splits `cont` into (inner, outer),
    
    1433
    +-- where `inner` has only applications, and `outer` is non-trivial
    
    1434
    +splitContForNoCaseCase env cont
    
    1435
    +  | seCaseCase env = Nothing
    
    1436
    +  | otherwise      = splitContArgs cont
    
    1437
    +
    
    1323 1438
     {- Note [Avoiding space leaks in OutType]
    
    1324 1439
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1325 1440
     Since the simplifier is run for multiple iterations, we need to ensure
    
    ... ... @@ -1362,6 +1477,13 @@ work. T5631 is a good example of this.
    1362 1477
       emit it into the output program, after obtaining it from
    
    1363 1478
       contResultType. (The hole type in ApplyToTy is only directly used
    
    1364 1479
       to form the result type in a new Stop continuation.)
    
    1480
    +
    
    1481
    +- In particular, the type annotation on a Case is forced by returnCase in
    
    1482
    +  GHC.Core.Opt.Simplify.Utils, where the Case is finally built (via mkCase, or
    
    1483
    +  directly).  Its callers
    
    1484
    +  should not force it themselves: e.g. simplWrapFloats is given the type of the
    
    1485
    +  body, but needs it only if there is a case-float, and forcing it in other
    
    1486
    +  cases can do a lot of unnecessary work.
    
    1365 1487
     -}
    
    1366 1488
     
    
    1367 1489
     ---------------------------------
    
    ... ... @@ -1473,10 +1595,16 @@ simplTick env tickish expr cont
    1473 1595
       -- push the continuation inside the tick.  This has the effect of moving the
    
    1474 1596
       -- tick to the outside of a case or application context, allowing the normal
    
    1475 1597
       -- 'case' and 'application' optimisations to fire.
    
    1598
    +  --
    
    1599
    +  -- We return the tick as a FloatTick, /outside/ the floats from `expr`.
    
    1600
    +  -- So all the code that was covered by the tick (including the floats,
    
    1601
    +  -- notably single-alternative case floats) remains covered, as soft scope
    
    1602
    +  -- requires; and yet `expr'` is exposed to the caller, e.g. for
    
    1603
    +  -- case-of-known-constructor in rebuildWithFloats.
    
    1604
    +  -- See Note [Tick-floats] in GHC.Core.Opt.Simplify.Env
    
    1476 1605
       | tickishHasSoftScope tickish
    
    1477 1606
       = do { (floats, expr') <- simplExprF env expr cont
    
    1478
    -       ; return (floats, mkTick tickish expr')
    
    1479
    -       }
    
    1607
    +       ; return (unitOL (FloatTick tickish) `addFloatBindsF` floats, expr') }
    
    1480 1608
     
    
    1481 1609
       -- Push tick inside if the context looks like this will allow us to
    
    1482 1610
       -- do a case-of-case - see Note [case-of-scc-of-case]
    
    ... ... @@ -1513,9 +1641,8 @@ simplTick env tickish expr cont
    1513 1641
     
    
    1514 1642
       no_floating_past_tick =
    
    1515 1643
         do { let (inc,outc) = splitCont cont
    
    1516
    -       ; (floats, expr1) <- simplExprF env expr inc
    
    1517
    -       ; let expr2    = wrapFloats floats expr1
    
    1518
    -             tickish' = simplTickish env tickish
    
    1644
    +       ; expr2 <- simplExprC env expr inc
    
    1645
    +       ; let tickish' = simplTickish env tickish
    
    1519 1646
            ; rebuild env (mkTick tickish' expr2) outc
    
    1520 1647
            }
    
    1521 1648
     
    
    ... ... @@ -1601,6 +1728,23 @@ simplTick env tickish expr cont
    1601 1728
     rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplFloats, OutExpr)
    
    1602 1729
     rebuild env expr cont = rebuild_go (zapSubstEnv env) expr cont
    
    1603 1730
     
    
    1731
    +rebuildWithFloats :: SimplEnv -> SimplFloats -> OutExpr -> SimplCont
    
    1732
    +                  -> SimplM (SimplFloats, OutExpr)
    
    1733
    +-- (rebuildWithFloats env floats expr cont) rebuilds (let floats in expr)
    
    1734
    +-- with continuation `cont`.  Used only when seCaseCase is off.
    
    1735
    +-- See (COC3) in Note [sm_case_case: switching off case continuations]
    
    1736
    +rebuildWithFloats env floats expr cont
    
    1737
    +  | Select { sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont' } <- cont
    
    1738
    +  , isEmptyJoinFloats (sfJoinFloats floats)
    
    1739
    +  , let env1 = zapSubstEnv env `setInScopeFromF` floats
    
    1740
    +  , Just do_it <- knownConCase_maybe (mkAltEnv env1 se) expr bndr alts cont'
    
    1741
    +  = do { (floats2, res) <- do_it
    
    1742
    +       ; return (floats `addFloats` floats2, res) }
    
    1743
    +
    
    1744
    +  | otherwise
    
    1745
    +  = do { expr' <- simplWrapFloats (seMode env) floats expr (contHoleType cont)
    
    1746
    +       ; rebuild env expr' cont }
    
    1747
    +
    
    1604 1748
     rebuild_go :: HasDebugCallStack
    
    1605 1749
                => SimplEnvIS -> OutExpr -> SimplCont -> SimplM (SimplFloats, OutExpr)
    
    1606 1750
     -- SimplEnvIS: at this point the substitution in the SimplEnv is irrelevant;
    
    ... ... @@ -1655,24 +1799,22 @@ completeBindX env from_what bndr rhs body cont
    1655 1799
       = do { (env1, bndr1)   <- simplNonRecBndr env bndr  -- Lambda binders don't have rules
    
    1656 1800
            ; (floats, expr') <- simplNonRecBody env1 from_what body cont
    
    1657 1801
            -- Do not float floats past the Case binder below
    
    1658
    -       ; let expr'' = wrapFloats floats expr'
    
    1659
    -             case_expr = Case rhs bndr1 (contResultType cont) [Alt DEFAULT [] expr'']
    
    1802
    +       ; let res_ty = contResultType cont
    
    1803
    +       ; expr'' <- simplWrapFloats (seMode env) floats expr' res_ty
    
    1804
    +       ; case_expr <- returnCase rhs bndr1 res_ty [Alt DEFAULT [] expr'']
    
    1660 1805
            ; return (emptyFloats env, case_expr) }
    
    1661 1806
     
    
    1662 1807
       | otherwise -- Make a let-binding
    
    1663 1808
       = do  { (env1, bndr1) <- simplNonRecBndr env bndr
    
    1664 1809
             ; (env2, bndr2) <- addBndrRules env1 bndr bndr1 (BC_Let NotTopLevel NonRecursive)
    
    1665 1810
     
    
    1666
    -        ; let is_strict = isStrictId bndr2
    
    1667
    -              -- isStrictId: use simplified binder because the InId bndr might not have
    
    1668
    -              -- a fixed runtime representation, which isStrictId doesn't expect
    
    1669
    -              -- c.f. Note [Dark corner with representation polymorphism]
    
    1670
    -
    
    1671
    -        ; (rhs_floats, rhs1) <- prepareBinding env NotTopLevel NonRecursive is_strict
    
    1672
    -                                               bndr2 (emptyFloats env) rhs
    
    1811
    +        ; (rhs_lets, lets_in_scope, rhs1)
    
    1812
    +              <- prepareBinding env NotTopLevel NonRecursive
    
    1813
    +                                bndr2 (idType bndr2) (emptyFloats env) rhs
    
    1673 1814
                   -- NB: it makes a surprisingly big difference (5% in compiler allocation
    
    1674 1815
                   -- in T9630) to pass 'env' rather than 'env1'.  It's fine to pass 'env',
    
    1675 1816
                   -- because this is completeBindX, so bndr is not in scope in the RHS.
    
    1817
    +        ; let rhs_floats = mkLetSimplFloats lets_in_scope rhs_lets
    
    1676 1818
     
    
    1677 1819
             ; let env3 = env2 `setInScopeFromF` rhs_floats
    
    1678 1820
             ; (bind_float, env4) <- completeBind (BC_Let NotTopLevel NonRecursive)
    
    ... ... @@ -2015,9 +2157,10 @@ simplNonRecE env from_what bndr (rhs, rhs_se) body cont
    2015 2157
            -- If not, the invariant holds already, and it's optional.
    
    2016 2158
     
    
    2017 2159
            -- (FromBeta Lifted) or FromLet: look at the demand info
    
    2160
    +       -- seCaseCase: see (COC-INV)
    
    2161
    +       -- in Note [sm_case_case: switching off case continuations]
    
    2018 2162
            _ -> seCaseCase env && isStrUsedDmd (idDemandInfo bndr)
    
    2019 2163
     
    
    2020
    -
    
    2021 2164
     ------------------
    
    2022 2165
     simplRecE :: SimplEnv
    
    2023 2166
               -> [(InId, InExpr)]
    
    ... ... @@ -2085,10 +2228,10 @@ is a join point, and what 'cont' is, in a value of type MaybeJoinCont
    2085 2228
     of a SpecConstr-generated RULE for a join point.
    
    2086 2229
     -}
    
    2087 2230
     
    
    2088
    -simplNonRecJoinPoint :: SimplEnv -> InId -> InExpr
    
    2231
    +simplJoinPointBind :: SimplEnv -> InBind
    
    2089 2232
                          -> InExpr -> SimplCont
    
    2090 2233
                          -> SimplM (SimplFloats, OutExpr)
    
    2091
    -simplNonRecJoinPoint env bndr rhs body cont
    
    2234
    +simplJoinPointBind env (NonRec bndr rhs) body cont
    
    2092 2235
        = assert (isJoinId bndr ) $
    
    2093 2236
          wrapJoinCont env cont $ \ env cont ->
    
    2094 2237
          do { -- We push join_cont into the join RHS and the body;
    
    ... ... @@ -2101,12 +2244,7 @@ simplNonRecJoinPoint env bndr rhs body cont
    2101 2244
             ; (floats2, body') <- simplExprF env3 body cont
    
    2102 2245
             ; return (floats1 `addFloats` floats2, body') }
    
    2103 2246
     
    
    2104
    -
    
    2105
    -------------------
    
    2106
    -simplRecJoinPoint :: SimplEnv -> [(InId, InExpr)]
    
    2107
    -                  -> InExpr -> SimplCont
    
    2108
    -                  -> SimplM (SimplFloats, OutExpr)
    
    2109
    -simplRecJoinPoint env pairs body cont
    
    2247
    +simplJoinPointBind env (Rec pairs) body cont
    
    2110 2248
       = wrapJoinCont env cont $ \ env cont ->
    
    2111 2249
         do { let bndrs  = map fst pairs
    
    2112 2250
                  mult   = contHoleScaling cont
    
    ... ... @@ -2125,18 +2263,13 @@ wrapJoinCont :: SimplEnv -> SimplCont
    2125 2263
     -- Deal with making the continuation duplicable if necessary,
    
    2126 2264
     -- and with the no-case-of-case situation.
    
    2127 2265
     wrapJoinCont env cont thing_inside
    
    2128
    -  | contIsStop cont        -- Common case; no need for fancy footwork
    
    2266
    +  | contIsStop cont        -- Fast path: no need for fancy footwork
    
    2129 2267
       = thing_inside env cont
    
    2130 2268
     
    
    2131
    -  | not (seCaseCase env)
    
    2132
    -    -- See Note [Join points with -fno-case-of-case]
    
    2133
    -  = do { (floats1, expr1) <- thing_inside env (mkBoringStop (contHoleType cont))
    
    2134
    -       ; let (floats2, expr2) = wrapJoinFloatsX floats1 expr1
    
    2135
    -       ; (floats3, expr3) <- rebuild (env `setInScopeFromF` floats2) expr2 cont
    
    2136
    -       ; return (floats2 `addFloats` floats3, expr3) }
    
    2137
    -
    
    2138 2269
       | otherwise
    
    2139 2270
         -- Normal case; see Note [Join points and case-of-case]
    
    2271
    +    -- Case-of-case should be /on/ here, else we should not
    
    2272
    +    -- be in wrapJoinCont in the first place
    
    2140 2273
       = do { (floats1, cont')  <- mkDupableCont env cont
    
    2141 2274
            ; (floats2, result) <- thing_inside (env `setInScopeFromF` floats1) cont'
    
    2142 2275
            ; return (floats1 `addFloats` floats2, result) }
    
    ... ... @@ -2166,8 +2299,84 @@ trimJoinCont var (JoinPoint arity) cont
    2166 2299
           = pprPanic "completeCall" $ ppr var $$ ppr cont
    
    2167 2300
     
    
    2168 2301
     
    
    2169
    -{- Note [Join points and case-of-case]
    
    2170
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2302
    +{- Note [sm_case_case: switching off case continuations]
    
    2303
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2304
    +Normally when we come across a `case` expression, we just push a `Select`
    
    2305
    +continuation onto the continuation, roughly like this.
    
    2306
    +   simplExprF (Case scrut alts) cont
    
    2307
    +     = simplExprF scrut (Select alts cont)
    
    2308
    +
    
    2309
    +There are two reasons that we might NOT want to do this
    
    2310
    +
    
    2311
    +1. Loss of full laziness.  The case-of-case transformation can hide
    
    2312
    +   opportunities for let-floating (aka full laziness). For example
    
    2313
    +       rec { f = \y. case (expensive x) of (a,b) -> blah }
    
    2314
    +   We might hope to float the (expensive x) out of the \y-loop.
    
    2315
    +   But if we inline `expensive` we might get
    
    2316
    +      \y. case (case x of I# x' -> body) of (a,b) -> blah
    
    2317
    +   Now if we do case-of-case we get
    
    2318
    +       \y. case x if I# x2 ->
    
    2319
    +           case body of (a,b) -> blah
    
    2320
    +
    
    2321
    +   Sadly, at this point `body` mentions `x2`, so we can't float it out of the \y-loop.
    
    2322
    +
    
    2323
    +2. Pushing a `case` inside a `let` can prevent a join point from being
    
    2324
    +   discovered (#27737).  For example
    
    2325
    +      case (letrec j x y = ... in id (j p q)) of blah
    
    2326
    +   Here `j` is not /yet/ a join point, because it is not tail called, but it
    
    2327
    +   well become one after we inline `id`.  But if we push that `case` inwards
    
    2328
    +   at the same time as inlinine `id` we'll get
    
    2329
    +      letrec j x y = ... in case (j p q) of blah
    
    2330
    +   and now `j` /still/ isn't a join point, and will never become one.  This
    
    2331
    +   matters in practice: #27737
    
    2332
    +
    
    2333
    +Solution in both cases: in the "gentle" simplification phase that precedes the
    
    2334
    +first float-out transformation, never push a `Select` continuation.  So we
    
    2335
    +do not push the `case` inwards.  This behaiour is controlled by the `sm_case_case`
    
    2336
    +field of `SimplMode`, interrogated via `seCaseCase`.
    
    2337
    +
    
    2338
    +Some specifics, for when `sm_case_case` is False:
    
    2339
    +
    
    2340
    +(COC-INV) When `sm_case_case` is False we obey the following invariant:
    
    2341
    +             The SimplCont never contains
    
    2342
    +                - Select
    
    2343
    +                - StrictBind
    
    2344
    +                - StrictArg
    
    2345
    +    This is achieved by testing `seCaseCase` just before pushing any of
    
    2346
    +    those three constructors. Why StrictBind and StrictArg?  Because
    
    2347
    +    they mess with evaluation order in the same way that Select does.
    
    2348
    +
    
    2349
    +(COC1) The (COC-INV) also solves #25055, where we pushed a `case` inside `runRW`:
    
    2350
    +           case (runRW# (\s. body)) of (a,b) -> blah
    
    2351
    +         --->
    
    2352
    +           runRW# (\s. case body of (a,b) -> blah)
    
    2353
    +  Again, we don't want to this when `sm_case_case` is False, but that falls
    
    2354
    +  out as a simple consequence of (COC-INV)
    
    2355
    +
    
    2356
    +(COC2) Supose `sm_case_case` is False, and we are simplifying
    
    2357
    +
    
    2358
    +    case (join j x = <j-rhs> in
    
    2359
    +          case y of
    
    2360
    +             A -> j 1
    
    2361
    +             B -> j 2
    
    2362
    +             C -> e) of <outer-alts>
    
    2363
    +
    
    2364
    +  Usually, we'd push the outer continuation (case . of <outer-alts>) into
    
    2365
    +  both the RHS and the body of the join point j.  But since we aren't doing
    
    2366
    +  case-of-case we could end up with this totally bogus result
    
    2367
    +
    
    2368
    +      join x = case <j-rhs> of <outer-alts> in
    
    2369
    +      case (case y of
    
    2370
    +               A -> j 1
    
    2371
    +               B -> j 2
    
    2372
    +               C -> e) of <outer-alts>
    
    2373
    +
    
    2374
    +   Again, (COC-INV) neatly avoid this bogosity: we never push a Select
    
    2375
    +   onto the continuation.  This is much nicer than switching off case-of-case
    
    2376
    +   specifically (which we used to do).
    
    2377
    +
    
    2378
    +Note [Join points and case-of-case]
    
    2379
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2171 2380
     When we perform the case-of-case transform (or otherwise push continuations
    
    2172 2381
     inward), we want to treat join points specially. Since they're always
    
    2173 2382
     tail-called and we want to maintain this invariant, we can do this (for any
    
    ... ... @@ -2198,44 +2407,6 @@ optional!
    2198 2407
     We need to make the continuation E duplicable (since we are duplicating it)
    
    2199 2408
     with mkDupableCont.
    
    2200 2409
     
    
    2201
    -Note [Join points with -fno-case-of-case]
    
    2202
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2203
    -Supose case-of-case is switched off, and we are simplifying
    
    2204
    -
    
    2205
    -    case (join j x = <j-rhs> in
    
    2206
    -          case y of
    
    2207
    -             A -> j 1
    
    2208
    -             B -> j 2
    
    2209
    -             C -> e) of <outer-alts>
    
    2210
    -
    
    2211
    -Usually, we'd push the outer continuation (case . of <outer-alts>) into
    
    2212
    -both the RHS and the body of the join point j.  But since we aren't doing
    
    2213
    -case-of-case we may then end up with this totally bogus result
    
    2214
    -
    
    2215
    -    join x = case <j-rhs> of <outer-alts> in
    
    2216
    -    case (case y of
    
    2217
    -             A -> j 1
    
    2218
    -             B -> j 2
    
    2219
    -             C -> e) of <outer-alts>
    
    2220
    -
    
    2221
    -This would be OK in the language of the paper, but not in GHC: j is no longer
    
    2222
    -a join point.  We can only do the "push continuation into the RHS of the
    
    2223
    -join point j" if we also push the continuation right down to the /jumps/ to
    
    2224
    -j, so that it can evaporate there (trimJoinCont). Then, if we are doing
    
    2225
    -case-of-case, we'll get to:
    
    2226
    -
    
    2227
    -    join x = case <j-rhs> of <outer-alts> in
    
    2228
    -    case y of
    
    2229
    -      A -> j 1
    
    2230
    -      B -> j 2
    
    2231
    -      C -> case e of <outer-alts>
    
    2232
    -
    
    2233
    -which is great.
    
    2234
    -
    
    2235
    -Bottom line: if case-of-case is off, we must stop pushing the continuation
    
    2236
    -inwards altogether at any join point.  Instead simplify the (join ... in ...)
    
    2237
    -with a Stop continuation, and wrap the original continuation around the
    
    2238
    -outside.  Surprisingly tricky!
    
    2239 2410
     
    
    2240 2411
     
    
    2241 2412
     ************************************************************************
    
    ... ... @@ -2353,49 +2524,14 @@ simplOutId :: SimplEnvIS -> OutId -> SimplCont -> SimplM (SimplFloats, OutExpr)
    2353 2524
     simplOutId env fun cont
    
    2354 2525
       | fun `hasKey` runRWKey
    
    2355 2526
       , ApplyToTy  { sc_cont = cont1 } <- cont
    
    2356
    -  , ApplyToTy  { sc_cont = cont2, sc_arg_ty = hole_ty } <- cont1
    
    2357
    -  , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_cast = arg_mco
    
    2358
    -               , sc_env = arg_se, sc_hole_ty = fun_ty } <- cont2
    
    2359
    -  -- Do this even if (contIsStop cont), or if seCaseCase is off.
    
    2360
    -  -- See Note [No eta-expansion in runRW#]
    
    2361
    -  = do { let (_saf,arg_env) = mkAltEnv env arg_se
    
    2362
    -
    
    2363
    -             overall_res_ty = contResultType cont3
    
    2364
    -             -- hole_ty is the type of the current runRW# application
    
    2365
    -             (outer_cont, new_runrw_res_ty, inner_cont)
    
    2366
    -                | seCaseCase env = (mkBoringStop overall_res_ty, overall_res_ty, cont3)
    
    2367
    -                | otherwise      = (cont3, hole_ty, mkBoringStop hole_ty)
    
    2368
    -                -- Only when case-of-case is on. See GHC.Driver.Config.Core.Opt.Simplify
    
    2369
    -                --    Note [Case-of-case and full laziness]
    
    2370
    -
    
    2371
    -       -- If the argument is a literal lambda already, take a short cut
    
    2372
    -       -- This isn't just efficiency:
    
    2373
    -       --    * If we don't do this we get a beta-redex every time, so the
    
    2374
    -       --      simplifier keeps doing more iterations.
    
    2375
    -       --    * Even more important: see Note [No eta-expansion in runRW#]
    
    2376
    -       ; arg' <- case arg of
    
    2377
    -           Lam s body -> do { (env', s') <- simplBinder arg_env s
    
    2378
    -                            ; body' <- simplExprC env' body inner_cont
    
    2379
    -                            ; return (Lam s' body') }
    
    2380
    -                            -- Important: do not try to eta-expand this lambda
    
    2381
    -                            -- See Note [No eta-expansion in runRW#]
    
    2382
    -
    
    2383
    -           _ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
    
    2384
    -                   ; let (m,_,_) = splitFunTy fun_ty
    
    2385
    -                         env'  = arg_env `addNewInScopeIds` [s']
    
    2386
    -                         hole_ty = mkVisFunTy m realWorldStatePrimTy new_runrw_res_ty
    
    2387
    -                   ; cont' <- pushCastMCo env' arg_mco $
    
    2388
    -                              ApplyToVal { sc_arg = Var s', sc_cast = MRefl
    
    2389
    -                                         , sc_env = Simplified OkDup
    
    2390
    -                                         , sc_cont = inner_cont
    
    2391
    -                                         , sc_hole_ty = hole_ty }
    
    2392
    -                                -- cont' applies to s', then K
    
    2393
    -                   ; body' <- simplExprC env' arg cont'
    
    2394
    -                   ; return (Lam s' body') }
    
    2395
    -
    
    2396
    -       ; let rr'   = getRuntimeRep new_runrw_res_ty
    
    2397
    -             call' = mkApps (Var fun) [mkTyArg rr', mkTyArg new_runrw_res_ty, arg']
    
    2398
    -       ; rebuild_go env call' outer_cont }
    
    2527
    +  , ApplyToTy  { sc_cont = cont2 } <- cont1
    
    2528
    +  , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_env = arg_se
    
    2529
    +               , sc_cast = arg_mco, sc_hole_ty = fun_ty } <- cont2
    
    2530
    +  = case splitContForNoCaseCase env cont3 of
    
    2531
    +      Nothing -> do { e' <- simplRunRW env fun arg arg_se arg_mco fun_ty cont3
    
    2532
    +                    ; return (emptyFloats env, e') }
    
    2533
    +      Just (ink,outk) -> do { e' <- simplRunRW env fun arg arg_se arg_mco fun_ty ink
    
    2534
    +                            ; rebuild env e' outk }
    
    2399 2535
     
    
    2400 2536
     -- Normal case for (f e1 .. en)
    
    2401 2537
     simplOutId env fun cont
    
    ... ... @@ -2430,6 +2566,51 @@ simplOutId env fun cont
    2430 2566
            ; rebuildCall env arg_info cont
    
    2431 2567
         } } } } }
    
    2432 2568
     
    
    2569
    +simplRunRW :: SimplEnv
    
    2570
    +           -> OutId        -- runRW#
    
    2571
    +           -> CoreExpr     -- Main value argument `e` of runRW#
    
    2572
    +           -> StaticEnv    -- ...and its static envt
    
    2573
    +           -> MOutCoercion -- ...and its MCoercion
    
    2574
    +           -> OutType      -- Type of (runRW# @k @ty), always t1->t2
    
    2575
    +           -> SimplCont    -- Continuation to push into body of `e`
    
    2576
    +           -> SimplM OutExpr
    
    2577
    +simplRunRW env fun arg arg_se arg_mco fun_ty cont
    
    2578
    +  -- Do this even if (contIsStop cont), or if seCaseCase is off.
    
    2579
    +  -- See Note [No eta-expansion in runRW#]
    
    2580
    +  = do { let (_saf,arg_env) = mkAltEnv env arg_se
    
    2581
    +
    
    2582
    +             overall_res_ty = contResultType cont
    
    2583
    +             -- hole_ty is the type of the current runRW# application
    
    2584
    +
    
    2585
    +       -- If the argument is a literal lambda already, take a short cut
    
    2586
    +       -- This isn't just efficiency:
    
    2587
    +       --    * If we don't do this we get a beta-redex every time, so the
    
    2588
    +       --      simplifier keeps doing more iterations.
    
    2589
    +       --    * Even more important: see Note [No eta-expansion in runRW#]
    
    2590
    +       ; arg' <- case arg of
    
    2591
    +           Lam s body -> do { (env', s') <- simplBinder arg_env s
    
    2592
    +                            ; body' <- simplExprC env' body cont
    
    2593
    +                            ; return (Lam s' body') }
    
    2594
    +                            -- Important: do not try to eta-expand this lambda
    
    2595
    +                            -- See Note [No eta-expansion in runRW#]
    
    2596
    +
    
    2597
    +           _ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
    
    2598
    +                   ; let (m,_,_) = splitFunTy fun_ty
    
    2599
    +                         env'    = arg_env `addNewInScopeIds` [s']
    
    2600
    +                         hole_ty = mkVisFunTy m realWorldStatePrimTy overall_res_ty
    
    2601
    +                   ; cont' <- pushCastMCo env' arg_mco $
    
    2602
    +                              ApplyToVal { sc_arg     = Var s', sc_cast = MRefl
    
    2603
    +                                         , sc_env     = Simplified OkDup
    
    2604
    +                                         , sc_cont    = cont
    
    2605
    +                                         , sc_hole_ty = hole_ty }
    
    2606
    +                                -- cont' applies to s', then K
    
    2607
    +                   ; body' <- simplExprC env' arg cont'
    
    2608
    +                   ; return (Lam s' body') }
    
    2609
    +
    
    2610
    +       ; let rr'   = getRuntimeRep overall_res_ty
    
    2611
    +             call' = mkApps (Var fun) [mkTyArg rr', mkTyArg overall_res_ty, arg']
    
    2612
    +       ; return call' }
    
    2613
    +
    
    2433 2614
     ---------------------------------------------------------
    
    2434 2615
     --      Dealing with a call site
    
    2435 2616
     
    
    ... ... @@ -2460,8 +2641,8 @@ rebuildCall env fun_info
    2460 2641
                             , sc_hole_ty = fun_ty, sc_cont = cont })
    
    2461 2642
       | UnSimplified arg_env <- arg_se
    
    2462 2643
       , isStrictArgInfo fun_info  -- Strict arguments
    
    2463
    -  , seCaseCase env            -- But only when case-of-case is on.
    
    2464
    -                              -- See Note [Case-of-case and full laziness]
    
    2644
    +  , seCaseCase env            -- But only when case-of-case is on; see (COC-INV)
    
    2645
    +                              -- in Note [sm_case_case: switching off case continuations]
    
    2465 2646
       = simplExprF (arg_env `setInScopeFromE` env) arg $
    
    2466 2647
         addCastMCo arg_mco $
    
    2467 2648
         StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
    
    ... ... @@ -2469,7 +2650,7 @@ rebuildCall env fun_info
    2469 2650
                   , sc_cont = cont }
    
    2470 2651
                     -- Note [Shadowing in the Simplifier]
    
    2471 2652
     
    
    2472
    -  | otherwise      -- Lazy, or already simplified arguments
    
    2653
    +  | otherwise      -- Lazy, or already simplified arguments, or -fno-case-of-case
    
    2473 2654
       -- DO NOT float anything outside, hence simplExprC
    
    2474 2655
       -- There is no benefit (unlike in a let-binding), and we'd
    
    2475 2656
       -- have to be very careful about bogus strictness through
    
    ... ... @@ -2753,14 +2934,10 @@ fireRuleAFTER env rule_match arg_specs cont
    2753 2934
       | RM { rm_rule = rule, rm_rhs = rhs, rm_args = rhs_args
    
    2754 2935
            , rm_floats = float_bs } <- rule_match
    
    2755 2936
       = do { let env' = env `addNewInScopeIds` floatsBinders float_bs
    
    2756
    -       ; (floats, e') <- simplExprF env' rhs $
    
    2757
    -                         pushOutArgs (exprType rhs) rhs_args $
    
    2758
    -                         pushArgSpecs (drop (ruleArity rule) arg_specs) cont
    
    2759
    -       ; return $
    
    2760
    -         if isEmptyFloatBinds float_bs  -- Not very pretty
    
    2761
    -         then (floats, e')
    
    2762
    -         else (emptyFloats env', GHC.Core.Make.wrapFloats float_bs $
    
    2763
    -                                 wrapFloats floats e') }
    
    2937
    +       ; addFloatBinds (contHoleScaling cont) float_bs $
    
    2938
    +         simplExprF env' rhs $
    
    2939
    +         pushOutArgs (exprType rhs) rhs_args $
    
    2940
    +         pushArgSpecs (drop (ruleArity rule) arg_specs) cont }
    
    2764 2941
     
    
    2765 2942
     
    
    2766 2943
     tryRules :: SimplEnv -> [CoreRule]
    
    ... ... @@ -3223,41 +3400,9 @@ rebuildCase, reallyRebuildCase
    3223 3400
     --      1. Eliminate the case if there's a known constructor
    
    3224 3401
     --------------------------------------------------
    
    3225 3402
     
    
    3226
    -rebuildCase (saf,env) scrut case_bndr alts cont
    
    3227
    -  | Lit lit <- scrut    -- No need for same treatment as constructors
    
    3228
    -                        -- because literals are inlined more vigorously
    
    3229
    -  , not (litIsLifted lit)
    
    3230
    -  = do  { tick (KnownBranch case_bndr)
    
    3231
    -        ; case findAlt (LitAlt lit) alts of
    
    3232
    -            Nothing             -> missingAlt env case_bndr alts cont
    
    3233
    -            Just (Alt _ bs rhs) -> simpl_rhs env scrut bs rhs }
    
    3234
    -
    
    3235
    -  | Just (in_scope', wfloats, con, ty_args, other_args)
    
    3236
    -      <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
    
    3237
    -        -- Works when the scrutinee is a variable with a known unfolding
    
    3238
    -        -- as well as when it's an explicit constructor application
    
    3239
    -  , let env0 = setInScopeSet env in_scope'
    
    3240
    -  = do  { tick (KnownBranch case_bndr)
    
    3241
    -        ; let -- case_bndr_unf: see Note [Do not duplicate constructor applications]
    
    3242
    -              case_bndr_rhs | exprIsTrivial scrut = scrut
    
    3243
    -                            | otherwise           = con_app
    
    3244
    -              con_app = Var (dataConWorkId con) `mkTyApps` ty_args
    
    3245
    -                                                `mkApps`   other_args
    
    3246
    -        ; wrapDataConFloats env wfloats case_bndr cont $
    
    3247
    -          case findAlt (DataAlt con) alts of
    
    3248
    -            Nothing                   -> missingAlt env0 case_bndr alts cont
    
    3249
    -            Just (Alt DEFAULT bs rhs) -> simpl_rhs env0 case_bndr_rhs bs rhs
    
    3250
    -            Just (Alt _       bs rhs) -> knownCon env0 scrut con other_args
    
    3251
    -                                                  case_bndr bs rhs cont
    
    3252
    -        }
    
    3253
    -  where
    
    3254
    -    simpl_rhs env case_bndr_rhs bs rhs
    
    3255
    -      = assert (null bs) $
    
    3256
    -        do { (floats1, env') <- simplAuxBind (saf,env) case_bndr case_bndr_rhs
    
    3257
    -               -- scrut is a constructor application,
    
    3258
    -               -- hence satisfies let-can-float invariant
    
    3259
    -           ; (floats2, expr') <- simplExprF env' rhs cont
    
    3260
    -           ; return (floats1 `addFloats` floats2, expr') }
    
    3403
    +rebuildCase saf_env scrut case_bndr alts cont
    
    3404
    +  | Just do_it <- knownConCase_maybe saf_env scrut case_bndr alts cont
    
    3405
    +  = do_it
    
    3261 3406
     
    
    3262 3407
     --------------------------------------------------
    
    3263 3408
     --      2. Eliminate the case if scrutinee is evaluated
    
    ... ... @@ -3318,54 +3463,74 @@ rebuildCase (saf,env) scrut case_bndr alts cont
    3318 3463
       | otherwise
    
    3319 3464
       = reallyRebuildCase (saf,env) scrut case_bndr alts cont
    
    3320 3465
     
    
    3321
    -doCaseToLet :: OutExpr          -- Scrutinee
    
    3322
    -            -> InId             -- Case binder
    
    3323
    -            -> Bool
    
    3324
    --- The situation is         case scrut of b { DEFAULT -> body }
    
    3325
    --- Can we transform thus?   let { b = scrut } in body
    
    3326
    -doCaseToLet scrut case_bndr
    
    3327
    -  | isTyCoVar case_bndr    -- Respect GHC.Core
    
    3328
    -  = isTyCoArg scrut        -- Note [Core type and coercion invariant]
    
    3329
    -
    
    3330
    -  | isUnliftedType (exprType scrut)
    
    3331
    -    -- We can call isUnliftedType here: scrutinees always have a fixed RuntimeRep (see FRRCase).
    
    3332
    -    -- Note however that we must check 'scrut' (which is an 'OutExpr') and not 'case_bndr'
    
    3333
    -    -- (which is an 'InId'): see Note [Dark corner with representation polymorphism].
    
    3334
    -    -- Using `exprType` is typically cheap because `scrut` is typically a variable.
    
    3335
    -    -- We could instead use mightBeUnliftedType (idType case_bndr), but that hurts
    
    3336
    -    -- the brain more.  Consider that if this test ever turns out to be a perf
    
    3337
    -    -- problem (which seems unlikely).
    
    3338
    -  = exprOkForSpeculation scrut
    
    3339
    -
    
    3340
    -  | otherwise  -- Scrut has a lifted type
    
    3341
    -  = exprIsHNF scrut
    
    3342
    -       --    || isStrUsedDmd (idDemandInfo case_bndr)
    
    3343
    -       -- We no longer look at the demand on the case binder
    
    3344
    -       -- See Note [Case-to-let for strictly-used binders]
    
    3345
    -
    
    3346 3466
     --------------------------------------------------
    
    3347 3467
     --      3. Catch-all case
    
    3348 3468
     --------------------------------------------------
    
    3349 3469
     
    
    3350 3470
     reallyRebuildCase (saf,env) scrut case_bndr alts cont
    
    3351
    -  | not (seCaseCase env)    -- Only when case-of-case is on.
    
    3352
    -                            -- See GHC.Driver.Config.Core.Opt.Simplify
    
    3353
    -                            --    Note [Case-of-case and full laziness]
    
    3354
    -  = do { case_expr <- simplAlts (saf,env) scrut case_bndr alts
    
    3355
    -                                (mkBoringStop (contHoleType cont))
    
    3356
    -       ; rebuild env case_expr cont }
    
    3357
    -
    
    3358
    -  | otherwise
    
    3359
    -  = do { (floats, env', cont') <- mkDupableCaseCont env alts cont
    
    3360
    -       ; case_expr <- simplAlts (saf,env') scrut
    
    3361
    -                                (scaleIdBy holeScaling case_bndr)
    
    3362
    -                                (scaleAltsBy holeScaling alts)
    
    3363
    -                                cont'
    
    3364
    -       ; return (floats, case_expr) }
    
    3471
    +  = do { (alt_env, scrut', case_bndr', imposs_deflt_cons, in_alts)
    
    3472
    +             <- prepareCase (saf,env) scrut (scaleIdBy holeScaling case_bndr)
    
    3473
    +                                            (scaleAltsBy holeScaling alts)
    
    3474
    +       ; case in_alts of
    
    3475
    +           [in_alt] -> rebuildSingleAltCase (saf,alt_env) scrut' case_bndr'
    
    3476
    +                                            imposs_deflt_cons bndr_swap cont in_alt
    
    3477
    +           _        -> rebuildMultiAltCase (saf,alt_env) scrut' case_bndr'
    
    3478
    +                                           imposs_deflt_cons bndr_swap cont in_alts }
    
    3365 3479
       where
    
    3366 3480
         holeScaling = contHoleScaling cont
    
    3367 3481
         -- Note [Scaling in case-of-case]
    
    3368 3482
     
    
    3483
    +    bndr_swap = scrutOkForBinderSwap scrut
    
    3484
    +
    
    3485
    +rebuildSingleAltCase :: (SimplAltFlag, SimplEnv)
    
    3486
    +                     -> OutExpr -> OutId       -- Scrutinee and case binder
    
    3487
    +                     -> [AltCon]               -- Constructors impossible in the DEFAULT alt
    
    3488
    +                     -> BinderSwapDecision
    
    3489
    +                     -> SimplCont
    
    3490
    +                     -> InAlt
    
    3491
    +                     -> SimplM (SimplFloats, OutExpr)
    
    3492
    +-- The arguments are prepared by prepareCase
    
    3493
    +-- We return the case as a FloatCase float, so that the floats from its RHS
    
    3494
    +-- are not trapped inside it.  See Note [Floating single-alternative cases]
    
    3495
    +-- There is only one alternative, so no need to make `cont` dupable
    
    3496
    +rebuildSingleAltCase (saf,alt_env) scrut' case_bndr' imposs_deflt_cons bndr_swap cont in_alt
    
    3497
    +  = do { (con, bs', alt_floats, rhs') <- simplAlt (saf,alt_env) (Just scrut') imposs_deflt_cons
    
    3498
    +                                                  case_bndr' bndr_swap cont in_alt
    
    3499
    +       ; let no_floats = emptyFloats alt_env
    
    3500
    +             case_float
    
    3501
    +               | DEFAULT <- con
    
    3502
    +               , doCaseToLet scrut' case_bndr'
    
    3503
    +               = -- Make a let-float, not a case-float, to maintain invariant
    
    3504
    +                 -- (FFC1) of Note [Case-floats] in GHC.Core.Opt.Simplify.Env.
    
    3505
    +                 -- We get here (rather than doing case-to-let in rebuildCase) when
    
    3506
    +                 -- prepareAlts has pruned away all but the DEFAULT alternative
    
    3507
    +                 no_floats `addLetFloat` NonRec case_bndr' scrut'
    
    3508
    +               | otherwise
    
    3509
    +               = addCaseFloat no_floats scrut' case_bndr' con bs'
    
    3510
    +       ; return (case_float `addFloats` alt_floats, rhs') }
    
    3511
    +
    
    3512
    +rebuildMultiAltCase :: (SimplAltFlag, SimplEnv)
    
    3513
    +                    -> OutExpr -> OutId       -- Scrutinee and case binder
    
    3514
    +                    -> [AltCon]               -- Constructors impossible in the DEFAULT alt
    
    3515
    +                    -> BinderSwapDecision
    
    3516
    +                    -> SimplCont
    
    3517
    +                    -> [InAlt]
    
    3518
    +                    -> SimplM (SimplFloats, OutExpr)
    
    3519
    +-- The arguments are prepared by prepareCase
    
    3520
    +rebuildMultiAltCase (saf,alt_env) scrut' case_bndr' imposs_deflt_cons bndr_swap cont in_alts
    
    3521
    +  = do { -- NB: pass alt_env, not the env before prepareCase, to mkDupableCaseCont,
    
    3522
    +         -- so that the case binder stays in scope in env'
    
    3523
    +         (floats, env', cont') <- mkDupableCaseCont alt_env in_alts cont
    
    3524
    +       ; traceSmpl "rebuildMultiAltCase" (vcat [ ppr case_bndr'
    
    3525
    +                                               , text "cont':" <+> ppr cont'
    
    3526
    +                                               , text "in_scope" <+> ppr (seInScope env') ])
    
    3527
    +       ; alts' <- forM in_alts $
    
    3528
    +                  simplAltC (saf,env') (Just scrut') imposs_deflt_cons
    
    3529
    +                            case_bndr' bndr_swap cont'
    
    3530
    +       ; case_expr <- mkCase (seMode env') scrut' case_bndr' (contResultType cont') alts'
    
    3531
    +                      -- mkCase forces the type; see Note [Avoiding space leaks in OutType]
    
    3532
    +       ; return (floats, case_expr) }
    
    3533
    +
    
    3369 3534
     {-
    
    3370 3535
     simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
    
    3371 3536
     try to eliminate uses of v in the RHSs in favour of case_bndr; that
    
    ... ... @@ -3466,7 +3631,6 @@ robust here. (Otherwise, there's a danger that we'll simply drop the
    3466 3631
     
    
    3467 3632
     Note [Scaling in case-of-case]
    
    3468 3633
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    3469
    -
    
    3470 3634
     When two cases commute, if done naively, the multiplicities will be wrong:
    
    3471 3635
     
    
    3472 3636
       case (case u of w[1] { (x[1], y[1]) } -> f x y) of w'[Many]
    
    ... ... @@ -3498,17 +3662,16 @@ scale the entire case we are simplifying, by a scaling factor which can be
    3498 3662
     computed in the continuation (with function `contHoleScaling`).
    
    3499 3663
     -}
    
    3500 3664
     
    
    3501
    -simplAlts :: (SimplAltFlag, SimplEnv)
    
    3502
    -          -> OutExpr                       -- Scrutinee
    
    3503
    -          -> InId -> [InAlt]  -- Alts (non-empty)
    
    3504
    -          -> SimplCont
    
    3505
    -          -> SimplM OutExpr  -- Returns the complete simplified case expression
    
    3506
    -
    
    3507
    -simplAlts (saf,env0) scrut case_bndr alts cont'
    
    3508
    -  = do  { traceSmpl "simplAlts" (vcat [ ppr case_bndr
    
    3509
    -                                      , text "cont':" <+> ppr cont'
    
    3510
    -                                      , text "in_scope" <+> ppr (seInScope env0) ])
    
    3511
    -        ; (env1, case_bndr1) <- simplAltIdBinder (saf,env0) case_bndr
    
    3665
    +prepareCase :: (SimplAltFlag, SimplEnv)
    
    3666
    +            -> OutExpr          -- Scrutinee
    
    3667
    +            -> InId -> [InAlt]  -- Case binder and alts (non-empty)
    
    3668
    +            -> SimplM ( SimplEnv   -- For the alternatives
    
    3669
    +                      , OutExpr    -- Scrutinee, perhaps improved by improveSeq
    
    3670
    +                      , OutId      -- Case binder
    
    3671
    +                      , [AltCon]   -- Constructors impossible in the DEFAULT alt
    
    3672
    +                      , [InAlt] )  -- Alternatives, from prepareAlts
    
    3673
    +prepareCase (saf,env0) scrut case_bndr alts
    
    3674
    +  = do  { (env1, case_bndr1) <- simplAltIdBinder (saf,env0) case_bndr
    
    3512 3675
             ; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
    
    3513 3676
                   env2       = modifyInScope env1 case_bndr2
    
    3514 3677
                   -- See Note [Case binder evaluated-ness]
    
    ... ... @@ -3523,15 +3686,34 @@ simplAlts (saf,env0) scrut case_bndr alts cont'
    3523 3686
               -- NB: pass case_bndr::InId, not case_bndr' :: OutId, to prepareAlts
    
    3524 3687
               --     See Note [Shadowing in prepareAlts] in GHC.Core.Opt.Simplify.Utils
    
    3525 3688
     
    
    3526
    -        ; alts' <- forM in_alts $
    
    3527
    -            simplAlt (saf,alt_env') (Just scrut') imposs_deflt_cons
    
    3528
    -                     case_bndr' (scrutOkForBinderSwap scrut) cont'
    
    3529
    -
    
    3530
    -        ; let alts_ty' = contResultType cont'
    
    3531
    -        -- See Note [Avoiding space leaks in OutType]
    
    3532
    -        ; seqType alts_ty' `seq`
    
    3533
    -          mkCase (seMode env0) scrut' case_bndr' alts_ty' alts' }
    
    3689
    +        ; return (alt_env', scrut', case_bndr', imposs_deflt_cons, in_alts) }
    
    3534 3690
     
    
    3691
    +{- Note [Floating single-alternative cases]
    
    3692
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    3693
    +When reallyRebuildCase finds a single-alternative case (after prepareAlts)
    
    3694
    +   case e of b { (# a, c #) -> let x1 = .. in ... let xn = .. in (# e1, e2 #) }
    
    3695
    +it does not return the case expression; instead it returns
    
    3696
    +  * floats:  [FloatCase e b (# a,c #) [a,c], x1 = .., ..., xn = ..]
    
    3697
    +  * result:  (# e1, e2 #)
    
    3698
    +This is done by rebuildSingleAltCase.  See Note [LetFloats] in GHC.Core.Opt.Simplify.Env.
    
    3699
    +
    
    3700
    +Why?  Because a caller (notably rebuildWithFloats, when case-of-case is
    
    3701
    +switched off) may want to do case-of-known-constructor on the result. If we
    
    3702
    +returned the whole case, exprIsConApp_maybe would have to walk all the way
    
    3703
    +down through the case and the lets, which can be quadratic (#27737, T18223).
    
    3704
    +
    
    3705
    +This is not restricted to the no-case-of-case path: when case-of-case is on,
    
    3706
    +the continuation has already been pushed into the alternative, and the
    
    3707
    +floats are simply wrapped around the result, or floated further out of a
    
    3708
    +strict let (which a StrictBind continuation would do anyway).  The
    
    3709
    +FloatFlag (FltCareful or FltOkSpec) stops a case-float from floating out of
    
    3710
    +a lazy let, or to top level; see doFloatFromRhs.
    
    3711
    +
    
    3712
    +We do not call mkCase when we build the FloatCase.  Instead, simplWrapFloats
    
    3713
    +calls mkCase when we eventually wrap the FloatCase around an expression, so we
    
    3714
    +still get case-merging, identity-case elimination, caseRules, etc.
    
    3715
    +See Note [Wrapping case-floats with mkCase] in GHC.Core.Opt.Simplify.Utils.
    
    3716
    +-}
    
    3535 3717
     
    
    3536 3718
     ------------------------------------
    
    3537 3719
     improveSeq :: (FamInstEnv, FamInstEnv)
    
    ... ... @@ -3552,6 +3734,16 @@ improveSeq _ (_,env) scrut _ case_bndr1 _
    3552 3734
     
    
    3553 3735
     
    
    3554 3736
     ------------------------------------
    
    3737
    +simplAltC :: (SimplAltFlag, SimplEnv) -> Maybe OutExpr -> [AltCon] -> OutId
    
    3738
    +          -> BinderSwapDecision -> SimplCont -> InAlt
    
    3739
    +          -> SimplM OutAlt
    
    3740
    +-- Like simplAlt, but wraps the floats around the RHS
    
    3741
    +simplAltC env scrut' imposs_deflt_cons case_bndr' bndr_swap' cont' alt
    
    3742
    +  = do { (con, bs, floats, rhs) <- simplAlt env scrut' imposs_deflt_cons
    
    3743
    +                                            case_bndr' bndr_swap' cont' alt
    
    3744
    +       ; rhs' <- simplWrapFloats (seMode (snd env)) floats rhs (contResultType cont')
    
    3745
    +       ; return (Alt con bs rhs') }
    
    3746
    +
    
    3555 3747
     simplAlt :: (SimplAltFlag, SimplEnv)
    
    3556 3748
              -> Maybe OutExpr       -- The scrutinee
    
    3557 3749
              -> [AltCon]            -- These constructors can't be present when
    
    ... ... @@ -3561,19 +3753,24 @@ simplAlt :: (SimplAltFlag, SimplEnv)
    3561 3753
                                     --           add unfolding `v :-> bndr |> sym co`
    
    3562 3754
              -> SimplCont
    
    3563 3755
              -> InAlt
    
    3564
    -         -> SimplM OutAlt
    
    3756
    +         -> SimplM (AltCon, [OutVar], SimplFloats, OutExpr)
    
    3757
    +         -- Returns the simplified alternative, in pieces
    
    3758
    +         -- The floats scope over the RHS only, and may mention the
    
    3759
    +         -- binders of the alternative.  So the caller must either wrap
    
    3760
    +         -- them around the RHS (simplAltC), or put them after a case-float
    
    3761
    +         -- that binds the binders (rebuildSingleAltCase)
    
    3565 3762
     
    
    3566 3763
     simplAlt (saf,env) _scrut' imposs_deflt_cons case_bndr' bndr_swap' cont' (Alt DEFAULT bndrs rhs)
    
    3567 3764
       = assert (null bndrs) $
    
    3568 3765
         do  { let env' = addDefaultUnfoldings env case_bndr' bndr_swap' imposs_deflt_cons
    
    3569
    -        ; rhs' <- simplAltExprC (saf,env') rhs cont'
    
    3570
    -        ; return (Alt DEFAULT [] rhs') }
    
    3766
    +        ; (floats, rhs') <- simplAltExprF (saf,env') rhs cont'
    
    3767
    +        ; return (DEFAULT, [], floats, rhs') }
    
    3571 3768
     
    
    3572 3769
     simplAlt (saf,env) _scrut' _ case_bndr' bndr_swap' cont' (Alt (LitAlt lit) bndrs rhs)
    
    3573 3770
       = assert (null bndrs) $
    
    3574 3771
         do  { let env' = addAltUnfoldings env case_bndr' bndr_swap' (Lit lit)
    
    3575
    -        ; rhs' <- simplAltExprC (saf,env') rhs cont'
    
    3576
    -        ; return (Alt (LitAlt lit) [] rhs') }
    
    3772
    +        ; (floats, rhs') <- simplAltExprF (saf,env') rhs cont'
    
    3773
    +        ; return (LitAlt lit, [], floats, rhs') }
    
    3577 3774
     
    
    3578 3775
     simplAlt (saf,env) scrut' _ case_bndr' bndr_swap' cont' (Alt (DataAlt con) vs rhs)
    
    3579 3776
       = do  { -- See Note [Adding evaluatedness info to pattern-bound variables]
    
    ... ... @@ -3591,8 +3788,8 @@ simplAlt (saf,env) scrut' _ case_bndr' bndr_swap' cont' (Alt (DataAlt con) vs rh
    3591 3788
                   con_app = mkConApp2 con inst_tys' vs'
    
    3592 3789
                   env''   = addAltUnfoldings env' case_bndr' bndr_swap' con_app
    
    3593 3790
     
    
    3594
    -        ; rhs' <- simplAltExprC (saf,env'') rhs cont'
    
    3595
    -        ; return (Alt (DataAlt con) vs' rhs') }
    
    3791
    +        ; (floats, rhs') <- simplAltExprF (saf,env'') rhs cont'
    
    3792
    +        ; return (DataAlt con, vs', floats, rhs') }
    
    3596 3793
     
    
    3597 3794
     {- Note [Adding evaluatedness info to pattern-bound variables]
    
    3598 3795
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -3773,11 +3970,6 @@ simplAltExprF (saf,env) expr cont
    3773 3970
           SAF_Out -> simplOutExpr env expr cont
    
    3774 3971
           SAF_In  -> simplExprF   env expr cont
    
    3775 3972
     
    
    3776
    -simplAltExprC :: (SimplAltFlag, SimplEnv) -> CoreExpr -> SimplCont -> SimplM OutExpr
    
    3777
    -simplAltExprC env expr cont
    
    3778
    -  = do { (floats, expr') <- simplAltExprF env expr cont
    
    3779
    -       ; return (wrapFloats floats expr') }
    
    3780
    -
    
    3781 3973
     
    
    3782 3974
     {- Note [Case binder evaluated-ness]
    
    3783 3975
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -3854,48 +4046,69 @@ All this should happen in one sweep.
    3854 4046
     
    
    3855 4047
     Note [FloatBinds from constructor wrappers]
    
    3856 4048
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    3857
    -If we have FloatBinds coming from the constructor wrapper
    
    3858
    -(as in Note [exprIsConApp_maybe on data constructors with wrappers]),
    
    3859
    -we cannot float past them. We'd need to float the FloatBind
    
    3860
    -together with the simplify floats, unfortunately the
    
    3861
    -simplifier doesn't have case-floats. The simplest thing we can
    
    3862
    -do is to wrap all the floats here. The next iteration of the
    
    3863
    -simplifier will take care of all these cases and lets.
    
    4049
    +exprIsConApp_maybe may return FloatBinds, e.g. coming from a constructor
    
    4050
    +wrapper (as in Note [exprIsConApp_maybe on data constructors with wrappers]),
    
    4051
    +or from looking through lets and single-alternative cases in the scrutinee.
    
    4052
    +These floats scope over the result of case-of-known-constructor.
    
    4053
    +
    
    4054
    +Since the Simplifier's floats can contain case-floats as well as let-floats
    
    4055
    +(see Note [LetFloats] in GHC.Core.Opt.Simplify.Env), we simply add them to
    
    4056
    +the SimplFloats, outside the floats from simplifying the alternative; see
    
    4057
    +knownConCase_maybe.  We do not wrap them around the result, because then a
    
    4058
    +subsequent case-of-known-constructor on the result would have to walk
    
    4059
    +through them all over again, which can be quadratic (#27737).
    
    3864 4060
     
    
    3865 4061
     Given data T = MkT !Bool, this allows us to simplify
    
    3866 4062
     case $WMkT b of { MkT x -> f x }
    
    3867 4063
     to
    
    3868 4064
     case b of { b' -> f b' }.
    
    3869
    -
    
    3870
    -We could try and be more clever (like maybe `wfloats` only contains
    
    3871
    -let binders, so we could float them). But the need for the extra
    
    3872
    -complication is not clear.
    
    3873 4065
     -}
    
    3874 4066
     
    
    3875
    -wrapDataConFloats :: SimplEnv -> FloatBinds -> InId -> SimplCont
    
    3876
    -                 -> SimplM (SimplFloats, OutExpr)
    
    3877
    -                 -> SimplM (SimplFloats, OutExpr)
    
    3878
    --- See Note [FloatBinds from constructor wrappers]
    
    3879
    -wrapDataConFloats env wfloats case_bndr cont thing_inside
    
    3880
    -  | isEmptyFloatBinds wfloats
    
    3881
    -  = thing_inside
    
    3882
    -  | otherwise
    
    3883
    -  = do { (floats, expr) <- thing_inside
    
    3884
    -       ; return ( emptyFloats env
    
    3885
    -                , GHC.Core.Make.wrapFloats (fmap scale_float wfloats) $
    
    3886
    -                  wrapFloats floats expr ) }
    
    3887
    -  where
    
    3888
    -    -- scale_float scales case-floats by the multiplicity of the continuation hole
    
    3889
    -    -- (see Note [Scaling in case-of-case]).
    
    3890
    -    -- Let floats are _not_ scaled, because they are aliases anyway.
    
    3891
    -    scale_float (GHC.Core.FloatCase scrut case_bndr con vars)
    
    3892
    -      = GHC.Core.FloatCase scrut (scale_id case_bndr) con (map scale_id vars)
    
    3893
    -    scale_float flt@(GHC.Core.FloatLet {})  = flt
    
    3894
    -    scale_float flt@(GHC.Core.FloatTick {}) = flt
    
    4067
    +knownConCase_maybe :: (SimplAltFlag, SimplEnv)
    
    4068
    +                   -> OutExpr          -- Scrutinee
    
    4069
    +                   -> InId             -- Case binder
    
    4070
    +                   -> [InAlt]          -- Alternatives (increasing order)
    
    4071
    +                   -> SimplCont
    
    4072
    +                   -> Maybe (SimplM (SimplFloats, OutExpr))
    
    4073
    +-- Case-of-known-constructor: returns Just if the scrutinee is a literal
    
    4074
    +-- or (via exprIsConApp_maybe) a constructor application
    
    4075
    +knownConCase_maybe (saf,env) scrut case_bndr alts cont
    
    4076
    +  | Lit lit <- scrut    -- No need for same treatment as constructors
    
    4077
    +                        -- because literals are inlined more vigorously
    
    4078
    +  , not (litIsLifted lit)
    
    4079
    +  = Just $
    
    4080
    +    do  { tick (KnownBranch case_bndr)
    
    4081
    +        ; case findAlt (LitAlt lit) alts of
    
    4082
    +            Nothing             -> missingAlt env case_bndr alts cont
    
    4083
    +            Just (Alt _ bs rhs) -> simpl_rhs env scrut bs rhs }
    
    3895 4084
     
    
    3896
    -    scale_id id = scaleVarBy holeScaling id
    
    4085
    +  | Just (in_scope', wfloats, con, ty_args, other_args)
    
    4086
    +      <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
    
    4087
    +        -- Works when the scrutinee is a variable with a known unfolding
    
    4088
    +        -- as well as when it's an explicit constructor application
    
    4089
    +  , let env0 = setInScopeSet env in_scope'
    
    4090
    +  = Just $
    
    4091
    +    do  { tick (KnownBranch case_bndr)
    
    4092
    +        ; let -- case_bndr_unf: see Note [Do not duplicate constructor applications]
    
    4093
    +              case_bndr_rhs | exprIsTrivial scrut = scrut
    
    4094
    +                            | otherwise           = con_app
    
    4095
    +              con_app = Var (dataConWorkId con) `mkTyApps` ty_args
    
    4096
    +                                                `mkApps`   other_args
    
    4097
    +          -- The wfloats scope over the result
    
    4098
    +          -- See Note [FloatBinds from constructor wrappers]
    
    4099
    +        ; addFloatBinds hole_scaling wfloats $
    
    4100
    +          case findAlt (DataAlt con) alts of
    
    4101
    +            Nothing                   -> missingAlt env0 case_bndr alts cont
    
    4102
    +            Just (Alt DEFAULT bs rhs) -> simpl_rhs env0 case_bndr_rhs bs rhs
    
    4103
    +            Just (Alt _       bs rhs) -> knownCon env0 scrut con other_args
    
    4104
    +                                                  case_bndr bs rhs cont }
    
    3897 4105
     
    
    3898
    -    holeScaling = contHoleScaling cont `mkMultMul` idMult case_bndr
    
    4106
    +  | otherwise
    
    4107
    +  = Nothing
    
    4108
    +  where
    
    4109
    +    hole_scaling = idMult case_bndr `mkMultMul` contHoleScaling cont
    
    4110
    +     -- See Note [Scaling in case-of-case]
    
    4111
    +     -- This is the contHoleScaling of the original Select continuation
    
    3899 4112
          -- We are in the following situation
    
    3900 4113
          --   case[p] case[q] u of { D x -> C v } of { C x -> w }
    
    3901 4114
          -- And we are producing case[??] u of { D x -> w[x\v]}
    
    ... ... @@ -3911,6 +4124,33 @@ wrapDataConFloats env wfloats case_bndr cont thing_inside
    3911 4124
          -- Which is ill-typed with respect to linearity. So it needs to be a
    
    3912 4125
          -- case[Many].
    
    3913 4126
     
    
    4127
    +    simpl_rhs env case_bndr_rhs bs rhs
    
    4128
    +      = assert (null bs) $
    
    4129
    +        do { (floats1, env') <- simplAuxBind (saf,env) case_bndr case_bndr_rhs
    
    4130
    +               -- scrut is a constructor application,
    
    4131
    +               -- hence satisfies let-can-float invariant
    
    4132
    +           ; (floats2, expr') <- simplExprF env' rhs cont
    
    4133
    +           ; return (floats1 `addFloats` floats2, expr') }
    
    4134
    +
    
    4135
    +addFloatBinds :: Mult -> FloatBinds
    
    4136
    +              -> SimplM (SimplFloats, a) -> SimplM (SimplFloats, a)
    
    4137
    +-- (addFloatBinds scaling fbs thing_inside) adds `fbs` outside the floats
    
    4138
    +-- returned by `thing_inside`.  The `scaling` is the multiplicity of the
    
    4139
    +-- continuation hole, by which case-floats are scaled, because they now
    
    4140
    +-- scope over that continuation: see Note [Scaling in case-of-case].
    
    4141
    +-- Let floats do not need this treatment
    
    4142
    +addFloatBinds scaling fbs thing_inside
    
    4143
    +  | isEmptyFloatBinds fbs     -- Short cut
    
    4144
    +  = thing_inside
    
    4145
    +  | otherwise
    
    4146
    +  = do { (floats, res) <- thing_inside
    
    4147
    +       ; return (fmap scale_float fbs `addFloatBindsF` floats, res) }
    
    4148
    +  where
    
    4149
    +    scale_float (FloatCase scrut b con vars)
    
    4150
    +      = FloatCase scrut (scale_id b) con (map scale_id vars)
    
    4151
    +    scale_float flt = flt
    
    4152
    +
    
    4153
    +    scale_id id = scaleVarBy scaling id
    
    3914 4154
     
    
    3915 4155
     knownCon :: SimplEnv
    
    3916 4156
              -> OutExpr                                  -- The scrutinee
    
    ... ... @@ -4149,8 +4389,8 @@ mkDupableContWithDmds env _
    4149 4389
               -- No need to use mkDupableCont before simplNonRecBody; we
    
    4150 4390
               -- use cont once here, and then share the result if necessary
    
    4151 4391
     
    
    4152
    -       ; let join_body = wrapFloats floats1 join_inner
    
    4153
    -             res_ty    = contResultType cont
    
    4392
    +       ; let res_ty = contResultType cont
    
    4393
    +       ; join_body <- simplWrapFloats (seMode env) floats1 join_inner res_ty
    
    4154 4394
     
    
    4155 4395
            ; mkDupableStrictBind env bndr' join_body res_ty }
    
    4156 4396
     
    
    ... ... @@ -4185,7 +4425,8 @@ mkDupableContWithDmds env _
    4185 4425
            ; arg_bndr <- newId (fsLit "arg") m arg_ty
    
    4186 4426
            ; let env' = env `addNewInScopeIds` [arg_bndr]
    
    4187 4427
            ; (floats, join_rhs) <- rebuildCall env' (addValArgTo fun (Var arg_bndr) fun_ty) cont
    
    4188
    -       ; mkDupableStrictBind env' arg_bndr (wrapFloats floats join_rhs) rhs_ty }
    
    4428
    +       ; join_rhs' <- simplWrapFloats (seMode env) floats join_rhs rhs_ty
    
    4429
    +       ; mkDupableStrictBind env' arg_bndr join_rhs' rhs_ty }
    
    4189 4430
       where
    
    4190 4431
         thumbsUpPlanA (StrictArg {})               = False
    
    4191 4432
         thumbsUpPlanA (StrictBind {})              = True
    
    ... ... @@ -4244,7 +4485,7 @@ mkDupableContWithDmds env _
    4244 4485
                                         scaleIdBy cont_scaling case_bndr
    
    4245 4486
     
    
    4246 4487
             ; alts' <- forM (scaleAltsBy cont_scaling alts) $
    
    4247
    -            simplAlt (saf,alt_env1) Nothing [] case_bndr' NoBinderSwap alt_cont
    
    4488
    +            simplAltC (saf,alt_env1) Nothing [] case_bndr' NoBinderSwap alt_cont
    
    4248 4489
                     -- Safe to say that there are no handled-cons for the DEFAULT case
    
    4249 4490
                     -- NB: simplBinder does not zap deadness occ-info, so
    
    4250 4491
                     -- a dead case_bndr' will still advertise its deadness
    

  • compiler/GHC/Core/Opt/Simplify/Utils.hs
    ... ... @@ -8,7 +8,7 @@ The simplifier utilities
    8 8
     
    
    9 9
     module GHC.Core.Opt.Simplify.Utils (
    
    10 10
             -- Rebuilding
    
    11
    -        rebuildLam, mkCase, prepareAlts,
    
    11
    +        rebuildLam, mkCase, returnCase, prepareAlts, simplWrapFloats,
    
    12 12
             tryEtaExpandRhs, wantEtaExpansion,
    
    13 13
     
    
    14 14
             -- Inlining,
    
    ... ... @@ -28,7 +28,7 @@ module GHC.Core.Opt.Simplify.Utils (
    28 28
             contIsTrivial, contArgs, contIsRhs, mkBottomCont,
    
    29 29
             hasArgs, countArgs, contOutArgs, dropContArgs,
    
    30 30
             mkBoringStop, mkRhsStop, mkLazyArgStop,
    
    31
    -        interestingCallContext,
    
    31
    +        interestingCallContext, splitContArgs,
    
    32 32
     
    
    33 33
             -- ArgInfo
    
    34 34
             ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo,
    
    ... ... @@ -74,12 +74,13 @@ import GHC.Types.InlinePragma
    74 74
     import GHC.Types.Tickish
    
    75 75
     import GHC.Types.Demand
    
    76 76
     import GHC.Types.Var.Set
    
    77
    +import GHC.Types.Var.Env ( InScopeSet )
    
    77 78
     import GHC.Types.Basic
    
    78 79
     import GHC.Types.Name.Env
    
    79 80
     
    
    80 81
     import GHC.Data.List.Infinite ( Infinite(..) )
    
    81 82
     import qualified GHC.Data.List.Infinite as Inf
    
    82
    -import GHC.Data.OrdList ( isNilOL )
    
    83
    +import GHC.Data.OrdList ( fromOL )
    
    83 84
     import GHC.Data.FastString ( fsLit )
    
    84 85
     
    
    85 86
     import GHC.Utils.Misc
    
    ... ... @@ -173,10 +174,11 @@ data SimplCont
    173 174
           , sc_opt  :: Bool         -- True <=> sc_co has had optCoercion applied to it
    
    174 175
                                     --      See Note [Avoid re-simplifying coercions]
    
    175 176
                                     --      in GHC.Core.Opt.Simplify.Iteration
    
    176
    -      , sc_cont :: SimplCont }
    
    177
    +      , sc_cont :: SimplCont }  -- Invariant: never a CastIt; successive casts
    
    178
    +                                --   are merged (see pushCast in GHC.Core.Opt.Simplify.Iteration)
    
    177 179
     
    
    178 180
       | ApplyToVal         -- (ApplyToVal arg K)[e] = K[ e arg ]
    
    179
    -      { sc_hole_ty :: OutType    -- Type of the function, presumably (forall a. blah)
    
    181
    +      { sc_hole_ty :: OutType    -- Type of the function, presumably (ty1 -> ty2)
    
    180 182
                                      -- See Note [The hole type in ApplyToTy]
    
    181 183
           , sc_env  :: StaticEnv     -- See Note [StaticEnv]
    
    182 184
           , sc_arg  :: CoreExpr      -- The argument
    
    ... ... @@ -495,12 +497,54 @@ contIsDupable :: SimplCont -> Bool
    495 497
     contIsDupable (Stop {})                    = True
    
    496 498
     contIsDupable (ApplyToTy  { sc_cont = k }) = contIsDupable k
    
    497 499
     contIsDupable (ApplyToVal { sc_env = se }) = okToDupSE se -- See (SE1) in Note [StaticEnv]
    
    498
    -contIsDupable (Select { sc_env = se })     = okToDupSE se -- ...ditto...
    
    500
    +contIsDupable (Select { sc_env = se, sc_bndr = bndr, sc_alts = alts, sc_cont = k })
    
    501
    +  = okToDupSE se -- ...ditto...
    
    502
    +    || (isUnpackingAlts bndr alts && contIsDupable k)
    
    503
    +         -- See Note [Duplicating unpacking continuations]
    
    499 504
     contIsDupable (StrictBind { sc_env = se }) = okToDupSE se -- ...ditto...
    
    500 505
     contIsDupable (StrictArg { sc_dup = dup }) = okToDup dup  -- ...ditto...
    
    501 506
     contIsDupable (CastIt { sc_cont = k })     = contIsDupable k
    
    502 507
     contIsDupable (TickIt _ k)                 = contIsDupable k
    
    503 508
     
    
    509
    +isUnpackingAlts :: InId -> [InAlt] -> Bool
    
    510
    +-- True of the alternatives of  case e of b { K x y -> y }
    
    511
    +-- and nested versions thereof;  see Note [Duplicating unpacking continuations]
    
    512
    +isUnpackingAlts case_bndr [Alt _ bndrs rhs] = go (case_bndr : bndrs) rhs
    
    513
    +  where
    
    514
    +    go bound (Var v) = v `elem` bound
    
    515
    +    go bound (Case (Var v) b _ [Alt _ bs rhs])
    
    516
    +      | v `elem` bound = go (b : bs ++ bound) rhs
    
    517
    +    go _ _ = False
    
    518
    +isUnpackingAlts _ _ = False
    
    519
    +
    
    520
    +{- Note [Duplicating unpacking continuations]
    
    521
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    522
    +Worker/wrapper for CPR produces a worker like this
    
    523
    +   $wf = \ds -> case (case ds of { A -> R e1; B -> R e2 }) of ww { __DEFAULT ->
    
    524
    +                case ww of { R y -> y } }
    
    525
    +The intention is that the unboxing (case . of R y -> y) cancels with the boxing
    
    526
    +(R e1) and (R e2).  But the continuation pushed into the inner case is
    
    527
    +   (Select ww [__DEFAULT -> case ww of { R y -> y }])
    
    528
    +which has more than one alternative to go into, so mkDupableCont would make it
    
    529
    +dupable by creating a join point
    
    530
    +   join $j ww = case ww of { __DEFAULT -> case ww of { R y -> y } }
    
    531
    +   in case ds of { A -> jump $j (R e1); B -> jump $j (R e2) }
    
    532
    +That is terrible if $j fails to inline; and even if it does inline, it takes an
    
    533
    +extra Simplifier iteration to tidy up (T15304).
    
    534
    +
    
    535
    +So contIsDupable treats a Select as dupable if its alternatives are "unpacking
    
    536
    +alternatives": a single alternative whose RHS is a variable bound by that
    
    537
    +alternative (a pattern variable or the case binder), or a single-alternative case
    
    538
    +on such a variable whose own RHS is again unpacking, and so on (to allow for nested
    
    539
    +CPR).  Such a continuation is tiny, so duplicating it costs nothing, and then
    
    540
    +case-of-known-constructor cancels it with the constructor in each branch, giving
    
    541
    +   $wf = \ds -> case ds of { A -> e1; B -> e2 }
    
    542
    +
    
    543
    +We insist that the variables are /bound/ by the continuation: a free variable might
    
    544
    +be mapped by the substitution in the (UnSimplified env) to a big expression, which
    
    545
    +we would then duplicate.
    
    546
    +-}
    
    547
    +
    
    504 548
     -------------------
    
    505 549
     contIsTrivial :: SimplCont -> Bool
    
    506 550
     contIsTrivial (Stop {})                                         = True
    
    ... ... @@ -632,6 +676,65 @@ contOutArgs env cont
    632 676
         -- No more arguments
    
    633 677
         go _ = []
    
    634 678
     
    
    679
    +splitContArgs :: SimplCont -> Maybe (SimplCont, SimplCont)
    
    680
    +-- Splits `cont` into (inner, outer), where `inner` has only
    
    681
    +-- applications and casts, and `outer` is non-trivial
    
    682
    +-- A cast goes in `inner` only if it is followed by an application;
    
    683
    +-- see Note [Do not push a cast inwards unnecessarily]
    
    684
    +splitContArgs cont@(ApplyToTy { sc_cont = cont1 })
    
    685
    +  = do { (inner, outer) <- splitContArgs cont1
    
    686
    +       ; return (cont { sc_cont = inner }, outer) }
    
    687
    +splitContArgs cont@(ApplyToVal { sc_cont = cont1 })
    
    688
    +  = do { (inner, outer) <- splitContArgs cont1
    
    689
    +       ; return (cont { sc_cont = inner }, outer) }
    
    690
    +splitContArgs cont@(CastIt { sc_cont = cont1 })
    
    691
    +  | isAppCont cont1   -- No need for isAppCont to look past a CastIt, because
    
    692
    +                      -- cont1 is never a CastIt; see the invariant on CastIt
    
    693
    +  = do { (inner, outer) <- splitContArgs cont1
    
    694
    +       ; return (cont { sc_cont = inner }, outer) }
    
    695
    +splitContArgs outer
    
    696
    +  | contIsStop outer = Nothing
    
    697
    +  | otherwise        = -- pprTrace "splitContHoleType" (ppr hole_ty) $
    
    698
    +                       return (mkBoringStop hole_ty, outer)
    
    699
    +  where
    
    700
    +    hole_ty = contHoleType outer
    
    701
    +
    
    702
    +isAppCont :: SimplCont -> Bool
    
    703
    +-- True of an application continuation
    
    704
    +isAppCont (ApplyToVal {}) = True
    
    705
    +isAppCont (ApplyToTy {})  = True
    
    706
    +isAppCont _               = False
    
    707
    +
    
    708
    +{- Note [Do not push a cast inwards unnecessarily]
    
    709
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    710
    +When case-of-case is off, splitContArgs splits the continuation into an `inner`
    
    711
    +part, which we push into a `case` or `let`, and an `outer` part, which we
    
    712
    +rebuild around the result.  The point of `inner` is to push applications
    
    713
    +inwards, so it should stop as soon as it can.  So a cast goes in `inner` only
    
    714
    +if it is followed by an application, e.g. (CastIt (ApplyToVal ..)); otherwise,
    
    715
    +e.g. (CastIt Stop) or (CastIt (Select ..)), the cast goes in `outer`.
    
    716
    +(Successive casts are merged, so we need not look past a CastIt.)  Consider
    
    717
    +   f x = Wrap (case x of { 0 -> g 10; 1 -> g 20; _ -> g 30 })
    
    718
    +where Wrap is a newtype constructor, so we have a cast round the case.
    
    719
    +If we pushed the cast into the alternatives we would get
    
    720
    +   f = \x -> case x of { 0 -> g 10 |> co; 1 -> g 20 |> co; _ -> g 30 |> co }
    
    721
    +Then
    
    722
    + * We duplicate the coercion in every alternative.  The coercion can be big:
    
    723
    +   for a derived Generic instance, `from` has one alternative per constructor
    
    724
    +   and the coercion mentions the whole representation type, so the total is
    
    725
    +   quadratic (T5642, T16577).
    
    726
    + * We lose cast worker/wrapper: the RHS is no longer of form (e |> co), so
    
    727
    +   we never get   f = $wf |> co.  And nothing ever moves the casts back out
    
    728
    +   of the alternatives, so the duplication lasts all the way to CorePrep.
    
    729
    +
    
    730
    +Leaving the cast in `outer` gives
    
    731
    +   f = \x -> (case x of { 0 -> g 10; 1 -> g 20; _ -> g 30 }) |> co
    
    732
    +We do this for every caller of splitContArgs, including a `let` with join
    
    733
    +points: if we pushed the cast into a join point's RHS we would have to push
    
    734
    +it into every jump too, but the jumps may be in a multi-alternative case
    
    735
    +from which we are keeping it out.
    
    736
    +-}
    
    737
    +
    
    635 738
     dropContArgs :: FullArgCount -> SimplCont -> SimplCont
    
    636 739
     dropContArgs 0 cont = cont
    
    637 740
     dropContArgs n (ApplyToTy  { sc_cont = cont }) = dropContArgs (n-1) cont
    
    ... ... @@ -2408,7 +2511,7 @@ new binding is abstracted. Several points worth noting
    2408 2511
     
    
    2409 2512
           (Why is it OK to float the unlifted `foo` there?
    
    2410 2513
           See Note [Core top-level string literals] in GHC.Core;
    
    2411
    -      it is controlled by GHC.Core.Opt.Simplify.Env.unitLetFloat.)
    
    2514
    +      it is controlled by GHC.Core.Opt.Simplify.Env.getFF_Let.)
    
    2412 2515
     
    
    2413 2516
           It is also necessary to do dependency analysis, because
    
    2414 2517
           otherwise (in #24551) we might get `foo = \@_ -> "missing"#` at the
    
    ... ... @@ -2416,18 +2519,20 @@ new binding is abstracted. Several points worth noting
    2416 2519
           manifestly a literal string.
    
    2417 2520
     -}
    
    2418 2521
     
    
    2419
    -abstractFloats :: UnfoldingOpts -> TopLevelFlag -> [OutTyVar] -> SimplFloats
    
    2420
    -              -> OutExpr -> SimplM ([OutBind], OutExpr)
    
    2421
    -abstractFloats uf_opts top_lvl main_tvs floats body
    
    2522
    +abstractFloats :: UnfoldingOpts -> TopLevelFlag -> [OutTyVar]
    
    2523
    +               -> InScopeSet   -- Includes the binders of the LetFloats
    
    2524
    +               -> LetFloats    -- Let-bindings only: see (PB1) in Note [prepareBinding]
    
    2525
    +                               -- in GHC.Core.Opt.Simplify.Iteration
    
    2526
    +               -> OutExpr -> SimplM ([OutBind], OutExpr)
    
    2527
    +abstractFloats uf_opts top_lvl main_tvs in_scope floats body
    
    2422 2528
       = assert (notNull body_floats) $
    
    2423
    -    assert (isNilOL (sfJoinFloats floats)) $
    
    2424 2529
         do  { let sccs = concatMap to_sccs body_floats
    
    2425 2530
             ; (subst, float_binds) <- mapAccumLM abstract empty_subst sccs
    
    2426 2531
             ; return (float_binds, GHC.Core.Subst.substExpr subst body) }
    
    2427 2532
       where
    
    2428 2533
         is_top_lvl  = isTopLevel top_lvl
    
    2429
    -    body_floats = letFloatBinds (sfLetFloats floats)
    
    2430
    -    empty_subst = GHC.Core.Subst.mkEmptySubst (sfInScope floats)
    
    2534
    +    body_floats = fromOL floats
    
    2535
    +    empty_subst = GHC.Core.Subst.mkEmptySubst in_scope
    
    2431 2536
     
    
    2432 2537
         -- See wrinkle (AB5) in Note [Which type variables to abstract over]
    
    2433 2538
         -- for why we need to re-do dependency analysis
    
    ... ... @@ -2862,7 +2967,64 @@ and now we can do case-merge again, getting the desired
    2862 2967
     
    
    2863 2968
     -}
    
    2864 2969
     
    
    2865
    -mkCase, mkCase1, mkCase2, mkCase3
    
    2970
    +simplWrapFloats :: SimplMode -> SimplFloats
    
    2971
    +                -> OutExpr      -- The body
    
    2972
    +                -> OutType      -- The type of the body
    
    2973
    +                -> SimplM OutExpr
    
    2974
    +-- Wrap the floats around the body, using mkCase for case-floats
    
    2975
    +-- See Note [Wrapping case-floats with mkCase]
    
    2976
    +simplWrapFloats mode (SimplFloats { sfLetFloats = lfs, sfJoinFloats = jbs }) body body_ty
    
    2977
    +  = go (fromOL lfs)
    
    2978
    +  where
    
    2979
    +    go []         = return (wrapJoinFloats jbs body)
    
    2980
    +                    -- Always safe to put the joins on the inside,
    
    2981
    +                    -- since the values can't refer to them
    
    2982
    +    go (fb : fbs) = do { body' <- go fbs; wrap fb body' }
    
    2983
    +
    
    2984
    +    wrap (FloatLet bind)    body = return (Let bind body)
    
    2985
    +    wrap (FloatTick t)      body = return (mkTick t body)
    
    2986
    +    wrap (FloatCase scrut bndr con bs) body
    
    2987
    +      = mkCase mode scrut bndr body_ty [Alt con bs body]
    
    2988
    +        -- NB: we must not force body_ty if there are no case-floats; that can
    
    2989
    +        -- do a lot of unnecessary work.  mkCase forces it when it builds the Case;
    
    2990
    +        -- see Note [Avoiding space leaks in OutType] in GHC.Core.Opt.Simplify.Iteration
    
    2991
    +        -- body_ty: lets, ticks and cases do not change the type, so every
    
    2992
    +        -- case-float has the same result type: the type of the original body.
    
    2993
    +        -- And body_ty comes from outside, so it cannot mention `bs`
    
    2994
    +
    
    2995
    +{- Note [Wrapping case-floats with mkCase]
    
    2996
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2997
    +The Simplifier returns a single-alternative case as a FloatCase, rather than
    
    2998
    +building it with mkCase; see Note [Floating single-alternative cases] in
    
    2999
    +GHC.Core.Opt.Simplify.Iteration.  So when we eventually wrap the floats around
    
    3000
    +an expression, simplWrapFloats uses mkCase for each FloatCase, so that we get
    
    3001
    +all the things that mkCase does: case-merging, identity-case elimination,
    
    3002
    +caseRules, etc.  For example, case-merging turns
    
    3003
    +     case x of b { DEFAULT -> case b of { A -> e1; B -> e2 } }
    
    3004
    +into  case x of b { A -> e1; B -> e2 }
    
    3005
    +which arises, for example, from  x `seq` case x of { A -> e1; B -> e2 }.
    
    3006
    +
    
    3007
    +Is the case-merging expensive?  mergeCaseAlts looks past lets (wrinkle (MC4) of
    
    3008
    +Note [Merge Nested Cases] in GHC.Core.Utils), but it stops at anything else,
    
    3009
    +such as a case that does not scrutinise the case binder.  So in a chain
    
    3010
    +    FloatCase e1 b1, lets1, FloatCase e2 b2, lets2, ...
    
    3011
    +each let is examined by only one FloatCase, and the total cost is linear.
    
    3012
    +
    
    3013
    +It could be quadratic if successive FloatCases evaluated the /same/ value:
    
    3014
    +    FloatCase e b1, FloatCase b1 b2, FloatCase b2 b3, lots of lets, case b3 of alts
    
    3015
    +Then each FloatCase merges with the case below it, floating the lets out again,
    
    3016
    +so that the next one looks past all of them again.  But such a chain does not
    
    3017
    +survive simplification: a case whose scrutinee is already evaluated (such as
    
    3018
    +the case binder b1 of an enclosing case) is eliminated by rebuildCase (see
    
    3019
    +Note [Case to let transformation] in GHC.Core.Opt.Simplify.Iteration) long before
    
    3020
    +it becomes a FloatCase.  (Calling mkCase on every case, as we used to, has
    
    3021
    +exactly the same theoretical exposure.)
    
    3022
    +
    
    3023
    +We do not use simplWrapFloats for the FloatBinds returned by the rule matcher;
    
    3024
    +GHC.Core.Make.wrapFloats is fine for those.
    
    3025
    +-}
    
    3026
    +
    
    3027
    +mkCase, mkCase1, mkCase2
    
    2866 3028
        :: SimplMode
    
    2867 3029
        -> OutExpr -> OutId
    
    2868 3030
        -> OutType -> [OutAlt]               -- Alternatives in standard (increasing) order
    
    ... ... @@ -2957,12 +3119,12 @@ mkCase2 mode scrut bndr alts_ty alts
    2957 3119
                       -- See Note [Unreachable caseRules alternatives]
    
    2958 3120
                       -- in GHC.Core.Opt.ConstantFold
    
    2959 3121
     
    
    2960
    -       ; mkCase3 mode scrut' bndr' alts_ty $
    
    3122
    +       ; returnCase scrut' bndr' alts_ty $
    
    2961 3123
              add_default (re_sort alts')
    
    2962 3124
            }
    
    2963 3125
     
    
    2964 3126
       | otherwise
    
    2965
    -  = mkCase3 mode scrut bndr alts_ty alts
    
    3127
    +  = returnCase scrut bndr alts_ty alts
    
    2966 3128
       where
    
    2967 3129
         -- We need to keep the correct association between the scrutinee and its
    
    2968 3130
         -- binder if the latter isn't dead. Hence we wrap rhs of alternatives with
    
    ... ... @@ -3039,8 +3201,12 @@ in GHC.Core.Opt.ConstantFold)
    3039 3201
     --------------------------------------------------
    
    3040 3202
     --      Catch-all
    
    3041 3203
     --------------------------------------------------
    
    3042
    -mkCase3 _mode scrut bndr alts_ty alts
    
    3043
    -  = return (Case scrut bndr alts_ty alts)
    
    3204
    +returnCase :: OutExpr -> OutId -> OutType -> [OutAlt] -> SimplM OutExpr
    
    3205
    +-- Build the Case, forcing alts_ty as we emit it into the output program
    
    3206
    +-- See Note [Avoiding space leaks in OutType] in GHC.Core.Opt.Simplify.Iteration
    
    3207
    +returnCase scrut bndr alts_ty alts
    
    3208
    +  = seqType alts_ty `seq`
    
    3209
    +    return (Case scrut bndr alts_ty alts)
    
    3044 3210
     
    
    3045 3211
     -- See Note [Exitification] and Note [Do not inline exit join points] in
    
    3046 3212
     -- GHC.Core.Opt.Exitify
    

  • compiler/GHC/Core/SimpleOpt.hs
    ... ... @@ -11,7 +11,7 @@ module GHC.Core.SimpleOpt (
    11 11
             simpleOptPgm, simpleOptExpr, simpleOptExprNoInline, simpleOptExprWith,
    
    12 12
     
    
    13 13
             -- ** Join points
    
    14
    -        joinPointBinding_maybe, joinPointBindings_maybe,
    
    14
    +        joinPointBinding_maybe, joinPointBindings_maybe, joinPointBind_maybe,
    
    15 15
     
    
    16 16
             -- ** Predicates on expressions
    
    17 17
             exprIsConApp_maybe, exprIsLiteral_maybe, exprIsLambda_maybe,
    
    ... ... @@ -1199,6 +1199,18 @@ joinPointBindings_maybe :: [(InBndr, InExpr)] -> Maybe [(InBndr, InExpr)]
    1199 1199
     joinPointBindings_maybe bndrs
    
    1200 1200
       = mapM (uncurry joinPointBinding_maybe) bndrs
    
    1201 1201
     
    
    1202
    +joinPointBind_maybe :: InBind -> Maybe InBind
    
    1203
    +joinPointBind_maybe (NonRec bndr rhs)
    
    1204
    +  | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
    
    1205
    +  = Just (NonRec bndr' rhs')
    
    1206
    +
    
    1207
    +joinPointBind_maybe (Rec pairs)
    
    1208
    +  | Just pairs' <- joinPointBindings_maybe pairs
    
    1209
    +  = Just (Rec pairs')
    
    1210
    +
    
    1211
    +joinPointBind_maybe _other
    
    1212
    +  = Nothing
    
    1213
    +
    
    1202 1214
     {- Note [JoinId vs TailCallInfo]
    
    1203 1215
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1204 1216
     * Occurrence information is /fundamentally fragile/; that is, it may
    
    ... ... @@ -1542,7 +1554,8 @@ exprIsConApp_maybe :: HasDebugCallStack
    1542 1554
                        => InScopeEnv -> CoreExpr
    
    1543 1555
                        -> Maybe (InScopeSet, FloatBinds, DataCon, [Type], [CoreExpr])
    
    1544 1556
     exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
    
    1545
    -  = go (Left in_scope) emptyFloatBinds expr (CC [] MRefl)
    
    1557
    +  = -- pprTrace "exprIsConApp" (ppr expr) $
    
    1558
    +    go (Left in_scope) emptyFloatBinds expr (CC [] MRefl)
    
    1546 1559
       where
    
    1547 1560
         go :: Either InScopeSet Subst
    
    1548 1561
                  -- Left in-scope  means "empty substitution"
    
    ... ... @@ -1655,7 +1668,8 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
    1655 1668
             | idArity fun == 0
    
    1656 1669
             , Just rhs <- expandUnfolding_maybe unfolding
    
    1657 1670
             , let in_scope' = extend_in_scope (exprFreeVars rhs)
    
    1658
    -        = go (Left in_scope') floats rhs cont
    
    1671
    +        = -- pprTrace "exprIsConApp:unf" (ppr fun <+> ppr rhs) $
    
    1672
    +          go (Left in_scope') floats rhs cont
    
    1659 1673
     
    
    1660 1674
             -- See Note [exprIsConApp_maybe on literal strings]
    
    1661 1675
             | (fun `hasKey` unpackCStringIdKey) ||
    
    ... ... @@ -1695,17 +1709,21 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
    1695 1709
         subst_co (Right s) co = GHC.Core.Subst.substCo s co
    
    1696 1710
     
    
    1697 1711
         subst_expr (Left {}) e = e
    
    1698
    -    subst_expr (Right s) e = substExpr s e
    
    1712
    +    subst_expr (Right s) e = -- pprTrace "subst_expr" (text "subst" <+> ppr s $$ text "expr" <+> ppr e) $
    
    1713
    +                             substExpr s e
    
    1699 1714
     
    
    1700
    -    subst_bndr msubst bndr
    
    1701
    -      = (Right subst', bndr')
    
    1715
    +    subst_bndrs subst bs = mapAccumL subst_bndr subst bs
    
    1716
    +
    
    1717
    +    subst_bndr (Left in_scope) bndr
    
    1718
    +      | bndr `elemInScopeSet` in_scope = subst_bndr1 (mkEmptySubst in_scope) bndr
    
    1719
    +      | otherwise                      = (Left (in_scope `extendInScopeSet` bndr), bndr)
    
    1720
    +    subst_bndr (Right subst) bndr = subst_bndr1 subst bndr
    
    1721
    +
    
    1722
    +    subst_bndr1 subst bndr
    
    1723
    +      = -- pprTrace "subst_bndr1" (ppr bndr <+> ppr bndr' $$ ppr subst) $
    
    1724
    +        (Right subst', bndr')
    
    1702 1725
           where
    
    1703 1726
             (subst', bndr') = substBndr subst bndr
    
    1704
    -        subst = case msubst of
    
    1705
    -                  Left in_scope -> mkEmptySubst in_scope
    
    1706
    -                  Right subst   -> subst
    
    1707
    -
    
    1708
    -    subst_bndrs subst bs = mapAccumL subst_bndr subst bs
    
    1709 1727
     
    
    1710 1728
         extend (Left in_scope) v e = Right (extendSubst (mkEmptySubst in_scope) v e)
    
    1711 1729
         extend (Right s)       v e = Right (extendSubst s v e)
    

  • compiler/GHC/Core/Type.hs
    ... ... @@ -55,7 +55,7 @@ module GHC.Core.Type (
    55 55
             splitForAllForAllTyBinders, splitForAllForAllTyBinder_maybe,
    
    56 56
             splitForAllTyCoVar_maybe, splitForAllTyCoVar,
    
    57 57
             splitForAllTyVar_maybe, splitForAllCoVar_maybe,
    
    58
    -        splitPiTy_maybe, splitPiTy, splitPiTys, collectPiTyBinders,
    
    58
    +        splitPiTy_maybe, splitPiTy, splitPiTys, splitUninstantiatedValArgTys,
    
    59 59
             getRuntimeArgTys,
    
    60 60
             mkTyConBindersPreferAnon,
    
    61 61
             mkPiTy, mkPiTys,
    
    ... ... @@ -263,7 +263,6 @@ import GHC.Utils.Monad.StrictReader
    263 263
     
    
    264 264
     import GHC.Data.FastString
    
    265 265
     import GHC.Data.Maybe   ( orElse, isJust )
    
    266
    -import GHC.List (build)
    
    267 266
     
    
    268 267
     -- $type_classification
    
    269 268
     -- #type_classification#
    
    ... ... @@ -1599,17 +1598,20 @@ splitPiTys ty = split ty ty []
    1599 1598
         split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
    
    1600 1599
         split orig_ty _                bs = (reverse bs, orig_ty)
    
    1601 1600
     
    
    1602
    -collectPiTyBinders :: Type -> [PiTyBinder]
    
    1603
    -collectPiTyBinders ty = build $ \c n ->
    
    1604
    -  let
    
    1605
    -    split (ForAllTy b res) = Named b `c` split res
    
    1606
    -    split (FunTy { ft_af = af, ft_mult = w, ft_arg = arg, ft_res = res })
    
    1607
    -                           = Anon (Scaled w arg) af `c` split res
    
    1608
    -    split ty | Just ty' <- coreView ty = split ty'
    
    1609
    -    split _                = n
    
    1610
    -  in
    
    1611
    -    split ty
    
    1612
    -{-# INLINE collectPiTyBinders #-}
    
    1601
    +splitUninstantiatedValArgTys :: Type -> [Type]
    
    1602
    +-- This function takes a type apart, returning all its /value/
    
    1603
    +-- argument types (including (forall (co::t1~t2).t)
    
    1604
    +-- doing no instantiation at all.
    
    1605
    +-- E.g. splitUinstantiatedValArgTys (forall a. a -> Int -> T a)
    
    1606
    +--         returns [a, Int]
    
    1607
    +-- It's a pretty specialised function, hence its long name
    
    1608
    +splitUninstantiatedValArgTys ty = go ty
    
    1609
    +  where
    
    1610
    +    go (ForAllTy (Bndr b _) res) | isCoVar b  = varType b : go res
    
    1611
    +                                 | otherwise  = go res
    
    1612
    +    go (FunTy { ft_arg = arg, ft_res = res }) = arg : go res
    
    1613
    +    go ty | Just ty' <- coreView ty = go ty'
    
    1614
    +    go _ = []
    
    1613 1615
     
    
    1614 1616
     -- | Extracts a list of run-time arguments from a function type,
    
    1615 1617
     -- looking through newtypes to the right of arrows.
    

  • compiler/GHC/Core/Utils.hs
    ... ... @@ -804,6 +804,9 @@ mkSingleAltCase scrut case_bndr con bndrs body
    804 804
         body_ty = exprType body
    
    805 805
     
    
    806 806
         case_ty -- See Note [Care with the type of a case expression]
    
    807
    +      | not (any isTyCoVar bndrs)   -- Fast path: only TyCoVars can occur in body_ty
    
    808
    +      = body_ty
    
    809
    +
    
    807 810
           | Just body_ty' <- occCheckExpand bndrs body_ty
    
    808 811
           = body_ty'
    
    809 812
     
    
    ... ... @@ -2207,6 +2210,8 @@ fun_always_ok _ = True
    2207 2210
     -- | A special version of 'exprOkForSpeculation' used during
    
    2208 2211
     -- Note [Speculative evaluation]. When the predicate arg `fun_ok` returns False
    
    2209 2212
     -- for `b`, then `b` is never considered ok-for-spec.
    
    2213
    +--
    
    2214
    +-- This is the whole reason for the fun_ok arg to expr_ok.
    
    2210 2215
     exprOkForSpecEval :: (Id -> Bool) -> CoreExpr -> Bool
    
    2211 2216
     exprOkForSpecEval fun_ok = expr_ok fun_ok primOpOkForSpeculation
    
    2212 2217
     
    
    ... ... @@ -2240,10 +2245,9 @@ expr_ok fun_ok primop_ok (Case scrut bndr _ alts)
    2240 2245
       && altsAreExhaustive alts
    
    2241 2246
     
    
    2242 2247
     expr_ok fun_ok primop_ok other_expr
    
    2243
    -  | (expr, args) <- collectArgs other_expr
    
    2248
    +  | (expr, val_args) <- collectValArgs other_expr
    
    2244 2249
       = case stripTicksTopE (not . tickishCounts) expr of
    
    2245
    -        Var f ->
    
    2246
    -           app_ok fun_ok primop_ok f args
    
    2250
    +        Var f -> app_ok fun_ok primop_ok f val_args
    
    2247 2251
     
    
    2248 2252
             -- 'LitRubbish' is the only literal that can occur in the head of an
    
    2249 2253
             -- application and will not be matched by the above case (Var /= Lit).
    
    ... ... @@ -2258,9 +2262,10 @@ expr_ok fun_ok primop_ok other_expr
    2258 2262
     
    
    2259 2263
     -----------------------------
    
    2260 2264
     app_ok :: (Id -> Bool) -> (PrimOp -> Bool) -> Id -> [CoreArg] -> Bool
    
    2261
    -app_ok fun_ok primop_ok fun args
    
    2265
    +app_ok fun_ok primop_ok fun val_args
    
    2262 2266
       | not (fun_ok fun)
    
    2263
    -  = False -- This code path is only taken for Note [Speculative evaluation]
    
    2267
    +  = False -- This code path is only taken for exprOkForSpecEval
    
    2268
    +          -- See Note [Speculative evaluation]
    
    2264 2269
     
    
    2265 2270
       | idArity fun > n_val_args
    
    2266 2271
       -- Partial application: just check passing the arguments is OK
    
    ... ... @@ -2281,17 +2286,18 @@ app_ok fun_ok primop_ok fun args
    2281 2286
     
    
    2282 2287
           ClassOpId _ is_terminating_result
    
    2283 2288
             | is_terminating_result -- See Note [exprOkForSpeculation and type classes]
    
    2284
    -        -> assertPpr (n_val_args == 1) (ppr fun $$ ppr args) $
    
    2289
    +        -> assertPpr (n_val_args == 1) (ppr fun $$ ppr val_args) $
    
    2285 2290
                True
    
    2286 2291
                -- assert: terminating result type => can't be applied;
    
    2287 2292
                -- c.f the _other case below
    
    2288 2293
     
    
    2289 2294
           PrimOpId op _
    
    2290 2295
             | primOpIsDiv op
    
    2291
    -        , Lit divisor <- last args
    
    2296
    +        , Lit divisor <- last val_args
    
    2292 2297
                 -- there can be 2 args (most div primops) or 3 args
    
    2293 2298
                 -- (WordQuotRem2Op), hence the use of last/init
    
    2294
    -        -> not (isZeroLit divisor) && all (expr_ok fun_ok primop_ok) (init args)
    
    2299
    +        -> not (isZeroLit divisor) &&
    
    2300
    +           all ok_for_spec (init val_args)
    
    2295 2301
                   -- Special case for dividing operations that fail
    
    2296 2302
                   -- In general they are NOT ok-for-speculation
    
    2297 2303
                   -- (which primop_ok will catch), but they ARE OK
    
    ... ... @@ -2300,12 +2306,14 @@ app_ok fun_ok primop_ok fun args
    2300 2306
                   -- can get rid of a thunk in an inner loop
    
    2301 2307
     
    
    2302 2308
             | otherwise -> primop_ok op && args_ok
    
    2309
    +              -- Assumes that the primop does not evaluate its
    
    2310
    +              -- definitely-lifted arguments
    
    2303 2311
     
    
    2304 2312
           _other  -- Unlifted and terminating types;
    
    2305 2313
                   -- Also c.f. the Var case of exprIsHNF
    
    2306 2314
              |  isTerminatingType fun_ty  -- See Note [exprOkForSpeculation and type classes]
    
    2307 2315
              || definitelyUnliftedType fun_ty
    
    2308
    -         -> assertPpr (n_val_args == 0) (ppr fun $$ ppr args)
    
    2316
    +         -> assertPpr (n_val_args == 0) (ppr fun $$ ppr val_args)
    
    2309 2317
                 True  -- Both terminating types (e.g. Eq a), and unlifted types (e.g. Int#)
    
    2310 2318
                       -- are non-functions and so will have no value args.  The assert is
    
    2311 2319
                       -- just to check this.
    
    ... ... @@ -2321,32 +2329,43 @@ app_ok fun_ok primop_ok fun args
    2321 2329
                  --     for evaluated-ness of the fun;
    
    2322 2330
                  --     see Note [exprOkForSpeculation and evaluated variables]
    
    2323 2331
       where
    
    2324
    -    fun_ty       = idType fun
    
    2325
    -    n_val_args   = valArgCount args
    
    2326
    -    (arg_tys, _) = splitPiTys fun_ty
    
    2332
    +    ok_for_spec = expr_ok fun_ok primop_ok   -- Used for recursive calls
    
    2333
    +
    
    2334
    +    fun_ty      = idType fun
    
    2335
    +    n_val_args  = length val_args
    
    2336
    +    val_arg_tys = splitUninstantiatedValArgTys fun_ty
    
    2337
    +                  -- val_arg_tys are /uninstantiated/; see (EOKS1)
    
    2327 2338
     
    
    2328 2339
         -- Even if a function call itself is OK, any unlifted
    
    2329 2340
         -- args are still evaluated eagerly and must be checked
    
    2330
    -    args_ok = all2Prefix arg_ok arg_tys args
    
    2331
    -    arg_ok :: PiTyVarBinder -> CoreExpr -> Bool
    
    2332
    -    arg_ok (Named _) _ = True   -- A type argument
    
    2333
    -    arg_ok (Anon ty _) arg      -- A term argument
    
    2334
    -       | definitelyLiftedType (scaledThing ty)
    
    2335
    -       = True -- lifted args are not evaluated eagerly
    
    2336
    -       | otherwise
    
    2337
    -       = expr_ok fun_ok primop_ok arg
    
    2341
    +    --   arg_ok bndr arg = field_ok bndr NotMarkedStrict arg
    
    2342
    +    -- See Note [exprOkForSpeculation] (a,b)
    
    2343
    +    args_ok = all2Prefix arg_ok val_arg_tys val_args
    
    2344
    +    arg_ok :: Type -> CoreExpr -> Bool
    
    2345
    +    arg_ok arg_ty arg = ok_for_spec arg || definitely_lifted arg_ty arg
    
    2338 2346
     
    
    2339 2347
         -- Used for strict DataCon worker arguments
    
    2340 2348
         -- See (SFC1) of Note [Strict fields in Core]
    
    2341
    -    fields_ok str_marks = all3Prefix field_ok arg_tys str_marks args
    
    2342
    -    field_ok :: PiTyVarBinder -> StrictnessMark -> CoreExpr -> Bool
    
    2343
    -    field_ok (Named _)   _   _ = True
    
    2344
    -    field_ok (Anon ty _) str arg
    
    2345
    -       | NotMarkedStrict <- str                 -- iff it's a lazy field
    
    2346
    -       , definitelyLiftedType (scaledThing ty)  -- and its type is lifted
    
    2347
    -       = True                                   -- then the worker app does not eval
    
    2348
    -       | otherwise
    
    2349
    -       = expr_ok fun_ok primop_ok arg
    
    2349
    +    -- See Note [exprOkForSpeculation] (a,b)
    
    2350
    +    fields_ok str_marks = all3Prefix field_ok val_arg_tys str_marks val_args
    
    2351
    +    field_ok :: Type -> StrictnessMark -> CoreExpr -> Bool
    
    2352
    +    field_ok arg_ty str arg
    
    2353
    +       = ok_for_spec arg || (definitely_lifted arg_ty arg && str==NotMarkedStrict)
    
    2354
    +       -- The (ok_for_spec arg) test works for /both/ for unlifted types, /and/
    
    2355
    +       -- for lifted but strict fields. E.g. K (I# 3) is ok-for-spec,
    
    2356
    +       -- even if K is strict
    
    2357
    +
    
    2358
    +    -- We want to see if the argument type is definitely lifted.
    
    2359
    +    -- But consider
    
    2360
    +    --     (#,#) @rep1 @rep2 @ty1 @ty2 arg1 arg2
    
    2361
    +    -- We don't /instantiate/ the type of (#,#) (although we could) so we don't
    
    2362
    +    -- know if the argument type is lifted or not.  So we look at the type of
    
    2363
    +    -- the /actual/ argument (it's usually a variable) instead.
    
    2364
    +    definitely_lifted uninstantiated_arg_ty arg
    
    2365
    +       = case typeLevity_maybe uninstantiated_arg_ty of
    
    2366
    +           Just Lifted   -> True
    
    2367
    +           Just Unlifted -> False
    
    2368
    +           Nothing       -> definitelyLiftedType (exprType arg)
    
    2350 2369
     
    
    2351 2370
     -----------------------------
    
    2352 2371
     altsAreExhaustive :: [Alt b] -> Bool
    
    ... ... @@ -2390,8 +2409,42 @@ cantEtaReduceFun fun
    2390 2409
            -- Don't undersaturate StrictWorkerIds.
    
    2391 2410
            -- See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
    
    2392 2411
     
    
    2393
    -{- Note [exprOkForSpeculation and type classes]
    
    2394
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2412
    +{- Note [exprOkForSpeculation]
    
    2413
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2414
    +Suppose we have
    
    2415
    +  data T a = K !a Int# a
    
    2416
    +
    
    2417
    +Is the call (K e1 e2 e3) ok-for-speculation?  Look at the arguments e1..e3,
    
    2418
    +and their types.  The call is ok-for-speculation if each argument satisfies
    
    2419
    +`field_ok`, namely:
    
    2420
    +  (a) (exprOkForSpeculation arg) holds, OR
    
    2421
    +  (b) Arg type is definitely lifted and it is not marked strict
    
    2422
    +
    
    2423
    +For (a) we conservatively assume we are going to evaluate the argument.
    
    2424
    +If it is ok-for-spec, then fine.
    
    2425
    +
    
    2426
    +But if the argument is of a lifted type, and not marked strict (notably by
    
    2427
    +a data constructor) then (b) holds.  For example
    
    2428
    +    Just (reverse xs)
    
    2429
    +is ok-for-spec.  See (EOKS1) for the argument liftedness test.
    
    2430
    +
    
    2431
    +If we have a plain variable `x`, is that ok-for-spec? Not if it is lifted:
    
    2432
    +it might be a thunk!  Hence the (definitelyUnliftedType fun_ty) test.
    
    2433
    +Remember, a naked variable `x` will land in `app_ok x []` with no arguments.
    
    2434
    +See Note [exprOkForSpeculation and evaluated variables].
    
    2435
    +
    
    2436
    +(EOKS1) To get the lifted-ness or otherwise of the arguments we just look at the
    
    2437
    +  /uninstantiated/ type of the data constructor or primop.  We'd get better information
    
    2438
    +  if we instantiated, but it's also more expensive.  Example:
    
    2439
    +    (#,#) :: forall r1 r2 (a::TYPE r1) (b::TYPE r2). a -> b -> (# a, b #)
    
    2440
    +  If we have a call
    
    2441
    +       (#,#) @LiftedRep @IntRep @Int @Int# 3 4#
    
    2442
    +  then we could see accurate liftedness by instantiation, but we don't try.
    
    2443
    +  Instead we get the actual type from (exprType arg).  That could be expensive,
    
    2444
    +  but it really only happens for unboxed tuples.
    
    2445
    +
    
    2446
    +Note [exprOkForSpeculation and type classes]
    
    2447
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2395 2448
     Consider (#22745, #15205)
    
    2396 2449
     
    
    2397 2450
       \(d :: C a b). case eq_sel (sc_sel d) of
    
    ... ... @@ -2674,8 +2727,7 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
    2674 2727
             -- PAP: Check unlifted val_args
    
    2675 2728
             args_hnf             = all2Prefix check_arg   val_arg_tys           val_args
    
    2676 2729
     
    
    2677
    -        fun_ty = idType id
    
    2678
    -        val_arg_tys = mapMaybe anonPiTyBinderType_maybe (collectPiTyBinders fun_ty)
    
    2730
    +        val_arg_tys = splitUninstantiatedValArgTys (idType id)
    
    2679 2731
               -- val_arg_tys = map exprType val_args, but much less costly.
    
    2680 2732
               -- The obvious definition regresses T16577 by 30% so we don't do it.
    
    2681 2733
     
    
    ... ... @@ -2700,7 +2752,6 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
    2700 2752
               | otherwise
    
    2701 2753
               = Nothing
    
    2702 2754
     
    
    2703
    -
    
    2704 2755
     {-
    
    2705 2756
     Note [exprIsHNF Tick]
    
    2706 2757
     ~~~~~~~~~~~~~~~~~~~~~
    

  • compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
    ... ... @@ -80,7 +80,7 @@ initGentleSimplMode :: DynFlags -> SimplMode
    80 80
     initGentleSimplMode dflags = (initSimplMode dflags InitialPhase "Gentle")
    
    81 81
       { -- Don't do case-of-case transformations.
    
    82 82
         -- This makes full laziness work better
    
    83
    -    -- See Note [Case-of-case and full laziness]
    
    83
    +    -- See Note [sm_case_case: switching off case continuations]
    
    84 84
         sm_case_case = False
    
    85 85
       }
    
    86 86
     
    
    ... ... @@ -90,37 +90,3 @@ floatEnable dflags =
    90 90
         (True, True) -> FloatEnabled
    
    91 91
         (True, False)-> FloatNestedOnly
    
    92 92
         (False, _)   -> FloatDisabled
    93
    -
    
    94
    -
    
    95
    -{- Note [Case-of-case and full laziness]
    
    96
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    97
    -Case-of-case can hide opportunities for let-floating (full laziness).
    
    98
    -For example
    
    99
    -   rec { f = \y. case (expensive x) of (a,b) -> blah }
    
    100
    -We might hope to float the (expensive x) out of the \y-loop.
    
    101
    -But if we inline `expensive` we might get
    
    102
    -   \y. case (case x of I# x' -> body) of (a,b) -> blah
    
    103
    -Now if we do case-of-case we get
    
    104
    -   \y. case x if I# x2 ->
    
    105
    -       case body of (a,b) -> blah
    
    106
    -
    
    107
    -Sadly, at this point `body` mentions `x2`, so we can't float it out of the
    
    108
    -\y-loop.
    
    109
    -
    
    110
    -Solution: don't do case-of-case in the "gentle" simplification phase that
    
    111
    -precedes the first float-out transformation.  Implementation:
    
    112
    -
    
    113
    -  * `sm_case_case` field in SimplMode
    
    114
    -
    
    115
    -  * Consult `sm_case_case` (via `seCaseCase`) before doing case-of-case
    
    116
    -    in GHC.Core.Opt.Simplify.Iteration.rebuildCall.
    
    117
    -
    
    118
    -Wrinkles
    
    119
    -
    
    120
    -* This applies equally to the case-of-runRW# transformation:
    
    121
    -    case (runRW# (\s. body)) of (a,b) -> blah
    
    122
    -    --->
    
    123
    -    runRW# (\s. case body of (a,b) -> blah)
    
    124
    -  Again, don't do this when `sm_case_case` is off.  See #25055 for
    
    125
    -  a motivating example.
    
    126
    --}

  • testsuite/tests/dmdanal/should_compile/T20510.stderr
    1 1
     
    
    2 2
     ==================== Exitification transformation ====================
    
    3 3
     Result size of Exitification transformation
    
    4
    -  = {terms: 50, types: 22, coercions: 0, joins: 2/2}
    
    4
    +  = {terms: 33, types: 15, coercions: 0, joins: 2/2}
    
    5 5
     
    
    6 6
     -- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
    
    7 7
     lvl :: Int
    
    ... ... @@ -11,7 +11,7 @@ lvl :: Int
    11 11
              Guidance=IF_ARGS [] 10 10}]
    
    12 12
     lvl = GHC.Internal.Types.I# 0#
    
    13 13
     
    
    14
    --- RHS size: {terms: 32, types: 14, coercions: 0, joins: 2/2}
    
    14
    +-- RHS size: {terms: 29, types: 12, coercions: 0, joins: 2/2}
    
    15 15
     small :: Int -> Int
    
    16 16
     [LclIdX,
    
    17 17
      Arity=1,
    
    ... ... @@ -22,7 +22,7 @@ small :: Int -> Int
    22 22
              Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=False)
    
    23 23
              Tmpl= \ (x [Dmd=S!P(SL)] :: Int) ->
    
    24 24
                      joinrec {
    
    25
    -                   go [InlPrag=[2], Occ=T[2], Dmd=LC(S,C(1,!P(L)))]
    
    25
    +                   go [InlPrag=[2], Occ=Many(T[2]), Dmd=LC(S,C(1,!P(L)))]
    
    26 26
                          :: Int -> Int -> Int
    
    27 27
                        [LclId[JoinId(2)(Nothing)],
    
    28 28
                         Arity=2,
    
    ... ... @@ -54,11 +54,11 @@ small :: Int -> Int
    54 54
                                 Guidance=IF_ARGS [0 51] 63 10}]
    
    55 55
                        $wgo (ww [Occ=Once2] :: GHC.Internal.Prim.Int#)
    
    56 56
                             (ww [Occ=Once1!, Dmd=SL] :: GHC.Internal.Prim.Int#)
    
    57
    -                     = case ww of ds {
    
    57
    +                     = case ww of wild {
    
    58 58
                              __DEFAULT ->
    
    59 59
                                jump go
    
    60
    -                             (GHC.Internal.Types.I# (GHC.Internal.Prim.+# ww ds))
    
    61
    -                             (GHC.Internal.Types.I# (GHC.Internal.Prim.-# ds 1#));
    
    60
    +                             (GHC.Internal.Types.I# (GHC.Internal.Prim.+# ww wild))
    
    61
    +                             (GHC.Internal.Types.I# (GHC.Internal.Prim.-# wild 1#));
    
    62 62
                              0# ->
    
    63 63
                                case x of { GHC.Internal.Types.I# y [Occ=Once1] ->
    
    64 64
                                GHC.Internal.Types.I# (GHC.Internal.Prim.*# ww y)
    
    ... ... @@ -67,13 +67,12 @@ small :: Int -> Int
    67 67
                      jump go lvl x}]
    
    68 68
     small
    
    69 69
       = \ (x [Dmd=S!P(SL)] :: Int) ->
    
    70
    +      case x of { GHC.Internal.Types.I# ww [Dmd=SL] ->
    
    70 71
           join {
    
    71 72
             exit :: GHC.Internal.Prim.Int# -> Int
    
    72 73
             [LclId[JoinId(1)(Nothing)]]
    
    73 74
             exit (ww :: GHC.Internal.Prim.Int#)
    
    74
    -          = case x of { GHC.Internal.Types.I# y ->
    
    75
    -            GHC.Internal.Types.I# (GHC.Internal.Prim.*# ww y)
    
    76
    -            } } in
    
    75
    +          = GHC.Internal.Types.I# (GHC.Internal.Prim.*# ww ww) } in
    
    77 76
           joinrec {
    
    78 77
             $wgo [InlPrag=[2], Occ=LoopBreaker]
    
    79 78
               :: GHC.Internal.Prim.Int# -> GHC.Internal.Prim.Int# -> Int
    
    ... ... @@ -82,56 +81,17 @@ small
    82 81
              Str=<L><SL>,
    
    83 82
              Unf=Unf{Src=<vanilla>, TopLvl=False,
    
    84 83
                      Value=True, ConLike=True, WorkFree=True, Expandable=True,
    
    85
    -                 Guidance=IF_ARGS [0 32] 43 10}]
    
    84
    +                 Guidance=IF_ARGS [0 32] 33 10}]
    
    86 85
             $wgo (ww :: GHC.Internal.Prim.Int#)
    
    87 86
                  (ww [Dmd=SL] :: GHC.Internal.Prim.Int#)
    
    88
    -          = case ww of ds {
    
    87
    +          = case ww of wild {
    
    89 88
                   __DEFAULT ->
    
    90 89
                     jump $wgo
    
    91
    -                  (GHC.Internal.Prim.+# ww ds) (GHC.Internal.Prim.-# ds 1#);
    
    90
    +                  (GHC.Internal.Prim.+# ww wild) (GHC.Internal.Prim.-# wild 1#);
    
    92 91
                   0# -> jump exit ww
    
    93 92
                 }; } in
    
    94
    -      case x of { GHC.Internal.Types.I# ww [Dmd=SL] -> jump $wgo 0# ww }
    
    95
    -
    
    96
    --- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
    
    97
    -$trModule :: GHC.Internal.Prim.Addr#
    
    98
    -[LclId,
    
    99
    - Unf=Unf{Src=<vanilla>, TopLvl=True,
    
    100
    -         Value=True, ConLike=True, WorkFree=True, Expandable=True,
    
    101
    -         Guidance=IF_ARGS [] 20 0}]
    
    102
    -$trModule = "main"#
    
    103
    -
    
    104
    --- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
    
    105
    -$trModule :: GHC.Internal.Types.TrName
    
    106
    -[LclId,
    
    107
    - Unf=Unf{Src=<vanilla>, TopLvl=True,
    
    108
    -         Value=True, ConLike=True, WorkFree=True, Expandable=True,
    
    109
    -         Guidance=IF_ARGS [] 10 10}]
    
    110
    -$trModule = GHC.Internal.Types.TrNameS $trModule
    
    111
    -
    
    112
    --- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
    
    113
    -$trModule :: GHC.Internal.Prim.Addr#
    
    114
    -[LclId,
    
    115
    - Unf=Unf{Src=<vanilla>, TopLvl=True,
    
    116
    -         Value=True, ConLike=True, WorkFree=True, Expandable=True,
    
    117
    -         Guidance=IF_ARGS [] 30 0}]
    
    118
    -$trModule = "T20510"#
    
    119
    -
    
    120
    --- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
    
    121
    -$trModule :: GHC.Internal.Types.TrName
    
    122
    -[LclId,
    
    123
    - Unf=Unf{Src=<vanilla>, TopLvl=True,
    
    124
    -         Value=True, ConLike=True, WorkFree=True, Expandable=True,
    
    125
    -         Guidance=IF_ARGS [] 10 10}]
    
    126
    -$trModule = GHC.Internal.Types.TrNameS $trModule
    
    127
    -
    
    128
    --- RHS size: {terms: 3, types: 0, coercions: 0, joins: 0/0}
    
    129
    -T20510.$trModule :: GHC.Internal.Types.Module
    
    130
    -[LclIdX,
    
    131
    - Unf=Unf{Src=<vanilla>, TopLvl=True,
    
    132
    -         Value=True, ConLike=True, WorkFree=True, Expandable=True,
    
    133
    -         Guidance=IF_ARGS [] 10 10}]
    
    134
    -T20510.$trModule = GHC.Internal.Types.Module $trModule $trModule
    
    93
    +      jump $wgo 0# ww
    
    94
    +      }
    
    135 95
     
    
    136 96
     
    
    137 97
     

  • testsuite/tests/show-bytecode/show-bytecode-hpc.stdout
    ... ... @@ -59,135 +59,133 @@ objects:
    59 59
         arity: 0
    
    60 60
         literals: label ‘_hpc_tickboxes_Example_hpc’
    
    61 61
         used items: named item ‘primes’
    
    62
    -  object ‘primes2_@name_suffix@’:
    
    62
    +  object ‘primes’:
    
    63 63
         arity: 0
    
    64
    -    literals: label ‘_hpc_tickboxes_Example_hpc’
    
    65
    -    used items:
    
    66
    -      object ‘primes2_sat_@name_suffix@’:
    
    67
    -        arity: 0
    
    68
    -        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    69
    -        used items:
    
    70
    -          object ‘primes2_sat_@name_suffix@’:
    
    71
    -            arity: 0
    
    72
    -            literals:
    
    73
    -              label ‘_hpc_tickboxes_Example_hpc’
    
    74
    -              word 3
    
    75
    -              info table of ‘IS’
    
    76
    -            used items:
    
    77
    -              named item ‘$fNumNatural’
    
    78
    -              named item ‘fromInteger’
    
    79
    -          named item ‘$fEnumNatural’
    
    80
    -          named item ‘enumFrom’
    
    81
    -      object ‘primes2_sat_@name_suffix@’:
    
    82
    -        arity: 0
    
    83
    -        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    84
    -        used items: named item ‘isPrime_@name_suffix@’
    
    85
    -      named item ‘filter’
    
    86
    -  object ‘isPrime_@name_suffix@’:
    
    87
    -    arity: 1
    
    88 64
         literals:
    
    89 65
           label ‘_hpc_tickboxes_Example_hpc’
    
    66
    +      info table of ‘(:)’
    
    90 67
         used items:
    
    91
    -      object ‘isPrime_sat_@name_suffix@’:
    
    68
    +      object ‘isPrime_@name_suffix@’:
    
    92 69
             arity: 1
    
    93
    -        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    70
    +        literals:
    
    71
    +          label ‘_hpc_tickboxes_Example_hpc’
    
    94 72
             used items:
    
    95
    -          object ‘isPrime_sat_@name_suffix@’:
    
    73
    +          object ‘isPrime_primes_sat_@name_suffix@’:
    
    96 74
                 arity: 1
    
    97 75
                 literals: label ‘_hpc_tickboxes_Example_hpc’
    
    98 76
                 used items:
    
    99
    -              object ‘isPrime_sat_@name_suffix@’:
    
    100
    -                arity: 0
    
    101
    -                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    102
    -                used items: named item ‘primes’
    
    103
    -              object ‘isPrime_sat_@name_suffix@’:
    
    77
    +              object ‘isPrime_primes_sat_@name_suffix@’:
    
    104 78
                     arity: 1
    
    105 79
                     literals: label ‘_hpc_tickboxes_Example_hpc’
    
    106 80
                     used items:
    
    107
    -                  object ‘isPrime_sat_@name_suffix@’:
    
    81
    +                  object ‘isPrime_primes_sat_@name_suffix@’:
    
    108 82
                         arity: 0
    
    109 83
                         literals: label ‘_hpc_tickboxes_Example_hpc’
    
    110
    -                    used items:
    
    111
    -                      object ‘v_@name_suffix@’:
    
    112
    -                        arity: 0
    
    113
    -                        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    114
    -                        used items:
    
    115
    -                          named item ‘$fIntegralInteger’
    
    116
    -                          named item ‘$fNumNatural’
    
    117
    -                          named item ‘(^)’
    
    118
    -                      object ‘v1_@name_suffix@’:
    
    119
    -                        arity: 0
    
    120
    -                        literals:
    
    121
    -                          label ‘_hpc_tickboxes_Example_hpc’
    
    122
    -                          word 2
    
    123
    -                          info table of ‘IS’
    
    124
    -                        used items: <none>
    
    125
    -                      object ‘pap_@name_suffix@’:
    
    126
    -                        arity: 3
    
    127
    -                        literals: <none>
    
    128
    -                        used items: <none>
    
    129
    -                  object ‘isPrime_sat_@name_suffix@’:
    
    84
    +                    used items: named item ‘primes’
    
    85
    +                  object ‘isPrime_primes_sat_@name_suffix@’:
    
    130 86
                         arity: 1
    
    131 87
                         literals: label ‘_hpc_tickboxes_Example_hpc’
    
    132 88
                         used items:
    
    133
    -                      object ‘v_@name_suffix@’:
    
    89
    +                      object ‘isPrime_primes_sat_@name_suffix@’:
    
    134 90
                             arity: 0
    
    135 91
                             literals: label ‘_hpc_tickboxes_Example_hpc’
    
    136 92
                             used items:
    
    137
    -                          named item ‘$fOrdNatural’
    
    138
    -                          named item ‘(<=)’
    
    139
    -                      object ‘v1_@name_suffix@’:
    
    93
    +                          object ‘v_@name_suffix@’:
    
    94
    +                            arity: 0
    
    95
    +                            literals: label ‘_hpc_tickboxes_Example_hpc’
    
    96
    +                            used items:
    
    97
    +                              named item ‘$fIntegralInteger’
    
    98
    +                              named item ‘$fNumNatural’
    
    99
    +                              named item ‘(^)’
    
    100
    +                          object ‘v1_@name_suffix@’:
    
    101
    +                            arity: 0
    
    102
    +                            literals:
    
    103
    +                              label ‘_hpc_tickboxes_Example_hpc’
    
    104
    +                              word 2
    
    105
    +                              info table of ‘IS’
    
    106
    +                            used items: <none>
    
    107
    +                          object ‘pap_@name_suffix@’:
    
    108
    +                            arity: 3
    
    109
    +                            literals: <none>
    
    110
    +                            used items: <none>
    
    111
    +                      object ‘isPrime_primes_sat_@name_suffix@’:
    
    140 112
                             arity: 1
    
    141 113
                             literals: label ‘_hpc_tickboxes_Example_hpc’
    
    142
    -                        used items: <none>
    
    114
    +                        used items:
    
    115
    +                          object ‘v_@name_suffix@’:
    
    116
    +                            arity: 0
    
    117
    +                            literals: label ‘_hpc_tickboxes_Example_hpc’
    
    118
    +                            used items:
    
    119
    +                              named item ‘$fOrdNatural’
    
    120
    +                              named item ‘(<=)’
    
    121
    +                          object ‘v1_@name_suffix@’:
    
    122
    +                            arity: 1
    
    123
    +                            literals: label ‘_hpc_tickboxes_Example_hpc’
    
    124
    +                            used items: <none>
    
    125
    +                          object ‘pap_@name_suffix@’:
    
    126
    +                            arity: 3
    
    127
    +                            literals: <none>
    
    128
    +                            used items: <none>
    
    129
    +                      named item ‘(.)’
    
    130
    +                  named item ‘takeWhile’
    
    131
    +              object ‘isPrime_primes_sat_@name_suffix@’:
    
    132
    +                arity: 1
    
    133
    +                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    134
    +                used items:
    
    135
    +                  object ‘v_@name_suffix@’:
    
    136
    +                    arity: 0
    
    137
    +                    literals: label ‘_hpc_tickboxes_Example_hpc’
    
    138
    +                    used items:
    
    143 139
                           object ‘pap_@name_suffix@’:
    
    144
    -                        arity: 3
    
    140
    +                        arity: 2
    
    145 141
                             literals: <none>
    
    146
    -                        used items: <none>
    
    147
    -                  named item ‘(.)’
    
    148
    -              named item ‘takeWhile’
    
    149
    -          object ‘isPrime_sat_@name_suffix@’:
    
    150
    -            arity: 1
    
    142
    +                        used items:
    
    143
    +                          named item ‘$fIntegralNatural’
    
    144
    +                          named item ‘divides’
    
    145
    +                  object ‘v1_@name_suffix@’:
    
    146
    +                    arity: 1
    
    147
    +                    literals: label ‘_hpc_tickboxes_Example_hpc’
    
    148
    +                    used items: <none>
    
    149
    +                  object ‘pap_@name_suffix@’:
    
    150
    +                    arity: 3
    
    151
    +                    literals: <none>
    
    152
    +                    used items: <none>
    
    153
    +              named item ‘$fFoldableList’
    
    154
    +              named item ‘any’
    
    155
    +          named item ‘not’
    
    156
    +      object ‘primes_sat_@name_suffix@’:
    
    157
    +        arity: 1
    
    158
    +        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    159
    +        used items:
    
    160
    +          object ‘primes_sat_@name_suffix@’:
    
    161
    +            arity: 0
    
    151 162
                 literals: label ‘_hpc_tickboxes_Example_hpc’
    
    152 163
                 used items:
    
    153
    -              object ‘v_@name_suffix@’:
    
    164
    +              object ‘primes_sat_@name_suffix@’:
    
    154 165
                     arity: 0
    
    155
    -                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    166
    +                literals:
    
    167
    +                  label ‘_hpc_tickboxes_Example_hpc’
    
    168
    +                  word 3
    
    169
    +                  info table of ‘IS’
    
    156 170
                     used items:
    
    157
    -                  object ‘pap_@name_suffix@’:
    
    158
    -                    arity: 2
    
    159
    -                    literals: <none>
    
    160
    -                    used items:
    
    161
    -                      named item ‘$fIntegralNatural’
    
    162
    -                      named item ‘divides’
    
    163
    -              object ‘v1_@name_suffix@’:
    
    164
    -                arity: 1
    
    165
    -                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    166
    -                used items: <none>
    
    167
    -              object ‘pap_@name_suffix@’:
    
    168
    -                arity: 3
    
    169
    -                literals: <none>
    
    170
    -                used items: <none>
    
    171
    -          named item ‘$fFoldableList’
    
    172
    -          named item ‘any’
    
    173
    -      named item ‘not’
    
    174
    -  object ‘primes’:
    
    175
    -    arity: 0
    
    176
    -    literals:
    
    177
    -      label ‘_hpc_tickboxes_Example_hpc’
    
    178
    -      info table of ‘(:)’
    
    179
    -    used items:
    
    180
    -      named item ‘primes2_@name_suffix@’
    
    181
    -      named item ‘primes1_@name_suffix@’
    
    182
    -  object ‘primes1_@name_suffix@’:
    
    183
    -    arity: 0
    
    184
    -    literals:
    
    185
    -      label ‘_hpc_tickboxes_Example_hpc’
    
    186
    -      word 2
    
    187
    -      info table of ‘IS’
    
    188
    -    used items:
    
    189
    -      named item ‘$fNumNatural’
    
    190
    -      named item ‘fromInteger’
    
    171
    +                  named item ‘$fNumNatural’
    
    172
    +                  named item ‘fromInteger’
    
    173
    +              named item ‘$fEnumNatural’
    
    174
    +              named item ‘enumFrom’
    
    175
    +          object ‘primes_sat_@name_suffix@’:
    
    176
    +            arity: 1
    
    177
    +            literals: label ‘_hpc_tickboxes_Example_hpc’
    
    178
    +            used items: <none>
    
    179
    +          named item ‘filter’
    
    180
    +      object ‘primes_sat_@name_suffix@’:
    
    181
    +        arity: 0
    
    182
    +        literals:
    
    183
    +          label ‘_hpc_tickboxes_Example_hpc’
    
    184
    +          word 2
    
    185
    +          info table of ‘IS’
    
    186
    +        used items:
    
    187
    +          named item ‘$fNumNatural’
    
    188
    +          named item ‘fromInteger’
    
    191 189
       object ‘fibonaccisPtr’:
    
    192 190
         arity: 0
    
    193 191
         literals:
    
    ... ... @@ -245,63 +243,59 @@ objects:
    245 243
         arity: 0
    
    246 244
         literals: label ‘_hpc_tickboxes_Example_hpc’
    
    247 245
         used items: named item ‘fibonaccis’
    
    248
    -  object ‘positiveFibonaccis1_@name_suffix@’:
    
    246
    +  object ‘fibonaccis’:
    
    249 247
         arity: 0
    
    250 248
         literals:
    
    251 249
           label ‘_hpc_tickboxes_Example_hpc’
    
    252 250
           info table of ‘(:)’
    
    253 251
         used items:
    
    254
    -      named item ‘positiveFibonaccis2_@name_suffix@’
    
    255
    -      named item ‘positiveFibonaccis_@name_suffix@’
    
    256
    -  object ‘positiveFibonaccis2_@name_suffix@’:
    
    257
    -    arity: 0
    
    258
    -    literals: label ‘_hpc_tickboxes_Example_hpc’
    
    259
    -    used items:
    
    260
    -      object ‘positiveFibonaccis2_sat_@name_suffix@’:
    
    261
    -        arity: 0
    
    262
    -        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    263
    -        used items: named item ‘positiveFibonaccis1_@name_suffix@’
    
    264
    -      object ‘positiveFibonaccis2_sat_@name_suffix@’:
    
    265
    -        arity: 0
    
    252
    +      object ‘positiveFibonaccis_@name_suffix@’:
    
    253
    +        arity: 1
    
    254
    +        literals:
    
    255
    +          label ‘_hpc_tickboxes_Example_hpc’
    
    256
    +          info table of ‘(:)’
    
    257
    +        used items:
    
    258
    +          object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
    
    259
    +            arity: 1
    
    260
    +            literals: label ‘_hpc_tickboxes_Example_hpc’
    
    261
    +            used items:
    
    262
    +              object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
    
    263
    +                arity: 1
    
    264
    +                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    265
    +                used items: <none>
    
    266
    +              object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
    
    267
    +                arity: 0
    
    268
    +                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    269
    +                used items: named item ‘fibonaccis’
    
    270
    +              object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
    
    271
    +                arity: 0
    
    272
    +                literals: label ‘_hpc_tickboxes_Example_hpc’
    
    273
    +                used items:
    
    274
    +                  named item ‘$fNumNatural’
    
    275
    +                  named item ‘(+)’
    
    276
    +              named item ‘zipWith’
    
    277
    +          object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
    
    278
    +            arity: 0
    
    279
    +            literals:
    
    280
    +              label ‘_hpc_tickboxes_Example_hpc’
    
    281
    +              word 1
    
    282
    +              info table of ‘IS’
    
    283
    +            used items:
    
    284
    +              named item ‘$fNumNatural’
    
    285
    +              named item ‘fromInteger’
    
    286
    +      object ‘fibonaccis_sat_@name_suffix@’:
    
    287
    +        arity: 1
    
    266 288
             literals: label ‘_hpc_tickboxes_Example_hpc’
    
    267
    -        used items: named item ‘fibonaccis’
    
    268
    -      object ‘positiveFibonaccis2_sat_@name_suffix@’:
    
    289
    +        used items: <none>
    
    290
    +      object ‘fibonaccis_sat_@name_suffix@’:
    
    269 291
             arity: 0
    
    270
    -        literals: label ‘_hpc_tickboxes_Example_hpc’
    
    292
    +        literals:
    
    293
    +          label ‘_hpc_tickboxes_Example_hpc’
    
    294
    +          word 0
    
    295
    +          info table of ‘IS’
    
    271 296
             used items:
    
    272 297
               named item ‘$fNumNatural’
    
    273
    -          named item ‘(+)’
    
    274
    -      named item ‘zipWith’
    
    275
    -  object ‘fibonaccis’:
    
    276
    -    arity: 0
    
    277
    -    literals:
    
    278
    -      label ‘_hpc_tickboxes_Example_hpc’
    
    279
    -      info table of ‘(:)’
    
    280
    -    used items:
    
    281
    -      named item ‘fibonaccis2_@name_suffix@’
    
    282
    -      named item ‘fibonaccis1_@name_suffix@’
    
    283
    -  object ‘fibonaccis2_@name_suffix@’:
    
    284
    -    arity: 0
    
    285
    -    literals: label ‘_hpc_tickboxes_Example_hpc’
    
    286
    -    used items: named item ‘positiveFibonaccis1_@name_suffix@’
    
    287
    -  object ‘positiveFibonaccis_@name_suffix@’:
    
    288
    -    arity: 0
    
    289
    -    literals:
    
    290
    -      label ‘_hpc_tickboxes_Example_hpc’
    
    291
    -      word 1
    
    292
    -      info table of ‘IS’
    
    293
    -    used items:
    
    294
    -      named item ‘$fNumNatural’
    
    295
    -      named item ‘fromInteger’
    
    296
    -  object ‘fibonaccis1_@name_suffix@’:
    
    297
    -    arity: 0
    
    298
    -    literals:
    
    299
    -      label ‘_hpc_tickboxes_Example_hpc’
    
    300
    -      word 0
    
    301
    -      info table of ‘IS’
    
    302
    -    used items:
    
    303
    -      named item ‘$fNumNatural’
    
    304
    -      named item ‘fromInteger’
    
    298
    +          named item ‘fromInteger’
    
    305 299
       object ‘$dTypeable2_@name_suffix@’:
    
    306 300
         arity: 0
    
    307 301
         literals: <none>
    

  • testsuite/tests/simplCore/should_compile/T26903.stderr
    1 1
     
    
    2 2
     ==================== Tidy Core ====================
    
    3 3
     Result size of Tidy Core
    
    4
    -  = {terms: 127, types: 130, coercions: 48, joins: 0/0}
    
    4
    +  = {terms: 127, types: 130, coercions: 24, joins: 0/0}
    
    5 5
     
    
    6 6
     $dmop
    
    7
    -  = (\ @a _ $dOrd xs ys ->
    
    8
    -       case $fOrdList_$ccompare $dOrd xs ys of {
    
    9
    -         __DEFAULT ->
    
    10
    -           reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [];
    
    11
    -         GT -> reverse1 (reverse1 (reverse1 (reverse xs) []) []) []
    
    12
    -       })
    
    13
    -    `cast` <Co:20> :: ...
    
    7
    +  = \ @a $dC $dOrd xs ys ->
    
    8
    +      case $fOrdList_$ccompare $dOrd xs ys of {
    
    9
    +        __DEFAULT ->
    
    10
    +          (reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [])
    
    11
    +          `cast` <Co:3>;
    
    12
    +        GT ->
    
    13
    +          (reverse1 (reverse1 (reverse1 (reverse xs) []) []) [])
    
    14
    +          `cast` <Co:3>
    
    15
    +      }
    
    14 16
     
    
    15 17
     $fCInt_$cop
    
    16
    -  = (\ xs ys ->
    
    17
    -       case $fOrdList_$s$ccompare xs ys of {
    
    18
    -         __DEFAULT ->
    
    19
    -           reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [];
    
    20
    -         GT -> reverse1 (reverse1 (reverse1 (reverse xs) []) []) []
    
    21
    -       })
    
    22
    -    `cast` <Co:11> :: ...
    
    18
    +  = \ xs ys ->
    
    19
    +      case $fOrdList_$s$ccompare xs ys of {
    
    20
    +        __DEFAULT ->
    
    21
    +          (reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [])
    
    22
    +          `cast` <Co:3>;
    
    23
    +        GT ->
    
    24
    +          (reverse1 (reverse1 (reverse1 (reverse xs) []) []) [])
    
    25
    +          `cast` <Co:3>
    
    26
    +      }
    
    23 27
     
    
    24 28
     $fCInt1
    
    25 29
       = \ xs ys ->
    
    26 30
           case $fOrdList_$s$ccompare xs ys of {
    
    27 31
             __DEFAULT ->
    
    28
    -          reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [];
    
    29
    -        GT -> reverse1 (reverse1 (reverse1 (reverse xs) []) []) []
    
    32
    +          (reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [])
    
    33
    +          `cast` <Co:3>;
    
    34
    +        GT ->
    
    35
    +          (reverse1 (reverse1 (reverse1 (reverse xs) []) []) [])
    
    36
    +          `cast` <Co:3>
    
    30 37
           }
    
    31 38
     
    
    32
    -$fCInt = C:C ($fCInt1 `cast` <Co:11> :: ...)
    
    39
    +$fCInt = C:C $fCInt1
    
    33 40
     
    
    34 41
     test4 = reverse1 [] []
    
    35 42
     
    
    ... ... @@ -44,8 +51,8 @@ test
    44 51
           case $fOrdList_$s$ccompare [] xs of {
    
    45 52
             __DEFAULT ->
    
    46 53
               (reverse1 (reverse1 (reverse1 (reverse1 (++ [] xs) []) []) []) [])
    
    47
    -          `cast` <Co:3> :: ...;
    
    48
    -        GT -> test1 `cast` <Co:3> :: ...
    
    54
    +          `cast` <Co:3>;
    
    55
    +        GT -> test1 `cast` <Co:3>
    
    49 56
           }
    
    50 57
     
    
    51 58
     
    

  • testsuite/tests/simplCore/should_compile/T27737a.hs
    1
    +{-# LANGUAGE NoMonoLocalBinds, MagicHash, UnboxedTuples #-}
    
    2
    +
    
    3
    +-- One of several regression tests arising from the work on #27737.
    
    4
    +--
    
    5
    +-- The Simplifier returns a single-alternative case as a case-float
    
    6
    +-- (FloatCase).  Here the local binding
    
    7
    +--     g = /\a. case addIntC# x y of (# r, _ #) -> ([], I# r)
    
    8
    +-- is lazy, non-recursive and has a type lambda but no value lambda, so
    
    9
    +-- simplLazyBind strips off the /\a and simplifies the body.  The case
    
    10
    +-- becomes a FloatCase; since addIntC# is ok-for-speculation, the float is
    
    11
    +-- FltOkSpec, which doFloatFromRhs allows out of a nested lazy binding.
    
    12
    +-- But then the floats must be abstracted over `a` (abstractFloats), which
    
    13
    +-- can only handle let-floats: at one stage the compiler panicked
    
    14
    +-- with "letFloatBinds".
    
    15
    +
    
    16
    +module T27737a where
    
    17
    +
    
    18
    +import GHC.Exts
    
    19
    +
    
    20
    +f :: Int -> Int -> ([Bool], [Char], Int)
    
    21
    +f (I# x) (I# y) = let g = case addIntC# x y of (# r, _ #) -> ([], I# r)
    
    22
    +                          -- g :: forall a. ([a], Int)
    
    23
    +                  in (fst g, fst g, snd g)

  • testsuite/tests/simplCore/should_compile/T27910.hs
    1
    +{-# LANGUAGE UnboxedTuples, MagicHash #-}
    
    2
    +module T27910 where
    
    3
    +import GHC.Exts
    
    4
    +
    
    5
    +k1 :: (# Int, Bool #) -> (# Int, Bool #) -> Int
    
    6
    +{-# NOINLINE k1 #-}
    
    7
    +k1 _ _ = 3
    
    8
    +
    
    9
    +k2 :: (# Int#, Int# #) -> (# Int#, Int# #) -> Int
    
    10
    +{-# NOINLINE k2 #-}
    
    11
    +k2 _ _ = 3
    
    12
    +
    
    13
    +lifted :: Int -> Bool -> Int
    
    14
    +lifted x y = case (# x, y #) of r -> k1 r r
    
    15
    +
    
    16
    +unlifted :: Int# -> Int# -> Int
    
    17
    +unlifted x y = case (# x, y #) of r -> k2 r r

  • testsuite/tests/simplCore/should_compile/T27910.stderr
    1
    +
    
    2
    +==================== FloatOut stats: ====================
    
    3
    +2 Lets floated to top level; 0 Lets floated elsewhere; from 4 Lambda groups
    
    4
    +
    
    5
    +
    
    6
    +
    
    7
    +==================== FloatOut stats: ====================
    
    8
    +4 Lets floated to top level; 0 Lets floated elsewhere; from 6 Lambda groups
    
    9
    +
    
    10
    +
    
    11
    +
    
    12
    +==================== Grand total simplifier statistics ====================
    
    13
    +Total ticks:     30
    
    14
    +
    
    15
    +8 PreInlineUnconditionally
    
    16
    +  1 ds
    
    17
    +  1 ds
    
    18
    +  1 ds
    
    19
    +  1 ds
    
    20
    +  1 ds
    
    21
    +  1 ds
    
    22
    +  1 ds
    
    23
    +  1 ds
    
    24
    +2 PostInlineUnconditionally
    
    25
    +  1 r
    
    26
    +  1 r
    
    27
    +4 UnfoldingDone
    
    28
    +  2 GHC.Internal.Prim.void#
    
    29
    +  1 T27910.k1
    
    30
    +  1 T27910.k2
    
    31
    +8 BetaReduction
    
    32
    +  1 ds
    
    33
    +  1 ds
    
    34
    +  1 ds
    
    35
    +  1 ds
    
    36
    +  1 ds
    
    37
    +  1 ds
    
    38
    +  1 ds
    
    39
    +  1 ds
    
    40
    +4 KnownBranch
    
    41
    +  2 wild
    
    42
    +  1 ww
    
    43
    +  1 ww
    
    44
    +4 CaseElim
    
    45
    +  2 ww
    
    46
    +  2 ww
    
    47
    +9 SimplifierDone 9
    
    48
    +
    
    49
    +

  • testsuite/tests/simplCore/should_compile/all.T
    ... ... @@ -627,5 +627,8 @@ test('T27749',
    627 627
          compile, ['-O -g3 -ddump-simpl -dsuppress-uniques'])
    
    628 628
     
    
    629 629
     test('T27629', only_ways(['optasm']), makefile_test, ['T27629'])
    
    630
    -
    
    631 630
     test('T27936', normal, compile, [''])
    
    631
    +
    
    632
    +# A case-float reaching abstractFloats used to make the Simplifier panic
    
    633
    +test('T27737a', normal, compile, ['-O'])
    
    634
    +test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])