2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[Simplify]{The main module of the simplifier}
7 module Simplify ( simplTopBinds, simplExpr ) where
9 #include "HsVersions.h"
11 import DynFlags ( dopt, DynFlag(Opt_D_dump_inlinings),
16 import SimplUtils ( mkCase, mkLam,
17 SimplCont(..), DupFlag(..), LetRhsFlag(..),
18 mkRhsStop, mkBoringStop, mkLazyArgStop, pushContArgs,
19 contResultType, countArgs, contIsDupable, contIsRhsOrArg,
20 getContArgs, interestingCallContext, interestingArg, isStrictType,
21 preInlineUnconditionally, postInlineUnconditionally,
22 interestingArgContext, inlineMode, activeInline, activeRule
24 import Id ( Id, idType, idInfo, idArity, isDataConWorkId,
25 idUnfolding, setIdUnfolding, isDeadBinder,
26 idNewDemandInfo, setIdInfo,
27 setIdOccInfo, zapLamIdInfo, setOneShotLambda
29 import MkId ( eRROR_ID )
30 import Literal ( mkStringLit )
31 import IdInfo ( OccInfo(..), isLoopBreaker,
32 setArityInfo, zapDemandInfo,
36 import NewDemand ( isStrictDmd )
37 import Unify ( coreRefineTys, dataConCanMatch )
38 import DataCon ( DataCon, dataConTyCon, dataConRepStrictness, isVanillaDataCon,
39 dataConInstArgTys, dataConTyVars )
40 import TyCon ( tyConArity, isAlgTyCon, isNewTyCon, tyConDataCons_maybe )
42 import PprCore ( pprParendExpr, pprCoreExpr )
43 import CoreUnfold ( mkUnfolding, callSiteInline )
44 import CoreUtils ( exprIsDupable, exprIsTrivial, needsCaseBinding,
45 exprIsConApp_maybe, mkPiTypes, findAlt,
46 exprType, exprIsHNF, findDefault, mergeAlts,
47 exprOkForSpeculation, exprArity,
48 mkCoerce, mkCoerce2, mkSCC, mkInlineMe, applyTypeToArg
50 import Rules ( lookupRule )
51 import BasicTypes ( isMarkedStrict )
52 import CostCentre ( currentCCS )
53 import Type ( TvSubstEnv, isUnLiftedType, seqType, tyConAppArgs, funArgTy,
54 splitFunTy_maybe, splitFunTy, coreEqType, splitTyConApp_maybe,
57 import Var ( tyVarKind, mkTyVar )
58 import VarEnv ( elemVarEnv, emptyVarEnv )
59 import TysPrim ( realWorldStatePrimTy )
60 import PrelInfo ( realWorldPrimId )
61 import BasicTypes ( TopLevelFlag(..), isTopLevel,
64 import Name ( mkSysTvName )
65 import StaticFlags ( opt_PprStyle_Debug )
68 import Maybes ( orElse )
70 import Util ( notNull, filterOut )
74 The guts of the simplifier is in this module, but the driver loop for
75 the simplifier is in SimplCore.lhs.
78 -----------------------------------------
79 *** IMPORTANT NOTE ***
80 -----------------------------------------
81 The simplifier used to guarantee that the output had no shadowing, but
82 it does not do so any more. (Actually, it never did!) The reason is
83 documented with simplifyArgs.
86 -----------------------------------------
87 *** IMPORTANT NOTE ***
88 -----------------------------------------
89 Many parts of the simplifier return a bunch of "floats" as well as an
90 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
92 All "floats" are let-binds, not case-binds, but some non-rec lets may
93 be unlifted (with RHS ok-for-speculation).
97 -----------------------------------------
98 ORGANISATION OF FUNCTIONS
99 -----------------------------------------
101 - simplify all top-level binders
102 - for NonRec, call simplRecOrTopPair
103 - for Rec, call simplRecBind
106 ------------------------------
107 simplExpr (applied lambda) ==> simplNonRecBind
108 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
109 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
111 ------------------------------
112 simplRecBind [binders already simplfied]
113 - use simplRecOrTopPair on each pair in turn
115 simplRecOrTopPair [binder already simplified]
116 Used for: recursive bindings (top level and nested)
117 top-level non-recursive bindings
119 - check for PreInlineUnconditionally
123 Used for: non-top-level non-recursive bindings
124 beta reductions (which amount to the same thing)
125 Because it can deal with strict arts, it takes a
126 "thing-inside" and returns an expression
128 - check for PreInlineUnconditionally
129 - simplify binder, including its IdInfo
138 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
139 Used for: binding case-binder and constr args in a known-constructor case
140 - check for PreInLineUnconditionally
144 ------------------------------
145 simplLazyBind: [binder already simplified, RHS not]
146 Used for: recursive bindings (top level and nested)
147 top-level non-recursive bindings
148 non-top-level, but *lazy* non-recursive bindings
149 [must not be strict or unboxed]
150 Returns floats + an augmented environment, not an expression
151 - substituteIdInfo and add result to in-scope
152 [so that rules are available in rec rhs]
155 - float if exposes constructor or PAP
159 completeNonRecX: [binder and rhs both simplified]
160 - if the the thing needs case binding (unlifted and not ok-for-spec)
166 completeLazyBind: [given a simplified RHS]
167 [used for both rec and non-rec bindings, top level and not]
168 - try PostInlineUnconditionally
169 - add unfolding [this is the only place we add an unfolding]
174 Right hand sides and arguments
175 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176 In many ways we want to treat
177 (a) the right hand side of a let(rec), and
178 (b) a function argument
179 in the same way. But not always! In particular, we would
180 like to leave these arguments exactly as they are, so they
181 will match a RULE more easily.
186 It's harder to make the rule match if we ANF-ise the constructor,
187 or eta-expand the PAP:
189 f (let { a = g x; b = h x } in (a,b))
192 On the other hand if we see the let-defns
197 then we *do* want to ANF-ise and eta-expand, so that p and q
198 can be safely inlined.
200 Even floating lets out is a bit dubious. For let RHS's we float lets
201 out if that exposes a value, so that the value can be inlined more vigorously.
204 r = let x = e in (x,x)
206 Here, if we float the let out we'll expose a nice constructor. We did experiments
207 that showed this to be a generally good thing. But it was a bad thing to float
208 lets out unconditionally, because that meant they got allocated more often.
210 For function arguments, there's less reason to expose a constructor (it won't
211 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
212 So for the moment we don't float lets out of function arguments either.
217 For eta expansion, we want to catch things like
219 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
221 If the \x was on the RHS of a let, we'd eta expand to bring the two
222 lambdas together. And in general that's a good thing to do. Perhaps
223 we should eta expand wherever we find a (value) lambda? Then the eta
224 expansion at a let RHS can concentrate solely on the PAP case.
227 %************************************************************************
229 \subsection{Bindings}
231 %************************************************************************
234 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
236 simplTopBinds env binds
237 = -- Put all the top-level binders into scope at the start
238 -- so that if a transformation rule has unexpectedly brought
239 -- anything into scope, then we don't get a complaint about that.
240 -- It's rather as if the top-level binders were imported.
241 simplRecBndrs env (bindersOfBinds binds) `thenSmpl` \ (env, bndrs') ->
242 simpl_binds env binds bndrs' `thenSmpl` \ (floats, _) ->
243 freeTick SimplifierDone `thenSmpl_`
244 returnSmpl (floatBinds floats)
246 -- We need to track the zapped top-level binders, because
247 -- they should have their fragile IdInfo zapped (notably occurrence info)
248 -- That's why we run down binds and bndrs' simultaneously.
249 simpl_binds :: SimplEnv -> [InBind] -> [OutId] -> SimplM (FloatsWith ())
250 simpl_binds env [] bs = ASSERT( null bs ) returnSmpl (emptyFloats env, ())
251 simpl_binds env (bind:binds) bs = simpl_bind env bind bs `thenSmpl` \ (floats,env) ->
252 addFloats env floats $ \env ->
253 simpl_binds env binds (drop_bs bind bs)
255 drop_bs (NonRec _ _) (_ : bs) = bs
256 drop_bs (Rec prs) bs = drop (length prs) bs
258 simpl_bind env bind bs
259 = getDOptsSmpl `thenSmpl` \ dflags ->
260 if dopt Opt_D_dump_inlinings dflags then
261 pprTrace "SimplBind" (ppr (bindersOf bind)) $ simpl_bind1 env bind bs
263 simpl_bind1 env bind bs
265 simpl_bind1 env (NonRec b r) (b':_) = simplRecOrTopPair env TopLevel b b' r
266 simpl_bind1 env (Rec pairs) bs' = simplRecBind env TopLevel pairs bs'
270 %************************************************************************
272 \subsection{simplNonRec}
274 %************************************************************************
276 simplNonRecBind is used for
277 * non-top-level non-recursive lets in expressions
281 * An unsimplified (binder, rhs) pair
282 * The env for the RHS. It may not be the same as the
283 current env because the bind might occur via (\x.E) arg
285 It uses the CPS form because the binding might be strict, in which
286 case we might discard the continuation:
287 let x* = error "foo" in (...x...)
289 It needs to turn unlifted bindings into a @case@. They can arise
290 from, say: (\x -> e) (4# + 3#)
293 simplNonRecBind :: SimplEnv
295 -> InExpr -> SimplEnv -- Arg, with its subst-env
296 -> OutType -- Type of thing computed by the context
297 -> (SimplEnv -> SimplM FloatsWithExpr) -- The body
298 -> SimplM FloatsWithExpr
300 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
302 = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
305 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
306 = simplNonRecBind' env bndr rhs rhs_se cont_ty thing_inside
308 simplNonRecBind' env bndr rhs rhs_se cont_ty thing_inside
309 | preInlineUnconditionally env NotTopLevel bndr rhs
310 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
311 thing_inside (extendIdSubst env bndr (mkContEx rhs_se rhs))
313 | isStrictDmd (idNewDemandInfo bndr) || isStrictType bndr_ty -- A strict let
314 = -- Don't use simplBinder because that doesn't keep
315 -- fragile occurrence info in the substitution
316 simplNonRecBndr env bndr `thenSmpl` \ (env, bndr1) ->
317 simplStrictArg AnRhs env rhs rhs_se (idType bndr1) cont_ty $ \ env1 rhs1 ->
319 -- Now complete the binding and simplify the body
321 (env2,bndr2) = addLetIdInfo env1 bndr bndr1
323 if needsCaseBinding bndr_ty rhs1
325 thing_inside env2 `thenSmpl` \ (floats, body) ->
326 returnSmpl (emptyFloats env2, Case rhs1 bndr2 (exprType body)
327 [(DEFAULT, [], wrapFloats floats body)])
329 completeNonRecX env2 True {- strict -} bndr bndr2 rhs1 thing_inside
331 | otherwise -- Normal, lazy case
332 = -- Don't use simplBinder because that doesn't keep
333 -- fragile occurrence info in the substitution
334 simplNonRecBndr env bndr `thenSmpl` \ (env, bndr') ->
335 simplLazyBind env NotTopLevel NonRecursive
336 bndr bndr' rhs rhs_se `thenSmpl` \ (floats, env) ->
337 addFloats env floats thing_inside
340 bndr_ty = idType bndr
343 A specialised variant of simplNonRec used when the RHS is already simplified, notably
344 in knownCon. It uses case-binding where necessary.
347 simplNonRecX :: SimplEnv
348 -> InId -- Old binder
349 -> OutExpr -- Simplified RHS
350 -> (SimplEnv -> SimplM FloatsWithExpr)
351 -> SimplM FloatsWithExpr
353 simplNonRecX env bndr new_rhs thing_inside
354 | needsCaseBinding (idType bndr) new_rhs
355 -- Make this test *before* the preInlineUnconditionally
356 -- Consider case I# (quotInt# x y) of
357 -- I# v -> let w = J# v in ...
358 -- If we gaily inline (quotInt# x y) for v, we end up building an
360 -- let w = J# (quotInt# x y) in ...
361 -- because quotInt# can fail.
362 = simplBinder env bndr `thenSmpl` \ (env, bndr') ->
363 thing_inside env `thenSmpl` \ (floats, body) ->
364 let body' = wrapFloats floats body in
365 returnSmpl (emptyFloats env, Case new_rhs bndr' (exprType body') [(DEFAULT, [], body')])
367 {- No, no, no! Do not try preInlineUnconditionally
368 Doing so risks exponential behaviour, because new_rhs has been simplified once already
369 In the cases described by the folowing commment, postInlineUnconditionally will
370 catch many of the relevant cases.
371 -- This happens; for example, the case_bndr during case of
372 -- known constructor: case (a,b) of x { (p,q) -> ... }
373 -- Here x isn't mentioned in the RHS, so we don't want to
374 -- create the (dead) let-binding let x = (a,b) in ...
376 -- Similarly, single occurrences can be inlined vigourously
377 -- e.g. case (f x, g y) of (a,b) -> ....
378 -- If a,b occur once we can avoid constructing the let binding for them.
379 | preInlineUnconditionally env NotTopLevel bndr new_rhs
380 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
382 -- NB: completeLazyBind uses postInlineUnconditionally; no need to do that here
386 = simplBinder env bndr `thenSmpl` \ (env, bndr') ->
387 completeNonRecX env False {- Non-strict; pessimistic -}
388 bndr bndr' new_rhs thing_inside
390 completeNonRecX env is_strict old_bndr new_bndr new_rhs thing_inside
391 = mkAtomicArgs is_strict
392 True {- OK to float unlifted -}
393 new_rhs `thenSmpl` \ (aux_binds, rhs2) ->
395 -- Make the arguments atomic if necessary,
396 -- adding suitable bindings
397 addAtomicBindsE env (fromOL aux_binds) $ \ env ->
398 completeLazyBind env NotTopLevel
399 old_bndr new_bndr rhs2 `thenSmpl` \ (floats, env) ->
400 addFloats env floats thing_inside
404 %************************************************************************
406 \subsection{Lazy bindings}
408 %************************************************************************
410 simplRecBind is used for
411 * recursive bindings only
414 simplRecBind :: SimplEnv -> TopLevelFlag
415 -> [(InId, InExpr)] -> [OutId]
416 -> SimplM (FloatsWith SimplEnv)
417 simplRecBind env top_lvl pairs bndrs'
418 = go env pairs bndrs' `thenSmpl` \ (floats, env) ->
419 returnSmpl (flattenFloats floats, env)
421 go env [] _ = returnSmpl (emptyFloats env, env)
423 go env ((bndr, rhs) : pairs) (bndr' : bndrs')
424 = simplRecOrTopPair env top_lvl bndr bndr' rhs `thenSmpl` \ (floats, env) ->
425 addFloats env floats (\env -> go env pairs bndrs')
429 simplRecOrTopPair is used for
430 * recursive bindings (whether top level or not)
431 * top-level non-recursive bindings
433 It assumes the binder has already been simplified, but not its IdInfo.
436 simplRecOrTopPair :: SimplEnv
438 -> InId -> OutId -- Binder, both pre-and post simpl
439 -> InExpr -- The RHS and its environment
440 -> SimplM (FloatsWith SimplEnv)
442 simplRecOrTopPair env top_lvl bndr bndr' rhs
443 | preInlineUnconditionally env top_lvl bndr rhs -- Check for unconditional inline
444 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
445 returnSmpl (emptyFloats env, extendIdSubst env bndr (mkContEx env rhs))
448 = simplLazyBind env top_lvl Recursive bndr bndr' rhs env
449 -- May not actually be recursive, but it doesn't matter
453 simplLazyBind is used for
454 * recursive bindings (whether top level or not)
455 * top-level non-recursive bindings
456 * non-top-level *lazy* non-recursive bindings
458 [Thus it deals with the lazy cases from simplNonRecBind, and all cases
459 from SimplRecOrTopBind]
462 1. It assumes that the binder is *already* simplified,
463 and is in scope, but not its IdInfo
465 2. It assumes that the binder type is lifted.
467 3. It does not check for pre-inline-unconditionallly;
468 that should have been done already.
471 simplLazyBind :: SimplEnv
472 -> TopLevelFlag -> RecFlag
473 -> InId -> OutId -- Binder, both pre-and post simpl
474 -> InExpr -> SimplEnv -- The RHS and its environment
475 -> SimplM (FloatsWith SimplEnv)
477 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
479 (env1,bndr2) = addLetIdInfo env bndr bndr1
480 rhs_env = setInScope rhs_se env1
481 is_top_level = isTopLevel top_lvl
482 ok_float_unlifted = not is_top_level && isNonRec is_rec
483 rhs_cont = mkRhsStop (idType bndr2)
485 -- Simplify the RHS; note the mkRhsStop, which tells
486 -- the simplifier that this is the RHS of a let.
487 simplExprF rhs_env rhs rhs_cont `thenSmpl` \ (floats, rhs1) ->
489 -- If any of the floats can't be floated, give up now
490 -- (The allLifted predicate says True for empty floats.)
491 if (not ok_float_unlifted && not (allLifted floats)) then
492 completeLazyBind env1 top_lvl bndr bndr2
493 (wrapFloats floats rhs1)
496 -- ANF-ise a constructor or PAP rhs
497 mkAtomicArgs False {- Not strict -}
498 ok_float_unlifted rhs1 `thenSmpl` \ (aux_binds, rhs2) ->
500 -- If the result is a PAP, float the floats out, else wrap them
501 -- By this time it's already been ANF-ised (if necessary)
502 if isEmptyFloats floats && isNilOL aux_binds then -- Shortcut a common case
503 completeLazyBind env1 top_lvl bndr bndr2 rhs2
505 else if is_top_level || exprIsTrivial rhs2 || exprIsHNF rhs2 then
506 -- WARNING: long dodgy argument coming up
507 -- WANTED: a better way to do this
509 -- We can't use "exprIsCheap" instead of exprIsHNF,
510 -- because that causes a strictness bug.
511 -- x = let y* = E in case (scc y) of { T -> F; F -> T}
512 -- The case expression is 'cheap', but it's wrong to transform to
513 -- y* = E; x = case (scc y) of {...}
514 -- Either we must be careful not to float demanded non-values, or
515 -- we must use exprIsHNF for the test, which ensures that the
516 -- thing is non-strict. So exprIsHNF => bindings are non-strict
517 -- I think. The WARN below tests for this.
519 -- We use exprIsTrivial here because we want to reveal lone variables.
520 -- E.g. let { x = letrec { y = E } in y } in ...
521 -- Here we definitely want to float the y=E defn.
522 -- exprIsHNF definitely isn't right for that.
524 -- Again, the floated binding can't be strict; if it's recursive it'll
525 -- be non-strict; if it's non-recursive it'd be inlined.
527 -- Note [SCC-and-exprIsTrivial]
529 -- y = let { x* = E } in scc "foo" x
530 -- then we do *not* want to float out the x binding, because
531 -- it's strict! Fortunately, exprIsTrivial replies False to
534 -- There's a subtlety here. There may be a binding (x* = e) in the
535 -- floats, where the '*' means 'will be demanded'. So is it safe
536 -- to float it out? Answer no, but it won't matter because
537 -- we only float if (a) arg' is a WHNF, or (b) it's going to top level
538 -- and so there can't be any 'will be demanded' bindings in the floats.
540 ASSERT2( is_top_level || not (any demanded_float (floatBinds floats)),
541 ppr (filter demanded_float (floatBinds floats)) )
543 tick LetFloatFromLet `thenSmpl_` (
544 addFloats env1 floats $ \ env2 ->
545 addAtomicBinds env2 (fromOL aux_binds) $ \ env3 ->
546 completeLazyBind env3 top_lvl bndr bndr2 rhs2)
549 completeLazyBind env1 top_lvl bndr bndr2 (wrapFloats floats rhs1)
552 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
553 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
554 demanded_float (Rec _) = False
559 %************************************************************************
561 \subsection{Completing a lazy binding}
563 %************************************************************************
566 * deals only with Ids, not TyVars
567 * takes an already-simplified binder and RHS
568 * is used for both recursive and non-recursive bindings
569 * is used for both top-level and non-top-level bindings
571 It does the following:
572 - tries discarding a dead binding
573 - tries PostInlineUnconditionally
574 - add unfolding [this is the only place we add an unfolding]
577 It does *not* attempt to do let-to-case. Why? Because it is used for
578 - top-level bindings (when let-to-case is impossible)
579 - many situations where the "rhs" is known to be a WHNF
580 (so let-to-case is inappropriate).
583 completeLazyBind :: SimplEnv
584 -> TopLevelFlag -- Flag stuck into unfolding
585 -> InId -- Old binder
586 -> OutId -- New binder
587 -> OutExpr -- Simplified RHS
588 -> SimplM (FloatsWith SimplEnv)
589 -- We return a new SimplEnv, because completeLazyBind may choose to do its work
590 -- by extending the substitution (e.g. let x = y in ...)
591 -- The new binding (if any) is returned as part of the floats.
592 -- NB: the returned SimplEnv has the right SubstEnv, but you should
593 -- (as usual) use the in-scope-env from the floats
595 completeLazyBind env top_lvl old_bndr new_bndr new_rhs
596 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
597 = -- Drop the binding
598 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
599 returnSmpl (emptyFloats env, extendIdSubst env old_bndr (DoneEx new_rhs))
600 -- Use the substitution to make quite, quite sure that the substitution
601 -- will happen, since we are going to discard the binding
606 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
608 -- Add the unfolding *only* for non-loop-breakers
609 -- Making loop breakers not have an unfolding at all
610 -- means that we can avoid tests in exprIsConApp, for example.
611 -- This is important: if exprIsConApp says 'yes' for a recursive
612 -- thing, then we can get into an infinite loop
614 -- If the unfolding is a value, the demand info may
615 -- go pear-shaped, so we nuke it. Example:
617 -- case x of (p,q) -> h p q x
618 -- Here x is certainly demanded. But after we've nuked
619 -- the case, we'll get just
620 -- let x = (a,b) in h a b x
621 -- and now x is not demanded (I'm assuming h is lazy)
622 -- This really happens. Similarly
623 -- let f = \x -> e in ...f..f...
624 -- After inling f at some of its call sites the original binding may
625 -- (for example) be no longer strictly demanded.
626 -- The solution here is a bit ad hoc...
627 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
628 final_info | loop_breaker = new_bndr_info
629 | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
630 | otherwise = info_w_unf
632 final_id = new_bndr `setIdInfo` final_info
634 -- These seqs forces the Id, and hence its IdInfo,
635 -- and hence any inner substitutions
637 returnSmpl (unitFloat env final_id new_rhs, env)
640 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
641 loop_breaker = isLoopBreaker occ_info
642 old_info = idInfo old_bndr
643 occ_info = occInfo old_info
648 %************************************************************************
650 \subsection[Simplify-simplExpr]{The main function: simplExpr}
652 %************************************************************************
654 The reason for this OutExprStuff stuff is that we want to float *after*
655 simplifying a RHS, not before. If we do so naively we get quadratic
656 behaviour as things float out.
658 To see why it's important to do it after, consider this (real) example:
672 a -- Can't inline a this round, cos it appears twice
676 Each of the ==> steps is a round of simplification. We'd save a
677 whole round if we float first. This can cascade. Consider
682 let f = let d1 = ..d.. in \y -> e
686 in \x -> ...(\y ->e)...
688 Only in this second round can the \y be applied, and it
689 might do the same again.
693 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
694 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
696 expr_ty' = substTy env (exprType expr)
697 -- The type in the Stop continuation, expr_ty', is usually not used
698 -- It's only needed when discarding continuations after finding
699 -- a function that returns bottom.
700 -- Hence the lazy substitution
703 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
704 -- Simplify an expression, given a continuation
705 simplExprC env expr cont
706 = simplExprF env expr cont `thenSmpl` \ (floats, expr) ->
707 returnSmpl (wrapFloats floats expr)
709 simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM FloatsWithExpr
710 -- Simplify an expression, returning floated binds
712 simplExprF env (Var v) cont = simplVar env v cont
713 simplExprF env (Lit lit) cont = rebuild env (Lit lit) cont
714 simplExprF env expr@(Lam _ _) cont = simplLam env expr cont
715 simplExprF env (Note note expr) cont = simplNote env note expr cont
716 simplExprF env (App fun arg) cont = simplExprF env fun (ApplyTo NoDup arg (Just env) cont)
718 simplExprF env (Type ty) cont
719 = ASSERT( contIsRhsOrArg cont )
720 simplType env ty `thenSmpl` \ ty' ->
721 rebuild env (Type ty') cont
723 simplExprF env (Case scrut bndr case_ty alts) cont
724 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
725 = -- Simplify the scrutinee with a Select continuation
726 simplExprF env scrut (Select NoDup bndr alts env cont)
729 = -- If case-of-case is off, simply simplify the case expression
730 -- in a vanilla Stop context, and rebuild the result around it
731 simplExprC env scrut case_cont `thenSmpl` \ case_expr' ->
732 rebuild env case_expr' cont
734 case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
735 case_ty' = substTy env case_ty -- c.f. defn of simplExpr
737 simplExprF env (Let (Rec pairs) body) cont
738 = simplRecBndrs env (map fst pairs) `thenSmpl` \ (env, bndrs') ->
739 -- NB: bndrs' don't have unfoldings or rules
740 -- We add them as we go down
742 simplRecBind env NotTopLevel pairs bndrs' `thenSmpl` \ (floats, env) ->
743 addFloats env floats $ \ env ->
744 simplExprF env body cont
746 -- A non-recursive let is dealt with by simplNonRecBind
747 simplExprF env (Let (NonRec bndr rhs) body) cont
748 = simplNonRecBind env bndr rhs env (contResultType cont) $ \ env ->
749 simplExprF env body cont
752 ---------------------------------
753 simplType :: SimplEnv -> InType -> SimplM OutType
754 -- Kept monadic just so we can do the seqType
756 = seqType new_ty `seq` returnSmpl new_ty
758 new_ty = substTy env ty
762 %************************************************************************
766 %************************************************************************
769 simplLam env fun cont
772 zap_it = mkLamBndrZapper fun (countArgs cont)
773 cont_ty = contResultType cont
775 -- Type-beta reduction
776 go env (Lam bndr body) (ApplyTo _ (Type ty_arg) mb_arg_se body_cont)
777 = ASSERT( isTyVar bndr )
778 do { tick (BetaReduction bndr)
779 ; ty_arg' <- case mb_arg_se of
780 Just arg_se -> simplType (setInScope arg_se env) ty_arg
781 Nothing -> return ty_arg
782 ; go (extendTvSubst env bndr ty_arg') body body_cont }
784 -- Ordinary beta reduction
785 go env (Lam bndr body) cont@(ApplyTo _ arg (Just arg_se) body_cont)
786 = do { tick (BetaReduction bndr)
787 ; simplNonRecBind env (zap_it bndr) arg arg_se cont_ty $ \ env ->
788 go env body body_cont }
790 go env (Lam bndr body) cont@(ApplyTo _ arg Nothing body_cont)
791 = do { tick (BetaReduction bndr)
792 ; simplNonRecX env (zap_it bndr) arg $ \ env ->
793 go env body body_cont }
795 -- Not enough args, so there are real lambdas left to put in the result
796 go env lam@(Lam _ _) cont
797 = do { (env, bndrs') <- simplLamBndrs env bndrs
798 ; body' <- simplExpr env body
799 ; (floats, new_lam) <- mkLam env bndrs' body' cont
800 ; addFloats env floats $ \ env ->
801 rebuild env new_lam cont }
803 (bndrs,body) = collectBinders lam
805 -- Exactly enough args
806 go env expr cont = simplExprF env expr cont
808 mkLamBndrZapper :: CoreExpr -- Function
809 -> Int -- Number of args supplied, *including* type args
810 -> Id -> Id -- Use this to zap the binders
811 mkLamBndrZapper fun n_args
812 | n_args >= n_params fun = \b -> b -- Enough args
813 | otherwise = \b -> zapLamIdInfo b
815 -- NB: we count all the args incl type args
816 -- so we must count all the binders (incl type lambdas)
817 n_params (Note _ e) = n_params e
818 n_params (Lam b e) = 1 + n_params e
819 n_params other = 0::Int
823 %************************************************************************
827 %************************************************************************
830 simplNote env (Coerce to from) body cont
832 addCoerce s1 k1 cont -- Drop redundant coerces. This can happen if a polymoprhic
833 -- (coerce a b e) is instantiated with a=ty1 b=ty2 and the
834 -- two are the same. This happens a lot in Happy-generated parsers
835 | s1 `coreEqType` k1 = cont
837 addCoerce s1 k1 (CoerceIt t1 cont)
838 -- coerce T1 S1 (coerce S1 K1 e)
841 -- coerce T1 K1 e, otherwise
843 -- For example, in the initial form of a worker
844 -- we may find (coerce T (coerce S (\x.e))) y
845 -- and we'd like it to simplify to e[y/x] in one round
847 | t1 `coreEqType` k1 = cont -- The coerces cancel out
848 | otherwise = CoerceIt t1 cont -- They don't cancel, but
849 -- the inner one is redundant
851 addCoerce t1t2 s1s2 (ApplyTo dup arg mb_arg_se cont)
852 | not (isTypeArg arg), -- This whole case only works for value args
853 -- Could upgrade to have equiv thing for type apps too
854 Just (s1, s2) <- splitFunTy_maybe s1s2
855 -- (coerce (T1->T2) (S1->S2) F) E
857 -- coerce T2 S2 (F (coerce S1 T1 E))
859 -- t1t2 must be a function type, T1->T2, because it's applied to something
860 -- but s1s2 might conceivably not be
862 -- When we build the ApplyTo we can't mix the out-types
863 -- with the InExpr in the argument, so we simply substitute
864 -- to make it all consistent. It's a bit messy.
865 -- But it isn't a common case.
867 (t1,t2) = splitFunTy t1t2
868 new_arg = mkCoerce2 s1 t1 arg'
869 arg' = case mb_arg_se of
871 Just arg_se -> substExpr (setInScope arg_se env) arg
873 ApplyTo dup new_arg Nothing (addCoerce t2 s2 cont)
875 addCoerce to' _ cont = CoerceIt to' cont
877 simplType env to `thenSmpl` \ to' ->
878 simplType env from `thenSmpl` \ from' ->
879 simplExprF env body (addCoerce to' from' cont)
882 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
883 -- inlining. All other CCCSs are mapped to currentCCS.
884 simplNote env (SCC cc) e cont
885 = simplExpr (setEnclosingCC env currentCCS) e `thenSmpl` \ e' ->
886 rebuild env (mkSCC cc e') cont
888 -- See notes with SimplMonad.inlineMode
889 simplNote env InlineMe e cont
890 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
891 = -- Don't inline inside an INLINE expression
892 simplExpr (setMode inlineMode env ) e `thenSmpl` \ e' ->
893 rebuild env (mkInlineMe e') cont
895 | otherwise -- Dissolve the InlineMe note if there's
896 -- an interesting context of any kind to combine with
897 -- (even a type application -- anything except Stop)
898 = simplExprF env e cont
900 simplNote env (CoreNote s) e cont
901 = simplExpr env e `thenSmpl` \ e' ->
902 rebuild env (Note (CoreNote s) e') cont
906 %************************************************************************
908 \subsection{Dealing with calls}
910 %************************************************************************
913 simplVar env var cont
914 = case substId env var of
915 DoneEx e -> simplExprF (zapSubstEnv env) e cont
916 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
917 DoneId var1 occ -> completeCall (zapSubstEnv env) var1 occ cont
918 -- Note [zapSubstEnv]
919 -- The template is already simplified, so don't re-substitute.
920 -- This is VITAL. Consider
922 -- let y = \z -> ...x... in
924 -- We'll clone the inner \x, adding x->x' in the id_subst
925 -- Then when we inline y, we must *not* replace x by x' in
926 -- the inlined copy!!
928 ---------------------------------------------------------
929 -- Dealing with a call site
931 completeCall env var occ_info cont
932 = -- Simplify the arguments
933 getDOptsSmpl `thenSmpl` \ dflags ->
935 chkr = getSwitchChecker env
936 (args, call_cont) = getContArgs chkr var cont
939 simplifyArgs env fn_ty (interestingArgContext var call_cont) args
940 (contResultType call_cont) $ \ env args ->
942 -- Next, look for rules or specialisations that match
944 -- It's important to simplify the args first, because the rule-matcher
945 -- doesn't do substitution as it goes. We don't want to use subst_args
946 -- (defined in the 'where') because that throws away useful occurrence info,
947 -- and perhaps-very-important specialisations.
949 -- Some functions have specialisations *and* are strict; in this case,
950 -- we don't want to inline the wrapper of the non-specialised thing; better
951 -- to call the specialised thing instead.
952 -- We used to use the black-listing mechanism to ensure that inlining of
953 -- the wrapper didn't occur for things that have specialisations till a
954 -- later phase, so but now we just try RULES first
956 -- You might think that we shouldn't apply rules for a loop breaker:
957 -- doing so might give rise to an infinite loop, because a RULE is
958 -- rather like an extra equation for the function:
959 -- RULE: f (g x) y = x+y
962 -- But it's too drastic to disable rules for loop breakers.
963 -- Even the foldr/build rule would be disabled, because foldr
964 -- is recursive, and hence a loop breaker:
965 -- foldr k z (build g) = g k z
966 -- So it's up to the programmer: rules can cause divergence
969 in_scope = getInScope env
971 maybe_rule = case activeRule env of
972 Nothing -> Nothing -- No rules apply
973 Just act_fn -> lookupRule act_fn in_scope rules var args
976 Just (rule_name, rule_rhs) ->
977 tick (RuleFired rule_name) `thenSmpl_`
978 (if dopt Opt_D_dump_inlinings dflags then
979 pprTrace "Rule fired" (vcat [
980 text "Rule:" <+> ftext rule_name,
981 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
982 text "After: " <+> pprCoreExpr rule_rhs,
983 text "Cont: " <+> ppr call_cont])
986 simplExprF env rule_rhs call_cont ;
988 Nothing -> -- No rules
990 -- Next, look for an inlining
992 arg_infos = [ interestingArg arg | arg <- args, isValArg arg]
993 interesting_cont = interestingCallContext (notNull args)
996 active_inline = activeInline env var occ_info
997 maybe_inline = callSiteInline dflags active_inline occ_info
998 var arg_infos interesting_cont
1000 case maybe_inline of {
1001 Just unfolding -- There is an inlining!
1002 -> tick (UnfoldingDone var) `thenSmpl_`
1003 (if dopt Opt_D_dump_inlinings dflags then
1004 pprTrace "Inlining done" (vcat [
1005 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1006 text "Inlined fn: " <+> ppr unfolding,
1007 text "Cont: " <+> ppr call_cont])
1010 simplExprF env unfolding (pushContArgs args call_cont)
1013 Nothing -> -- No inlining!
1016 rebuild env (mkApps (Var var) args) call_cont
1020 %************************************************************************
1022 \subsection{Arguments}
1024 %************************************************************************
1027 ---------------------------------------------------------
1028 -- Simplifying the arguments of a call
1030 simplifyArgs :: SimplEnv
1031 -> OutType -- Type of the function
1032 -> Bool -- True if the fn has RULES
1033 -> [(InExpr, Maybe SimplEnv, Bool)] -- Details of the arguments
1034 -> OutType -- Type of the continuation
1035 -> (SimplEnv -> [OutExpr] -> SimplM FloatsWithExpr)
1036 -> SimplM FloatsWithExpr
1038 -- [CPS-like because of strict arguments]
1040 -- Simplify the arguments to a call.
1041 -- This part of the simplifier may break the no-shadowing invariant
1043 -- f (...(\a -> e)...) (case y of (a,b) -> e')
1044 -- where f is strict in its second arg
1045 -- If we simplify the innermost one first we get (...(\a -> e)...)
1046 -- Simplifying the second arg makes us float the case out, so we end up with
1047 -- case y of (a,b) -> f (...(\a -> e)...) e'
1048 -- So the output does not have the no-shadowing invariant. However, there is
1049 -- no danger of getting name-capture, because when the first arg was simplified
1050 -- we used an in-scope set that at least mentioned all the variables free in its
1051 -- static environment, and that is enough.
1053 -- We can't just do innermost first, or we'd end up with a dual problem:
1054 -- case x of (a,b) -> f e (...(\a -> e')...)
1056 -- I spent hours trying to recover the no-shadowing invariant, but I just could
1057 -- not think of an elegant way to do it. The simplifier is already knee-deep in
1058 -- continuations. We have to keep the right in-scope set around; AND we have
1059 -- to get the effect that finding (error "foo") in a strict arg position will
1060 -- discard the entire application and replace it with (error "foo"). Getting
1061 -- all this at once is TOO HARD!
1063 simplifyArgs env fn_ty has_rules args cont_ty thing_inside
1064 = go env fn_ty args thing_inside
1066 go env fn_ty [] thing_inside = thing_inside env []
1067 go env fn_ty (arg:args) thing_inside = simplifyArg env fn_ty has_rules arg cont_ty $ \ env arg' ->
1068 go env (applyTypeToArg fn_ty arg') args $ \ env args' ->
1069 thing_inside env (arg':args')
1071 simplifyArg env fn_ty has_rules (arg, Nothing, _) cont_ty thing_inside
1072 = thing_inside env arg -- Already simplified
1074 simplifyArg env fn_ty has_rules (Type ty_arg, Just se, _) cont_ty thing_inside
1075 = simplType (setInScope se env) ty_arg `thenSmpl` \ new_ty_arg ->
1076 thing_inside env (Type new_ty_arg)
1078 simplifyArg env fn_ty has_rules (val_arg, Just arg_se, is_strict) cont_ty thing_inside
1080 = simplStrictArg AnArg env val_arg arg_se arg_ty cont_ty thing_inside
1082 | otherwise -- Lazy argument
1083 -- DO NOT float anything outside, hence simplExprC
1084 -- There is no benefit (unlike in a let-binding), and we'd
1085 -- have to be very careful about bogus strictness through
1086 -- floating a demanded let.
1087 = simplExprC (setInScope arg_se env) val_arg
1088 (mkLazyArgStop arg_ty has_rules) `thenSmpl` \ arg1 ->
1089 thing_inside env arg1
1091 arg_ty = funArgTy fn_ty
1094 simplStrictArg :: LetRhsFlag
1095 -> SimplEnv -- The env of the call
1096 -> InExpr -> SimplEnv -- The arg plus its env
1097 -> OutType -- arg_ty: type of the argument
1098 -> OutType -- cont_ty: Type of thing computed by the context
1099 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)
1100 -- Takes an expression of type rhs_ty,
1101 -- returns an expression of type cont_ty
1102 -- The env passed to this continuation is the
1103 -- env of the call, plus any new in-scope variables
1104 -> SimplM FloatsWithExpr -- An expression of type cont_ty
1106 simplStrictArg is_rhs call_env arg arg_env arg_ty cont_ty thing_inside
1107 = simplExprF (setInScope arg_env call_env) arg
1108 (ArgOf is_rhs arg_ty cont_ty (\ new_env -> thing_inside (setInScope call_env new_env)))
1109 -- Notice the way we use arg_env (augmented with in-scope vars from call_env)
1110 -- to simplify the argument
1111 -- and call-env (augmented with in-scope vars from the arg) to pass to the continuation
1115 %************************************************************************
1117 \subsection{mkAtomicArgs}
1119 %************************************************************************
1121 mkAtomicArgs takes a putative RHS, checks whether it's a PAP or
1122 constructor application and, if so, converts it to ANF, so that the
1123 resulting thing can be inlined more easily. Thus
1130 There are three sorts of binding context, specified by the two
1136 N N Top-level or recursive Only bind args of lifted type
1138 N Y Non-top-level and non-recursive, Bind args of lifted type, or
1139 but lazy unlifted-and-ok-for-speculation
1141 Y Y Non-top-level, non-recursive, Bind all args
1142 and strict (demanded)
1149 there is no point in transforming to
1151 x = case (y div# z) of r -> MkC r
1153 because the (y div# z) can't float out of the let. But if it was
1154 a *strict* let, then it would be a good thing to do. Hence the
1155 context information.
1158 mkAtomicArgs :: Bool -- A strict binding
1159 -> Bool -- OK to float unlifted args
1161 -> SimplM (OrdList (OutId,OutExpr), -- The floats (unusually) may include
1162 OutExpr) -- things that need case-binding,
1163 -- if the strict-binding flag is on
1165 mkAtomicArgs is_strict ok_float_unlifted rhs
1166 | (Var fun, args) <- collectArgs rhs, -- It's an application
1167 isDataConWorkId fun || valArgCount args < idArity fun -- And it's a constructor or PAP
1168 = go fun nilOL [] args -- Have a go
1170 | otherwise = bale_out -- Give up
1173 bale_out = returnSmpl (nilOL, rhs)
1175 go fun binds rev_args []
1176 = returnSmpl (binds, mkApps (Var fun) (reverse rev_args))
1178 go fun binds rev_args (arg : args)
1179 | exprIsTrivial arg -- Easy case
1180 = go fun binds (arg:rev_args) args
1182 | not can_float_arg -- Can't make this arg atomic
1183 = bale_out -- ... so give up
1185 | otherwise -- Don't forget to do it recursively
1186 -- E.g. x = a:b:c:[]
1187 = mkAtomicArgs is_strict ok_float_unlifted arg `thenSmpl` \ (arg_binds, arg') ->
1188 newId FSLIT("a") arg_ty `thenSmpl` \ arg_id ->
1189 go fun ((arg_binds `snocOL` (arg_id,arg')) `appOL` binds)
1190 (Var arg_id : rev_args) args
1192 arg_ty = exprType arg
1193 can_float_arg = is_strict
1194 || not (isUnLiftedType arg_ty)
1195 || (ok_float_unlifted && exprOkForSpeculation arg)
1198 addAtomicBinds :: SimplEnv -> [(OutId,OutExpr)]
1199 -> (SimplEnv -> SimplM (FloatsWith a))
1200 -> SimplM (FloatsWith a)
1201 addAtomicBinds env [] thing_inside = thing_inside env
1202 addAtomicBinds env ((v,r):bs) thing_inside = addAuxiliaryBind env (NonRec v r) $ \ env ->
1203 addAtomicBinds env bs thing_inside
1205 addAtomicBindsE :: SimplEnv -> [(OutId,OutExpr)]
1206 -> (SimplEnv -> SimplM FloatsWithExpr)
1207 -> SimplM FloatsWithExpr
1208 -- Same again, but this time we're in an expression context,
1209 -- and may need to do some case bindings
1211 addAtomicBindsE env [] thing_inside
1213 addAtomicBindsE env ((v,r):bs) thing_inside
1214 | needsCaseBinding (idType v) r
1215 = addAtomicBindsE (addNewInScopeIds env [v]) bs thing_inside `thenSmpl` \ (floats, expr) ->
1216 WARN( exprIsTrivial expr, ppr v <+> pprCoreExpr expr )
1217 (let body = wrapFloats floats expr in
1218 returnSmpl (emptyFloats env, Case r v (exprType body) [(DEFAULT,[],body)]))
1221 = addAuxiliaryBind env (NonRec v r) $ \ env ->
1222 addAtomicBindsE env bs thing_inside
1226 %************************************************************************
1228 \subsection{The main rebuilder}
1230 %************************************************************************
1233 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
1235 rebuild env expr (Stop _ _ _) = rebuildDone env expr
1236 rebuild env expr (ArgOf _ _ _ cont_fn) = cont_fn env expr
1237 rebuild env expr (CoerceIt to_ty cont) = rebuild env (mkCoerce to_ty expr) cont
1238 rebuild env expr (Select _ bndr alts se cont) = rebuildCase (setInScope se env) expr bndr alts cont
1239 rebuild env expr (ApplyTo _ arg mb_se cont) = rebuildApp env expr arg mb_se cont
1241 rebuildApp env fun arg mb_se cont
1242 = do { arg' <- simplArg env arg mb_se
1243 ; rebuild env (App fun arg') cont }
1245 simplArg :: SimplEnv -> CoreExpr -> Maybe SimplEnv -> SimplM CoreExpr
1246 simplArg env arg Nothing = return arg -- The arg is already simplified
1247 simplArg env arg (Just arg_env) = simplExpr (setInScope arg_env env) arg
1249 rebuildDone env expr = returnSmpl (emptyFloats env, expr)
1253 %************************************************************************
1255 \subsection{Functions dealing with a case}
1257 %************************************************************************
1259 Blob of helper functions for the "case-of-something-else" situation.
1262 ---------------------------------------------------------
1263 -- Eliminate the case if possible
1265 rebuildCase :: SimplEnv
1266 -> OutExpr -- Scrutinee
1267 -> InId -- Case binder
1268 -> [InAlt] -- Alternatives (inceasing order)
1270 -> SimplM FloatsWithExpr
1272 rebuildCase env scrut case_bndr alts cont
1273 | Just (con,args) <- exprIsConApp_maybe scrut
1274 -- Works when the scrutinee is a variable with a known unfolding
1275 -- as well as when it's an explicit constructor application
1276 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1278 | Lit lit <- scrut -- No need for same treatment as constructors
1279 -- because literals are inlined more vigorously
1280 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1283 = -- Prepare the continuation;
1284 -- The new subst_env is in place
1285 prepareCaseCont env alts cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1286 addFloats env floats $ \ env ->
1289 -- The case expression is annotated with the result type of the continuation
1290 -- This may differ from the type originally on the case. For example
1291 -- case(T) (case(Int#) a of { True -> 1#; False -> 0# }) of
1294 -- let j a# = <blob>
1295 -- in case(T) a of { True -> j 1#; False -> j 0# }
1296 -- Note that the case that scrutinises a now returns a T not an Int#
1297 res_ty' = contResultType dup_cont
1300 -- Deal with case binder
1301 simplCaseBinder env scrut case_bndr `thenSmpl` \ (alt_env, case_bndr') ->
1303 -- Deal with the case alternatives
1304 simplAlts alt_env scrut case_bndr' alts dup_cont `thenSmpl` \ alts' ->
1306 -- Put the case back together
1307 mkCase scrut case_bndr' res_ty' alts' `thenSmpl` \ case_expr ->
1309 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1310 -- The case binder *not* scope over the whole returned case-expression
1311 rebuild env case_expr nondup_cont
1314 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1315 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1316 way, there's a chance that v will now only be used once, and hence
1321 There is a time we *don't* want to do that, namely when
1322 -fno-case-of-case is on. This happens in the first simplifier pass,
1323 and enhances full laziness. Here's the bad case:
1324 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1325 If we eliminate the inner case, we trap it inside the I# v -> arm,
1326 which might prevent some full laziness happening. I've seen this
1327 in action in spectral/cichelli/Prog.hs:
1328 [(m,n) | m <- [1..max], n <- [1..max]]
1329 Hence the check for NoCaseOfCase.
1333 There is another situation when we don't want to do it. If we have
1335 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1336 ...other cases .... }
1338 We'll perform the binder-swap for the outer case, giving
1340 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1341 ...other cases .... }
1343 But there is no point in doing it for the inner case, because w1 can't
1344 be inlined anyway. Furthermore, doing the case-swapping involves
1345 zapping w2's occurrence info (see paragraphs that follow), and that
1346 forces us to bind w2 when doing case merging. So we get
1348 case x of w1 { A -> let w2 = w1 in e1
1349 B -> let w2 = w1 in e2
1350 ...other cases .... }
1352 This is plain silly in the common case where w2 is dead.
1354 Even so, I can't see a good way to implement this idea. I tried
1355 not doing the binder-swap if the scrutinee was already evaluated
1356 but that failed big-time:
1360 case v of w { MkT x ->
1361 case x of x1 { I# y1 ->
1362 case x of x2 { I# y2 -> ...
1364 Notice that because MkT is strict, x is marked "evaluated". But to
1365 eliminate the last case, we must either make sure that x (as well as
1366 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1367 the binder-swap. So this whole note is a no-op.
1371 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1372 any occurrence info (eg IAmDead) in the case binder, because the
1373 case-binder now effectively occurs whenever v does. AND we have to do
1374 the same for the pattern-bound variables! Example:
1376 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1378 Here, b and p are dead. But when we move the argment inside the first
1379 case RHS, and eliminate the second case, we get
1381 case x of { (a,b) -> a b }
1383 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1386 Indeed, this can happen anytime the case binder isn't dead:
1387 case <any> of x { (a,b) ->
1388 case x of { (p,q) -> p } }
1389 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1390 The point is that we bring into the envt a binding
1392 after the outer case, and that makes (a,b) alive. At least we do unless
1393 the case binder is guaranteed dead.
1396 simplCaseBinder env (Var v) case_bndr
1397 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
1399 -- Failed try [see Note 2 above]
1400 -- not (isEvaldUnfolding (idUnfolding v))
1402 = simplBinder env (zap case_bndr) `thenSmpl` \ (env, case_bndr') ->
1403 returnSmpl (modifyInScope env v case_bndr', case_bndr')
1404 -- We could extend the substitution instead, but it would be
1405 -- a hack because then the substitution wouldn't be idempotent
1406 -- any more (v is an OutId). And this does just as well.
1408 zap b = b `setIdOccInfo` NoOccInfo
1410 simplCaseBinder env other_scrut case_bndr
1411 = simplBinder env case_bndr `thenSmpl` \ (env, case_bndr') ->
1412 returnSmpl (env, case_bndr')
1416 simplAlts does two things:
1418 1. Eliminate alternatives that cannot match, including the
1419 DEFAULT alternative.
1421 2. If the DEFAULT alternative can match only one possible constructor,
1422 then make that constructor explicit.
1424 case e of x { DEFAULT -> rhs }
1426 case e of x { (a,b) -> rhs }
1427 where the type is a single constructor type. This gives better code
1428 when rhs also scrutinises x or e.
1430 Here "cannot match" includes knowledge from GADTs
1432 It's a good idea do do this stuff before simplifying the alternatives, to
1433 avoid simplifying alternatives we know can't happen, and to come up with
1434 the list of constructors that are handled, to put into the IdInfo of the
1435 case binder, for use when simplifying the alternatives.
1437 Eliminating the default alternative in (1) isn't so obvious, but it can
1440 data Colour = Red | Green | Blue
1449 DEFAULT -> [ case y of ... ]
1451 If we inline h into f, the default case of the inlined h can't happen.
1452 If we don't notice this, we may end up filtering out *all* the cases
1453 of the inner case y, which give us nowhere to go!
1457 simplAlts :: SimplEnv
1459 -> OutId -- Case binder
1460 -> [InAlt] -> SimplCont
1461 -> SimplM [OutAlt] -- Includes the continuation
1463 simplAlts env scrut case_bndr' alts cont'
1464 = do { mb_alts <- mapSmpl (simplAlt env imposs_cons case_bndr' cont') alts_wo_default
1465 ; default_alts <- simplDefault env case_bndr' imposs_deflt_cons cont' maybe_deflt
1466 ; return (mergeAlts default_alts [alt' | Just (_, alt') <- mb_alts]) }
1467 -- We need the mergeAlts in case the new default_alt
1468 -- has turned into a constructor alternative.
1470 (alts_wo_default, maybe_deflt) = findDefault alts
1471 imposs_cons = case scrut of
1472 Var v -> otherCons (idUnfolding v)
1475 -- "imposs_deflt_cons" are handled either by the context,
1476 -- OR by a branch in this case expression. (Don't include DEFAULT!!)
1477 imposs_deflt_cons = nub (imposs_cons ++ [con | (con,_,_) <- alts_wo_default])
1479 simplDefault :: SimplEnv
1480 -> OutId -- Case binder; need just for its type. Note that as an
1481 -- OutId, it has maximum information; this is important.
1482 -- Test simpl013 is an example
1483 -> [AltCon] -- These cons can't happen when matching the default
1486 -> SimplM [OutAlt] -- One branch or none; we use a list because it's what
1487 -- mergeAlts expects
1490 simplDefault env case_bndr' imposs_cons cont Nothing
1491 = return [] -- No default branch
1492 simplDefault env case_bndr' imposs_cons cont (Just rhs)
1493 | -- This branch handles the case where we are
1494 -- scrutinisng an algebraic data type
1495 Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr'),
1496 isAlgTyCon tycon, -- It's a data type, tuple, or unboxed tuples.
1497 not (isNewTyCon tycon), -- We can have a newtype, if we are just doing an eval:
1498 -- case x of { DEFAULT -> e }
1499 -- and we don't want to fill in a default for them!
1500 Just all_cons <- tyConDataCons_maybe tycon,
1501 not (null all_cons), -- This is a tricky corner case. If the data type has no constructors,
1502 -- which GHC allows, then the case expression will have at most a default
1503 -- alternative. We don't want to eliminate that alternative, because the
1504 -- invariant is that there's always one alternative. It's more convenient
1506 -- case x of { DEFAULT -> e }
1507 -- as it is, rather than transform it to
1508 -- error "case cant match"
1509 -- which would be quite legitmate. But it's a really obscure corner, and
1510 -- not worth wasting code on.
1512 let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1513 poss_data_cons = filterOut (`elem` imposs_data_cons) all_cons
1514 gadt_imposs | all isTyVarTy inst_tys = []
1515 | otherwise = filter (cant_match inst_tys) poss_data_cons
1516 final_poss = filterOut (`elem` gadt_imposs) poss_data_cons
1518 = case final_poss of
1519 [] -> returnSmpl [] -- Eliminate the default alternative
1520 -- altogether if it can't match
1522 [con] -> -- It matches exactly one constructor, so fill it in
1523 do { con_alt <- mkDataConAlt case_bndr' con inst_tys rhs
1524 ; Just (_, alt') <- simplAlt env [] case_bndr' cont con_alt
1525 -- The simplAlt must succeed with Just because we have
1526 -- already filtered out construtors that can't match
1529 two_or_more -> simplify_default (map DataAlt gadt_imposs ++ imposs_cons)
1532 = simplify_default imposs_cons
1534 cant_match tys data_con = not (dataConCanMatch data_con tys)
1536 simplify_default imposs_cons
1537 = do { let env' = mk_rhs_env env case_bndr' (mkOtherCon imposs_cons)
1538 -- Record the constructors that the case-binder *can't* be.
1539 ; rhs' <- simplExprC env' rhs cont
1540 ; return [(DEFAULT, [], rhs')] }
1542 mkDataConAlt :: Id -> DataCon -> [OutType] -> InExpr -> SimplM InAlt
1543 -- Make a data-constructor alternative to replace the DEFAULT case
1544 -- NB: there's something a bit bogus here, because we put OutTypes into an InAlt
1545 mkDataConAlt case_bndr con tys rhs
1546 = do { tick (FillInCaseDefault case_bndr)
1547 ; args <- mk_args con tys
1548 ; return (DataAlt con, args, rhs) }
1550 mk_args con inst_tys
1551 = do { (tv_bndrs, inst_tys') <- mk_tv_bndrs con inst_tys
1552 ; let arg_tys = dataConInstArgTys con inst_tys'
1553 ; arg_ids <- mapM (newId FSLIT("a")) arg_tys
1554 ; returnSmpl (tv_bndrs ++ arg_ids) }
1556 mk_tv_bndrs con inst_tys
1557 | isVanillaDataCon con
1558 = return ([], inst_tys)
1560 = do { tv_uniqs <- getUniquesSmpl
1561 ; let new_tvs = zipWith mk tv_uniqs (dataConTyVars con)
1562 mk uniq tv = mkTyVar (mkSysTvName uniq FSLIT("t")) (tyVarKind tv)
1563 ; return (new_tvs, mkTyVarTys new_tvs) }
1565 simplAlt :: SimplEnv
1566 -> [AltCon] -- These constructors can't be present when
1567 -- matching this alternative
1568 -> OutId -- The case binder
1571 -> SimplM (Maybe (TvSubstEnv, OutAlt))
1573 -- Simplify an alternative, returning the type refinement for the
1574 -- alternative, if the alternative does any refinement at all
1575 -- Nothing => the alternative is inaccessible
1577 simplAlt env imposs_cons case_bndr' cont' (con, bndrs, rhs)
1578 | con `elem` imposs_cons -- This case can't match
1581 simplAlt env handled_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1582 -- TURGID DUPLICATION, needed only for the simplAlt call
1583 -- in mkDupableAlt. Clean this up when moving to FC
1584 = ASSERT( null bndrs )
1585 simplExprC env' rhs cont' `thenSmpl` \ rhs' ->
1586 returnSmpl (Just (emptyVarEnv, (DEFAULT, [], rhs')))
1588 env' = mk_rhs_env env case_bndr' (mkOtherCon handled_cons)
1589 -- Record the constructors that the case-binder *can't* be.
1591 simplAlt env handled_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1592 = ASSERT( null bndrs )
1593 simplExprC env' rhs cont' `thenSmpl` \ rhs' ->
1594 returnSmpl (Just (emptyVarEnv, (LitAlt lit, [], rhs')))
1596 env' = mk_rhs_env env case_bndr' (mkUnfolding False (Lit lit))
1598 simplAlt env handled_cons case_bndr' cont' (DataAlt con, vs, rhs)
1599 | isVanillaDataCon con
1600 = -- Deal with the pattern-bound variables
1601 -- Mark the ones that are in ! positions in the data constructor
1602 -- as certainly-evaluated.
1603 -- NB: it happens that simplBinders does *not* erase the OtherCon
1604 -- form of unfolding, so it's ok to add this info before
1605 -- doing simplBinders
1606 simplBinders env (add_evals con vs) `thenSmpl` \ (env, vs') ->
1608 -- Bind the case-binder to (con args)
1609 let unf = mkUnfolding False (mkConApp con con_args)
1610 inst_tys' = tyConAppArgs (idType case_bndr')
1611 con_args = map Type inst_tys' ++ map varToCoreExpr vs'
1612 env' = mk_rhs_env env case_bndr' unf
1614 simplExprC env' rhs cont' `thenSmpl` \ rhs' ->
1615 returnSmpl (Just (emptyVarEnv, (DataAlt con, vs', rhs')))
1617 | otherwise -- GADT case
1619 (tvs,ids) = span isTyVar vs
1621 simplBinders env tvs `thenSmpl` \ (env1, tvs') ->
1622 case coreRefineTys con tvs' (idType case_bndr') of {
1623 Nothing -- Inaccessible
1624 | opt_PprStyle_Debug -- Hack: if debugging is on, generate an error case
1626 -> let rhs' = mkApps (Var eRROR_ID)
1627 [Type (substTy env (exprType rhs)),
1628 Lit (mkStringLit "Impossible alternative (GADT)")]
1630 simplBinders env1 ids `thenSmpl` \ (env2, ids') ->
1631 returnSmpl (Just (emptyVarEnv, (DataAlt con, tvs' ++ ids', rhs')))
1633 | otherwise -- Filter out the inaccessible branch
1636 Just refine@(tv_subst_env, _) -> -- The normal case
1639 env2 = refineSimplEnv env1 refine
1640 -- Simplify the Ids in the refined environment, so their types
1641 -- reflect the refinement. Usually this doesn't matter, but it helps
1642 -- in mkDupableAlt, when we want to float a lambda that uses these binders
1643 -- Furthermore, it means the binders contain maximal type information
1645 simplBinders env2 (add_evals con ids) `thenSmpl` \ (env3, ids') ->
1646 let unf = mkUnfolding False con_app
1647 con_app = mkConApp con con_args
1648 con_args = map varToCoreExpr vs' -- NB: no inst_tys'
1649 env_w_unf = mk_rhs_env env3 case_bndr' unf
1652 simplExprC env_w_unf rhs cont' `thenSmpl` \ rhs' ->
1653 returnSmpl (Just (tv_subst_env, (DataAlt con, vs', rhs'))) }
1656 -- add_evals records the evaluated-ness of the bound variables of
1657 -- a case pattern. This is *important*. Consider
1658 -- data T = T !Int !Int
1660 -- case x of { T a b -> T (a+1) b }
1662 -- We really must record that b is already evaluated so that we don't
1663 -- go and re-evaluate it when constructing the result.
1664 add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1666 cat_evals dc vs strs
1670 go (v:vs) strs | isTyVar v = v : go vs strs
1671 go (v:vs) (str:strs)
1672 | isMarkedStrict str = evald_v : go vs strs
1673 | otherwise = zapped_v : go vs strs
1675 zapped_v = zap_occ_info v
1676 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1677 go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1679 -- If the case binder is alive, then we add the unfolding
1681 -- to the envt; so vs are now very much alive
1682 zap_occ_info | isDeadBinder case_bndr' = \id -> id
1683 | otherwise = \id -> id `setIdOccInfo` NoOccInfo
1685 mk_rhs_env env case_bndr' case_bndr_unf
1686 = modifyInScope env case_bndr' (case_bndr' `setIdUnfolding` case_bndr_unf)
1690 %************************************************************************
1692 \subsection{Known constructor}
1694 %************************************************************************
1696 We are a bit careful with occurrence info. Here's an example
1698 (\x* -> case x of (a*, b) -> f a) (h v, e)
1700 where the * means "occurs once". This effectively becomes
1701 case (h v, e) of (a*, b) -> f a)
1703 let a* = h v; b = e in f a
1707 All this should happen in one sweep.
1710 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1711 -> InId -> [InAlt] -> SimplCont
1712 -> SimplM FloatsWithExpr
1714 knownCon env scrut con args bndr alts cont
1715 = tick (KnownBranch bndr) `thenSmpl_`
1716 case findAlt con alts of
1717 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1718 simplNonRecX env bndr scrut $ \ env ->
1719 -- This might give rise to a binding with non-atomic args
1720 -- like x = Node (f x) (g x)
1721 -- but simplNonRecX will atomic-ify it
1722 simplExprF env rhs cont
1724 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1725 simplNonRecX env bndr scrut $ \ env ->
1726 simplExprF env rhs cont
1728 (DataAlt dc, bs, rhs)
1729 -> ASSERT( n_drop_tys + length bs == length args )
1730 bind_args env bs (drop n_drop_tys args) $ \ env ->
1732 -- It's useful to bind bndr to scrut, rather than to a fresh
1733 -- binding x = Con arg1 .. argn
1734 -- because very often the scrut is a variable, so we avoid
1735 -- creating, and then subsequently eliminating, a let-binding
1736 -- BUT, if scrut is a not a variable, we must be careful
1737 -- about duplicating the arg redexes; in that case, make
1738 -- a new con-app from the args
1739 bndr_rhs = case scrut of
1742 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1743 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1744 -- args are aready OutExprs, but bs are InIds
1746 simplNonRecX env bndr bndr_rhs $ \ env ->
1747 simplExprF env rhs cont
1749 n_drop_tys | isVanillaDataCon dc = tyConArity (dataConTyCon dc)
1751 -- Vanilla data constructors lack type arguments in the pattern
1754 bind_args env [] _ thing_inside = thing_inside env
1756 bind_args env (b:bs) (Type ty : args) thing_inside
1757 = ASSERT( isTyVar b )
1758 bind_args (extendTvSubst env b ty) bs args thing_inside
1760 bind_args env (b:bs) (arg : args) thing_inside
1761 -- Note that the binder might be "dead", because it doesn't occur in the RHS
1762 -- Nevertheless we bind it here, in case we need it for the con_app for the case_bndr
1764 simplNonRecX env b arg $ \ env ->
1765 bind_args env bs args thing_inside
1769 %************************************************************************
1771 \subsection{Duplicating continuations}
1773 %************************************************************************
1776 prepareCaseCont :: SimplEnv
1777 -> [InAlt] -> SimplCont
1778 -> SimplM (FloatsWith (SimplCont,SimplCont))
1779 -- Return a duplicatable continuation, a non-duplicable part
1780 -- plus some extra bindings (that scope over the entire
1783 -- No need to make it duplicatable if there's only one alternative
1784 prepareCaseCont env [alt] cont = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1785 prepareCaseCont env alts cont = mkDupableCont env cont
1789 mkDupableCont :: SimplEnv -> SimplCont
1790 -> SimplM (FloatsWith (SimplCont, SimplCont))
1792 mkDupableCont env cont
1793 | contIsDupable cont
1794 = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1796 mkDupableCont env (CoerceIt ty cont)
1797 = mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1798 returnSmpl (floats, (CoerceIt ty dup_cont, nondup_cont))
1800 mkDupableCont env cont@(ArgOf _ arg_ty _ _)
1801 = returnSmpl (emptyFloats env, (mkBoringStop arg_ty, cont))
1802 -- Do *not* duplicate an ArgOf continuation
1803 -- Because ArgOf continuations are opaque, we gain nothing by
1804 -- propagating them into the expressions, and we do lose a lot.
1805 -- Here's an example:
1806 -- && (case x of { T -> F; F -> T }) E
1807 -- Now, && is strict so we end up simplifying the case with
1808 -- an ArgOf continuation. If we let-bind it, we get
1810 -- let $j = \v -> && v E
1811 -- in simplExpr (case x of { T -> F; F -> T })
1812 -- (ArgOf (\r -> $j r)
1813 -- And after simplifying more we get
1815 -- let $j = \v -> && v E
1816 -- in case of { T -> $j F; F -> $j T }
1817 -- Which is a Very Bad Thing
1819 -- The desire not to duplicate is the entire reason that
1820 -- mkDupableCont returns a pair of continuations.
1822 -- The original plan had:
1823 -- e.g. (...strict-fn...) [...hole...]
1825 -- let $j = \a -> ...strict-fn...
1826 -- in $j [...hole...]
1828 mkDupableCont env (ApplyTo _ arg mb_se cont)
1829 = -- e.g. [...hole...] (...arg...)
1831 -- let a = ...arg...
1832 -- in [...hole...] a
1833 do { (floats, (dup_cont, nondup_cont)) <- mkDupableCont env cont
1834 ; addFloats env floats $ \ env -> do
1835 { arg1 <- simplArg env arg mb_se
1836 ; (floats2, arg2) <- mkDupableArg env arg1
1837 ; return (floats2, (ApplyTo OkToDup arg2 Nothing dup_cont, nondup_cont)) }}
1839 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1840 -- | not (exprIsDupable rhs && contIsDupable case_cont) -- See notes below
1841 -- | not (isDeadBinder case_bndr)
1842 | all isDeadBinder bs
1843 = returnSmpl (emptyFloats env, (mkBoringStop scrut_ty, cont))
1845 scrut_ty = substTy se (idType case_bndr)
1847 {- Note [Single-alternative cases]
1848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1849 This case is just like the ArgOf case. Here's an example:
1853 case (case x of I# x' ->
1855 True -> I# (negate# x')
1856 False -> I# x') of y {
1858 Because the (case x) has only one alternative, we'll transform to
1860 case (case x' <# 0# of
1861 True -> I# (negate# x')
1862 False -> I# x') of y {
1864 But now we do *NOT* want to make a join point etc, giving
1866 let $j = \y -> MkT y
1868 True -> $j (I# (negate# x'))
1870 In this case the $j will inline again, but suppose there was a big
1871 strict computation enclosing the orginal call to MkT. Then, it won't
1872 "see" the MkT any more, because it's big and won't get duplicated.
1873 And, what is worse, nothing was gained by the case-of-case transform.
1875 When should use this case of mkDupableCont?
1876 However, matching on *any* single-alternative case is a *disaster*;
1877 e.g. case (case ....) of (a,b) -> (# a,b #)
1878 We must push the outer case into the inner one!
1881 * Match [(DEFAULT,_,_)], but in the common case of Int,
1882 the alternative-filling-in code turned the outer case into
1883 case (...) of y { I# _ -> MkT y }
1885 * Match on single alternative plus (not (isDeadBinder case_bndr))
1886 Rationale: pushing the case inwards won't eliminate the construction.
1887 But there's a risk of
1888 case (...) of y { (a,b) -> let z=(a,b) in ... }
1889 Now y looks dead, but it'll come alive again. Still, this
1890 seems like the best option at the moment.
1892 * Match on single alternative plus (all (isDeadBinder bndrs))
1893 Rationale: this is essentially seq.
1895 * Match when the rhs is *not* duplicable, and hence would lead to a
1896 join point. This catches the disaster-case above. We can test
1897 the *un-simplified* rhs, which is fine. It might get bigger or
1898 smaller after simplification; if it gets smaller, this case might
1899 fire next time round. NB also that we must test contIsDupable
1900 case_cont *btoo, because case_cont might be big!
1902 HOWEVER: I found that this version doesn't work well, because
1903 we can get let x = case (...) of { small } in ...case x...
1904 When x is inlined into its full context, we find that it was a bad
1905 idea to have pushed the outer case inside the (...) case.
1908 mkDupableCont env (Select _ case_bndr alts se cont)
1909 = -- e.g. (case [...hole...] of { pi -> ei })
1911 -- let ji = \xij -> ei
1912 -- in case [...hole...] of { pi -> ji xij }
1913 do { tick (CaseOfCase case_bndr)
1914 ; let alt_env = setInScope se env
1915 ; (floats1, (dup_cont, nondup_cont)) <- mkDupableCont alt_env cont
1916 -- NB: call mkDupableCont here, *not* prepareCaseCont
1917 -- We must make a duplicable continuation, whereas prepareCaseCont
1918 -- doesn't when there is a single case branch
1919 ; addFloats alt_env floats1 $ \ alt_env -> do
1921 { (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1922 -- NB: simplBinder does not zap deadness occ-info, so
1923 -- a dead case_bndr' will still advertise its deadness
1924 -- This is really important because in
1925 -- case e of b { (# a,b #) -> ... }
1926 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1927 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1928 -- In the new alts we build, we have the new case binder, so it must retain
1931 ; (floats2, alts') <- mkDupableAlts alt_env case_bndr' alts dup_cont
1932 ; return (floats2, (Select OkToDup case_bndr' alts' (zapSubstEnv se)
1933 (mkBoringStop (contResultType dup_cont)),
1937 mkDupableArg :: SimplEnv -> OutExpr -> SimplM (FloatsWith OutExpr)
1938 -- Let-bind the thing if necessary
1939 mkDupableArg env arg
1941 = return (emptyFloats env, arg)
1943 = do { arg_id <- newId FSLIT("a") (exprType arg)
1944 ; tick (CaseOfCase arg_id)
1945 -- Want to tick here so that we go round again,
1946 -- and maybe copy or inline the code.
1947 -- Not strictly CaseOfCase, but never mind
1948 ; return (unitFloat env arg_id arg, Var arg_id) }
1949 -- What if the arg should be case-bound?
1950 -- This has been this way for a long time, so I'll leave it,
1951 -- but I can't convince myself that it's right.
1953 mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplCont
1954 -> SimplM (FloatsWith [InAlt])
1955 -- Absorbs the continuation into the new alternatives
1957 mkDupableAlts env case_bndr' alts dupable_cont
1960 go env [] = returnSmpl (emptyFloats env, [])
1962 = do { (floats1, mb_alt') <- mkDupableAlt env case_bndr' dupable_cont alt
1963 ; addFloats env floats1 $ \ env -> do
1964 { (floats2, alts') <- go env alts
1965 ; returnSmpl (floats2, case mb_alt' of
1966 Just alt' -> alt' : alts'
1970 mkDupableAlt env case_bndr' cont alt
1971 = simplAlt env [] case_bndr' cont alt `thenSmpl` \ mb_stuff ->
1973 Nothing -> returnSmpl (emptyFloats env, Nothing) ;
1975 Just (reft, (con, bndrs', rhs')) ->
1976 -- Safe to say that there are no handled-cons for the DEFAULT case
1978 if exprIsDupable rhs' then
1979 returnSmpl (emptyFloats env, Just (con, bndrs', rhs'))
1980 -- It is worth checking for a small RHS because otherwise we
1981 -- get extra let bindings that may cause an extra iteration of the simplifier to
1982 -- inline back in place. Quite often the rhs is just a variable or constructor.
1983 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1984 -- iterations because the version with the let bindings looked big, and so wasn't
1985 -- inlined, but after the join points had been inlined it looked smaller, and so
1988 -- NB: we have to check the size of rhs', not rhs.
1989 -- Duplicating a small InAlt might invalidate occurrence information
1990 -- However, if it *is* dupable, we return the *un* simplified alternative,
1991 -- because otherwise we'd need to pair it up with an empty subst-env....
1992 -- but we only have one env shared between all the alts.
1993 -- (Remember we must zap the subst-env before re-simplifying something).
1994 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1998 rhs_ty' = exprType rhs'
1999 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
2001 | isTyVar bndr = not (bndr `elemVarEnv` reft)
2002 -- Don't abstract over tyvar binders which are refined away
2003 -- See Note [Refinement] below
2004 | otherwise = not (isDeadBinder bndr)
2005 -- The deadness info on the new Ids is preserved by simplBinders
2007 -- If we try to lift a primitive-typed something out
2008 -- for let-binding-purposes, we will *caseify* it (!),
2009 -- with potentially-disastrous strictness results. So
2010 -- instead we turn it into a function: \v -> e
2011 -- where v::State# RealWorld#. The value passed to this function
2012 -- is realworld#, which generates (almost) no code.
2014 -- There's a slight infelicity here: we pass the overall
2015 -- case_bndr to all the join points if it's used in *any* RHS,
2016 -- because we don't know its usage in each RHS separately
2018 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
2019 -- we make the join point into a function whenever used_bndrs'
2020 -- is empty. This makes the join-point more CPR friendly.
2021 -- Consider: let j = if .. then I# 3 else I# 4
2022 -- in case .. of { A -> j; B -> j; C -> ... }
2024 -- Now CPR doesn't w/w j because it's a thunk, so
2025 -- that means that the enclosing function can't w/w either,
2026 -- which is a lose. Here's the example that happened in practice:
2027 -- kgmod :: Int -> Int -> Int
2028 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2032 -- I have seen a case alternative like this:
2033 -- True -> \v -> ...
2034 -- It's a bit silly to add the realWorld dummy arg in this case, making
2037 -- (the \v alone is enough to make CPR happy) but I think it's rare
2039 ( if not (any isId used_bndrs')
2040 then newId FSLIT("w") realWorldStatePrimTy `thenSmpl` \ rw_id ->
2041 returnSmpl ([rw_id], [Var realWorldPrimId])
2043 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs')
2044 ) `thenSmpl` \ (final_bndrs', final_args) ->
2046 -- See comment about "$j" name above
2047 newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty') `thenSmpl` \ join_bndr ->
2048 -- Notice the funky mkPiTypes. If the contructor has existentials
2049 -- it's possible that the join point will be abstracted over
2050 -- type varaibles as well as term variables.
2051 -- Example: Suppose we have
2052 -- data T = forall t. C [t]
2054 -- case (case e of ...) of
2055 -- C t xs::[t] -> rhs
2056 -- We get the join point
2057 -- let j :: forall t. [t] -> ...
2058 -- j = /\t \xs::[t] -> rhs
2060 -- case (case e of ...) of
2061 -- C t xs::[t] -> j t xs
2063 -- We make the lambdas into one-shot-lambdas. The
2064 -- join point is sure to be applied at most once, and doing so
2065 -- prevents the body of the join point being floated out by
2066 -- the full laziness pass
2067 really_final_bndrs = map one_shot final_bndrs'
2068 one_shot v | isId v = setOneShotLambda v
2070 join_rhs = mkLams really_final_bndrs rhs'
2071 join_call = mkApps (Var join_bndr) final_args
2073 returnSmpl (unitFloat env join_bndr join_rhs, Just (con, bndrs', join_call)) }
2080 MkT :: a -> b -> T a
2084 MkT a' b (p::a') (q::b) -> [p,w]
2086 The danger is that we'll make a join point
2090 and that's ill-typed, because (p::a') but (w::a).
2092 Solution so far: don't abstract over a', because the type refinement
2093 maps [a' -> a] . Ultimately that won't work when real refinement goes on.
2095 Then we must abstract over any refined free variables. Hmm. Maybe we
2096 could just abstract over *all* free variables, thereby lambda-lifting
2097 the join point? We should try this.