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 IdInfo ( OccInfo(..), isLoopBreaker,
30 setArityInfo, zapDemandInfo,
34 import NewDemand ( isStrictDmd )
35 import TcGadt ( dataConCanMatch )
36 import DataCon ( dataConTyCon, dataConRepStrictness )
37 import TyCon ( tyConArity, isAlgTyCon, isNewTyCon, tyConDataCons_maybe )
39 import PprCore ( pprParendExpr, pprCoreExpr )
40 import CoreUnfold ( mkUnfolding, callSiteInline )
41 import CoreUtils ( exprIsDupable, exprIsTrivial, needsCaseBinding,
42 exprIsConApp_maybe, mkPiTypes, findAlt,
43 exprType, exprIsHNF, findDefault, mergeAlts,
44 exprOkForSpeculation, exprArity,
45 mkCoerce, mkSCC, mkInlineMe, applyTypeToArg,
48 import Rules ( lookupRule )
49 import BasicTypes ( isMarkedStrict )
50 import CostCentre ( currentCCS )
51 import Type ( TvSubstEnv, isUnLiftedType, seqType, tyConAppArgs, funArgTy,
52 coreEqType, splitTyConApp_maybe,
53 isTyVarTy, isFunTy, tcEqType
55 import Coercion ( Coercion, coercionKind,
56 mkTransCoercion, mkSymCoercion, splitCoercionKind_maybe, decomposeCo )
57 import VarEnv ( elemVarEnv, emptyVarEnv )
58 import TysPrim ( realWorldStatePrimTy )
59 import PrelInfo ( realWorldPrimId )
60 import BasicTypes ( TopLevelFlag(..), isTopLevel,
65 import Maybes ( orElse )
67 import Util ( notNull, filterOut )
71 The guts of the simplifier is in this module, but the driver loop for
72 the simplifier is in SimplCore.lhs.
75 -----------------------------------------
76 *** IMPORTANT NOTE ***
77 -----------------------------------------
78 The simplifier used to guarantee that the output had no shadowing, but
79 it does not do so any more. (Actually, it never did!) The reason is
80 documented with simplifyArgs.
83 -----------------------------------------
84 *** IMPORTANT NOTE ***
85 -----------------------------------------
86 Many parts of the simplifier return a bunch of "floats" as well as an
87 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
89 All "floats" are let-binds, not case-binds, but some non-rec lets may
90 be unlifted (with RHS ok-for-speculation).
94 -----------------------------------------
95 ORGANISATION OF FUNCTIONS
96 -----------------------------------------
98 - simplify all top-level binders
99 - for NonRec, call simplRecOrTopPair
100 - for Rec, call simplRecBind
103 ------------------------------
104 simplExpr (applied lambda) ==> simplNonRecBind
105 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
106 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
108 ------------------------------
109 simplRecBind [binders already simplfied]
110 - use simplRecOrTopPair on each pair in turn
112 simplRecOrTopPair [binder already simplified]
113 Used for: recursive bindings (top level and nested)
114 top-level non-recursive bindings
116 - check for PreInlineUnconditionally
120 Used for: non-top-level non-recursive bindings
121 beta reductions (which amount to the same thing)
122 Because it can deal with strict arts, it takes a
123 "thing-inside" and returns an expression
125 - check for PreInlineUnconditionally
126 - simplify binder, including its IdInfo
135 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
136 Used for: binding case-binder and constr args in a known-constructor case
137 - check for PreInLineUnconditionally
141 ------------------------------
142 simplLazyBind: [binder already simplified, RHS not]
143 Used for: recursive bindings (top level and nested)
144 top-level non-recursive bindings
145 non-top-level, but *lazy* non-recursive bindings
146 [must not be strict or unboxed]
147 Returns floats + an augmented environment, not an expression
148 - substituteIdInfo and add result to in-scope
149 [so that rules are available in rec rhs]
152 - float if exposes constructor or PAP
156 completeNonRecX: [binder and rhs both simplified]
157 - if the the thing needs case binding (unlifted and not ok-for-spec)
163 completeLazyBind: [given a simplified RHS]
164 [used for both rec and non-rec bindings, top level and not]
165 - try PostInlineUnconditionally
166 - add unfolding [this is the only place we add an unfolding]
171 Right hand sides and arguments
172 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173 In many ways we want to treat
174 (a) the right hand side of a let(rec), and
175 (b) a function argument
176 in the same way. But not always! In particular, we would
177 like to leave these arguments exactly as they are, so they
178 will match a RULE more easily.
183 It's harder to make the rule match if we ANF-ise the constructor,
184 or eta-expand the PAP:
186 f (let { a = g x; b = h x } in (a,b))
189 On the other hand if we see the let-defns
194 then we *do* want to ANF-ise and eta-expand, so that p and q
195 can be safely inlined.
197 Even floating lets out is a bit dubious. For let RHS's we float lets
198 out if that exposes a value, so that the value can be inlined more vigorously.
201 r = let x = e in (x,x)
203 Here, if we float the let out we'll expose a nice constructor. We did experiments
204 that showed this to be a generally good thing. But it was a bad thing to float
205 lets out unconditionally, because that meant they got allocated more often.
207 For function arguments, there's less reason to expose a constructor (it won't
208 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
209 So for the moment we don't float lets out of function arguments either.
214 For eta expansion, we want to catch things like
216 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
218 If the \x was on the RHS of a let, we'd eta expand to bring the two
219 lambdas together. And in general that's a good thing to do. Perhaps
220 we should eta expand wherever we find a (value) lambda? Then the eta
221 expansion at a let RHS can concentrate solely on the PAP case.
224 %************************************************************************
226 \subsection{Bindings}
228 %************************************************************************
231 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
233 simplTopBinds env binds
234 = -- Put all the top-level binders into scope at the start
235 -- so that if a transformation rule has unexpectedly brought
236 -- anything into scope, then we don't get a complaint about that.
237 -- It's rather as if the top-level binders were imported.
238 simplRecBndrs env (bindersOfBinds binds) `thenSmpl` \ (env, bndrs') ->
239 simpl_binds env binds bndrs' `thenSmpl` \ (floats, _) ->
240 freeTick SimplifierDone `thenSmpl_`
241 returnSmpl (floatBinds floats)
243 -- We need to track the zapped top-level binders, because
244 -- they should have their fragile IdInfo zapped (notably occurrence info)
245 -- That's why we run down binds and bndrs' simultaneously.
246 simpl_binds :: SimplEnv -> [InBind] -> [OutId] -> SimplM (FloatsWith ())
247 simpl_binds env [] bs = ASSERT( null bs ) returnSmpl (emptyFloats env, ())
248 simpl_binds env (bind:binds) bs = simpl_bind env bind bs `thenSmpl` \ (floats,env) ->
249 addFloats env floats $ \env ->
250 simpl_binds env binds (drop_bs bind bs)
252 drop_bs (NonRec _ _) (_ : bs) = bs
253 drop_bs (Rec prs) bs = drop (length prs) bs
255 simpl_bind env bind bs
256 = getDOptsSmpl `thenSmpl` \ dflags ->
257 if dopt Opt_D_dump_inlinings dflags then
258 pprTrace "SimplBind" (ppr (bindersOf bind)) $ simpl_bind1 env bind bs
260 simpl_bind1 env bind bs
262 simpl_bind1 env (NonRec b r) (b':_) = simplRecOrTopPair env TopLevel b b' r
263 simpl_bind1 env (Rec pairs) bs' = simplRecBind env TopLevel pairs bs'
267 %************************************************************************
269 \subsection{simplNonRec}
271 %************************************************************************
273 simplNonRecBind is used for
274 * non-top-level non-recursive lets in expressions
278 * An unsimplified (binder, rhs) pair
279 * The env for the RHS. It may not be the same as the
280 current env because the bind might occur via (\x.E) arg
282 It uses the CPS form because the binding might be strict, in which
283 case we might discard the continuation:
284 let x* = error "foo" in (...x...)
286 It needs to turn unlifted bindings into a @case@. They can arise
287 from, say: (\x -> e) (4# + 3#)
290 simplNonRecBind :: SimplEnv
292 -> InExpr -> SimplEnv -- Arg, with its subst-env
293 -> OutType -- Type of thing computed by the context
294 -> (SimplEnv -> SimplM FloatsWithExpr) -- The body
295 -> SimplM FloatsWithExpr
297 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
299 = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
302 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
303 = simplNonRecBind' env bndr rhs rhs_se cont_ty thing_inside
305 simplNonRecBind' env bndr rhs rhs_se cont_ty thing_inside
306 | preInlineUnconditionally env NotTopLevel bndr rhs
307 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
308 thing_inside (extendIdSubst env bndr (mkContEx rhs_se rhs))
310 | isStrictDmd (idNewDemandInfo bndr) || isStrictType bndr_ty -- A strict let
311 = -- Don't use simplBinder because that doesn't keep
312 -- fragile occurrence info in the substitution
313 simplNonRecBndr env bndr `thenSmpl` \ (env, bndr1) ->
314 simplStrictArg AnRhs env rhs rhs_se (idType bndr1) cont_ty $ \ env1 rhs1 ->
316 -- Now complete the binding and simplify the body
318 (env2,bndr2) = addLetIdInfo env1 bndr bndr1
320 completeNonRecX env2 True {- strict -} bndr bndr2 rhs1 thing_inside
322 | otherwise -- Normal, lazy case
323 = -- Don't use simplBinder because that doesn't keep
324 -- fragile occurrence info in the substitution
325 simplNonRecBndr env bndr `thenSmpl` \ (env, bndr') ->
326 simplLazyBind env NotTopLevel NonRecursive
327 bndr bndr' rhs rhs_se `thenSmpl` \ (floats, env) ->
328 addFloats env floats thing_inside
331 bndr_ty = idType bndr
334 A specialised variant of simplNonRec used when the RHS is already simplified, notably
335 in knownCon. It uses case-binding where necessary.
338 simplNonRecX :: SimplEnv
339 -> InId -- Old binder
340 -> OutExpr -- Simplified RHS
341 -> (SimplEnv -> SimplM FloatsWithExpr)
342 -> SimplM FloatsWithExpr
344 simplNonRecX env bndr new_rhs thing_inside
345 = do { (env, bndr') <- simplBinder env bndr
346 ; completeNonRecX env False {- Non-strict; pessimistic -}
347 bndr bndr' new_rhs thing_inside }
350 completeNonRecX :: SimplEnv
351 -> Bool -- Strict binding
352 -> InId -- Old binder
353 -> OutId -- New binder
354 -> OutExpr -- Simplified RHS
355 -> (SimplEnv -> SimplM FloatsWithExpr)
356 -> SimplM FloatsWithExpr
358 completeNonRecX env is_strict old_bndr new_bndr new_rhs thing_inside
359 | needsCaseBinding (idType new_bndr) new_rhs
360 -- Make this test *before* the preInlineUnconditionally
361 -- Consider case I# (quotInt# x y) of
362 -- I# v -> let w = J# v in ...
363 -- If we gaily inline (quotInt# x y) for v, we end up building an
365 -- let w = J# (quotInt# x y) in ...
366 -- because quotInt# can fail.
367 = do { (floats, body) <- thing_inside env
368 ; let body' = wrapFloats floats body
369 ; return (emptyFloats env, Case new_rhs new_bndr (exprType body)
370 [(DEFAULT, [], body')]) }
373 = -- Make the arguments atomic if necessary,
374 -- adding suitable bindings
375 -- pprTrace "completeNonRecX" (ppr new_bndr <+> ppr new_rhs) $
376 mkAtomicArgsE env is_strict new_rhs $ \ env new_rhs ->
377 completeLazyBind env NotTopLevel
378 old_bndr new_bndr new_rhs `thenSmpl` \ (floats, env) ->
379 addFloats env floats thing_inside
381 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
382 Doing so risks exponential behaviour, because new_rhs has been simplified once already
383 In the cases described by the folowing commment, postInlineUnconditionally will
384 catch many of the relevant cases.
385 -- This happens; for example, the case_bndr during case of
386 -- known constructor: case (a,b) of x { (p,q) -> ... }
387 -- Here x isn't mentioned in the RHS, so we don't want to
388 -- create the (dead) let-binding let x = (a,b) in ...
390 -- Similarly, single occurrences can be inlined vigourously
391 -- e.g. case (f x, g y) of (a,b) -> ....
392 -- If a,b occur once we can avoid constructing the let binding for them.
393 | preInlineUnconditionally env NotTopLevel bndr new_rhs
394 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
396 -- NB: completeLazyBind uses postInlineUnconditionally; no need to do that here
401 %************************************************************************
403 \subsection{Lazy bindings}
405 %************************************************************************
407 simplRecBind is used for
408 * recursive bindings only
411 simplRecBind :: SimplEnv -> TopLevelFlag
412 -> [(InId, InExpr)] -> [OutId]
413 -> SimplM (FloatsWith SimplEnv)
414 simplRecBind env top_lvl pairs bndrs'
415 = go env pairs bndrs' `thenSmpl` \ (floats, env) ->
416 returnSmpl (flattenFloats floats, env)
418 go env [] _ = returnSmpl (emptyFloats env, env)
420 go env ((bndr, rhs) : pairs) (bndr' : bndrs')
421 = simplRecOrTopPair env top_lvl bndr bndr' rhs `thenSmpl` \ (floats, env) ->
422 addFloats env floats (\env -> go env pairs bndrs')
426 simplRecOrTopPair is used for
427 * recursive bindings (whether top level or not)
428 * top-level non-recursive bindings
430 It assumes the binder has already been simplified, but not its IdInfo.
433 simplRecOrTopPair :: SimplEnv
435 -> InId -> OutId -- Binder, both pre-and post simpl
436 -> InExpr -- The RHS and its environment
437 -> SimplM (FloatsWith SimplEnv)
439 simplRecOrTopPair env top_lvl bndr bndr' rhs
440 | preInlineUnconditionally env top_lvl bndr rhs -- Check for unconditional inline
441 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
442 returnSmpl (emptyFloats env, extendIdSubst env bndr (mkContEx env rhs))
445 = simplLazyBind env top_lvl Recursive bndr bndr' rhs env
446 -- May not actually be recursive, but it doesn't matter
450 simplLazyBind is used for
451 * recursive bindings (whether top level or not)
452 * top-level non-recursive bindings
453 * non-top-level *lazy* non-recursive bindings
455 [Thus it deals with the lazy cases from simplNonRecBind, and all cases
456 from SimplRecOrTopBind]
459 1. It assumes that the binder is *already* simplified,
460 and is in scope, but not its IdInfo
462 2. It assumes that the binder type is lifted.
464 3. It does not check for pre-inline-unconditionallly;
465 that should have been done already.
468 simplLazyBind :: SimplEnv
469 -> TopLevelFlag -> RecFlag
470 -> InId -> OutId -- Binder, both pre-and post simpl
471 -> InExpr -> SimplEnv -- The RHS and its environment
472 -> SimplM (FloatsWith SimplEnv)
474 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
476 (env1,bndr2) = addLetIdInfo env bndr bndr1
477 rhs_env = setInScope rhs_se env1
478 is_top_level = isTopLevel top_lvl
479 ok_float_unlifted = not is_top_level && isNonRec is_rec
480 rhs_cont = mkRhsStop (idType bndr2)
482 -- Simplify the RHS; note the mkRhsStop, which tells
483 -- the simplifier that this is the RHS of a let.
484 simplExprF rhs_env rhs rhs_cont `thenSmpl` \ (floats, rhs1) ->
486 -- If any of the floats can't be floated, give up now
487 -- (The allLifted predicate says True for empty floats.)
488 if (not ok_float_unlifted && not (allLifted floats)) then
489 completeLazyBind env1 top_lvl bndr bndr2
490 (wrapFloats floats rhs1)
493 -- ANF-ise a constructor or PAP rhs
494 mkAtomicArgs False {- Not strict -}
495 ok_float_unlifted rhs1 `thenSmpl` \ (aux_binds, rhs2) ->
497 -- If the result is a PAP, float the floats out, else wrap them
498 -- By this time it's already been ANF-ised (if necessary)
499 if isEmptyFloats floats && isNilOL aux_binds then -- Shortcut a common case
500 completeLazyBind env1 top_lvl bndr bndr2 rhs2
502 else if is_top_level || exprIsTrivial rhs2 || exprIsHNF rhs2 then
503 -- WARNING: long dodgy argument coming up
504 -- WANTED: a better way to do this
506 -- We can't use "exprIsCheap" instead of exprIsHNF,
507 -- because that causes a strictness bug.
508 -- x = let y* = E in case (scc y) of { T -> F; F -> T}
509 -- The case expression is 'cheap', but it's wrong to transform to
510 -- y* = E; x = case (scc y) of {...}
511 -- Either we must be careful not to float demanded non-values, or
512 -- we must use exprIsHNF for the test, which ensures that the
513 -- thing is non-strict. So exprIsHNF => bindings are non-strict
514 -- I think. The WARN below tests for this.
516 -- We use exprIsTrivial here because we want to reveal lone variables.
517 -- E.g. let { x = letrec { y = E } in y } in ...
518 -- Here we definitely want to float the y=E defn.
519 -- exprIsHNF definitely isn't right for that.
521 -- Again, the floated binding can't be strict; if it's recursive it'll
522 -- be non-strict; if it's non-recursive it'd be inlined.
524 -- Note [SCC-and-exprIsTrivial]
526 -- y = let { x* = E } in scc "foo" x
527 -- then we do *not* want to float out the x binding, because
528 -- it's strict! Fortunately, exprIsTrivial replies False to
531 -- There's a subtlety here. There may be a binding (x* = e) in the
532 -- floats, where the '*' means 'will be demanded'. So is it safe
533 -- to float it out? Answer no, but it won't matter because
534 -- we only float if (a) arg' is a WHNF, or (b) it's going to top level
535 -- and so there can't be any 'will be demanded' bindings in the floats.
537 WARN( not (is_top_level || not (any demanded_float (floatBinds floats))),
538 ppr (filter demanded_float (floatBinds floats)) )
540 tick LetFloatFromLet `thenSmpl_` (
541 addFloats env1 floats $ \ env2 ->
542 addAtomicBinds env2 (fromOL aux_binds) $ \ env3 ->
543 completeLazyBind env3 top_lvl bndr bndr2 rhs2)
546 completeLazyBind env1 top_lvl bndr bndr2 (wrapFloats floats rhs1)
549 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
550 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
551 demanded_float (Rec _) = False
556 %************************************************************************
558 \subsection{Completing a lazy binding}
560 %************************************************************************
563 * deals only with Ids, not TyVars
564 * takes an already-simplified binder and RHS
565 * is used for both recursive and non-recursive bindings
566 * is used for both top-level and non-top-level bindings
568 It does the following:
569 - tries discarding a dead binding
570 - tries PostInlineUnconditionally
571 - add unfolding [this is the only place we add an unfolding]
574 It does *not* attempt to do let-to-case. Why? Because it is used for
575 - top-level bindings (when let-to-case is impossible)
576 - many situations where the "rhs" is known to be a WHNF
577 (so let-to-case is inappropriate).
580 completeLazyBind :: SimplEnv
581 -> TopLevelFlag -- Flag stuck into unfolding
582 -> InId -- Old binder
583 -> OutId -- New binder
584 -> OutExpr -- Simplified RHS
585 -> SimplM (FloatsWith SimplEnv)
586 -- We return a new SimplEnv, because completeLazyBind may choose to do its work
587 -- by extending the substitution (e.g. let x = y in ...)
588 -- The new binding (if any) is returned as part of the floats.
589 -- NB: the returned SimplEnv has the right SubstEnv, but you should
590 -- (as usual) use the in-scope-env from the floats
592 completeLazyBind env top_lvl old_bndr new_bndr new_rhs
593 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
594 = -- Drop the binding
595 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
596 -- pprTrace "Inline unconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
597 returnSmpl (emptyFloats env, extendIdSubst env old_bndr (DoneEx new_rhs))
598 -- Use the substitution to make quite, quite sure that the substitution
599 -- will happen, since we are going to discard the binding
604 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
606 -- Add the unfolding *only* for non-loop-breakers
607 -- Making loop breakers not have an unfolding at all
608 -- means that we can avoid tests in exprIsConApp, for example.
609 -- This is important: if exprIsConApp says 'yes' for a recursive
610 -- thing, then we can get into an infinite loop
611 -- If the unfolding is a value, the demand info may
612 -- go pear-shaped, so we nuke it. Example:
614 -- case x of (p,q) -> h p q x
615 -- Here x is certainly demanded. But after we've nuked
616 -- the case, we'll get just
617 -- let x = (a,b) in h a b x
618 -- and now x is not demanded (I'm assuming h is lazy)
619 -- This really happens. Similarly
620 -- let f = \x -> e in ...f..f...
621 -- After inling f at some of its call sites the original binding may
622 -- (for example) be no longer strictly demanded.
623 -- The solution here is a bit ad hoc...
624 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
625 final_info | loop_breaker = new_bndr_info
626 | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
627 | otherwise = info_w_unf
629 final_id = new_bndr `setIdInfo` final_info
631 -- These seqs forces the Id, and hence its IdInfo,
632 -- and hence any inner substitutions
634 -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
635 returnSmpl (unitFloat env final_id new_rhs, env)
637 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
638 loop_breaker = isLoopBreaker occ_info
639 old_info = idInfo old_bndr
640 occ_info = occInfo old_info
645 %************************************************************************
647 \subsection[Simplify-simplExpr]{The main function: simplExpr}
649 %************************************************************************
651 The reason for this OutExprStuff stuff is that we want to float *after*
652 simplifying a RHS, not before. If we do so naively we get quadratic
653 behaviour as things float out.
655 To see why it's important to do it after, consider this (real) example:
669 a -- Can't inline a this round, cos it appears twice
673 Each of the ==> steps is a round of simplification. We'd save a
674 whole round if we float first. This can cascade. Consider
679 let f = let d1 = ..d.. in \y -> e
683 in \x -> ...(\y ->e)...
685 Only in this second round can the \y be applied, and it
686 might do the same again.
690 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
691 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
693 expr_ty' = substTy env (exprType expr)
694 -- The type in the Stop continuation, expr_ty', is usually not used
695 -- It's only needed when discarding continuations after finding
696 -- a function that returns bottom.
697 -- Hence the lazy substitution
700 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
701 -- Simplify an expression, given a continuation
702 simplExprC env expr cont
703 = simplExprF env expr cont `thenSmpl` \ (floats, expr) ->
704 returnSmpl (wrapFloats floats expr)
706 simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM FloatsWithExpr
707 -- Simplify an expression, returning floated binds
709 simplExprF env (Var v) cont = simplVar env v cont
710 simplExprF env (Lit lit) cont = rebuild env (Lit lit) cont
711 simplExprF env expr@(Lam _ _) cont = simplLam env expr cont
712 simplExprF env (Note note expr) cont = simplNote env note expr cont
713 simplExprF env (Cast body co) cont = simplCast env body co cont
714 simplExprF env (App fun arg) cont = simplExprF env fun
715 (ApplyTo NoDup arg (Just env) cont)
717 simplExprF env (Type ty) cont
718 = ASSERT( contIsRhsOrArg cont )
719 simplType env ty `thenSmpl` \ ty' ->
720 rebuild env (Type ty') cont
722 simplExprF env (Case scrut bndr case_ty alts) cont
723 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
724 = -- Simplify the scrutinee with a Select continuation
725 simplExprF env scrut (Select NoDup bndr alts env cont)
728 = -- If case-of-case is off, simply simplify the case expression
729 -- in a vanilla Stop context, and rebuild the result around it
730 simplExprC env scrut case_cont `thenSmpl` \ case_expr' ->
731 rebuild env case_expr' cont
733 case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
734 case_ty' = substTy env case_ty -- c.f. defn of simplExpr
736 simplExprF env (Let (Rec pairs) body) cont
737 = simplRecBndrs env (map fst pairs) `thenSmpl` \ (env, bndrs') ->
738 -- NB: bndrs' don't have unfoldings or rules
739 -- We add them as we go down
741 simplRecBind env NotTopLevel pairs bndrs' `thenSmpl` \ (floats, env) ->
742 addFloats env floats $ \ env ->
743 simplExprF env body cont
745 -- A non-recursive let is dealt with by simplNonRecBind
746 simplExprF env (Let (NonRec bndr rhs) body) cont
747 = simplNonRecBind env bndr rhs env (contResultType cont) $ \ env ->
748 simplExprF env body cont
751 ---------------------------------
752 simplType :: SimplEnv -> InType -> SimplM OutType
753 -- Kept monadic just so we can do the seqType
755 = seqType new_ty `seq` returnSmpl new_ty
757 new_ty = substTy env ty
761 %************************************************************************
765 %************************************************************************
768 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont -> SimplM FloatsWithExpr
769 simplCast env body co cont
772 | (s1, k1) <- coercionKind co
773 , s1 `tcEqType` k1 = cont
774 addCoerce co1 (CoerceIt co2 cont)
775 | (s1, k1) <- coercionKind co1
776 , (l1, t1) <- coercionKind co2
777 -- coerce T1 S1 (coerce S1 K1 e)
780 -- coerce T1 K1 e, otherwise
782 -- For example, in the initial form of a worker
783 -- we may find (coerce T (coerce S (\x.e))) y
784 -- and we'd like it to simplify to e[y/x] in one round
786 , s1 `coreEqType` t1 = cont -- The coerces cancel out
787 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
789 addCoerce co (ApplyTo dup arg arg_se cont)
790 | not (isTypeArg arg) -- This whole case only works for value args
791 -- Could upgrade to have equiv thing for type apps too
792 , Just (s1s2, t1t2) <- splitCoercionKind_maybe co
794 -- co : s1s2 :=: t1t2
795 -- (coerce (T1->T2) (S1->S2) F) E
797 -- coerce T2 S2 (F (coerce S1 T1 E))
799 -- t1t2 must be a function type, T1->T2, because it's applied
800 -- to something but s1s2 might conceivably not be
802 -- When we build the ApplyTo we can't mix the out-types
803 -- with the InExpr in the argument, so we simply substitute
804 -- to make it all consistent. It's a bit messy.
805 -- But it isn't a common case.
808 -- we split coercion t1->t2 :=: s1->s2 into t1 :=: s1 and
809 -- t2 :=: s2 with left and right on the curried form:
810 -- (->) t1 t2 :=: (->) s1 s2
811 [co1, co2] = decomposeCo 2 co
812 new_arg = mkCoerce (mkSymCoercion co1) arg'
813 arg' = case arg_se of
815 Just arg_se -> substExpr (setInScope arg_se env) arg
816 result = ApplyTo dup new_arg (Just $ zapSubstEnv env)
818 addCoerce co cont = CoerceIt co cont
820 simplType env co `thenSmpl` \ co' ->
821 simplExprF env body (addCoerce co' cont)
824 %************************************************************************
828 %************************************************************************
831 simplLam env fun cont
834 zap_it = mkLamBndrZapper fun (countArgs cont)
835 cont_ty = contResultType cont
837 -- Type-beta reduction
838 go env (Lam bndr body) (ApplyTo _ (Type ty_arg) mb_arg_se body_cont)
839 = ASSERT( isTyVar bndr )
840 do { tick (BetaReduction bndr)
841 ; ty_arg' <- case mb_arg_se of
842 Just arg_se -> simplType (setInScope arg_se env) ty_arg
843 Nothing -> return ty_arg
844 ; go (extendTvSubst env bndr ty_arg') body body_cont }
846 -- Ordinary beta reduction
847 go env (Lam bndr body) cont@(ApplyTo _ arg (Just arg_se) body_cont)
848 = do { tick (BetaReduction bndr)
849 ; simplNonRecBind env (zap_it bndr) arg arg_se cont_ty $ \ env ->
850 go env body body_cont }
852 go env (Lam bndr body) cont@(ApplyTo _ arg Nothing body_cont)
853 = do { tick (BetaReduction bndr)
854 ; simplNonRecX env (zap_it bndr) arg $ \ env ->
855 go env body body_cont }
857 -- Not enough args, so there are real lambdas left to put in the result
858 go env lam@(Lam _ _) cont
859 = do { (env, bndrs') <- simplLamBndrs env bndrs
860 ; body' <- simplExpr env body
861 ; (floats, new_lam) <- mkLam env bndrs' body' cont
862 ; addFloats env floats $ \ env ->
863 rebuild env new_lam cont }
865 (bndrs,body) = collectBinders lam
867 -- Exactly enough args
868 go env expr cont = simplExprF env expr cont
870 mkLamBndrZapper :: CoreExpr -- Function
871 -> Int -- Number of args supplied, *including* type args
872 -> Id -> Id -- Use this to zap the binders
873 mkLamBndrZapper fun n_args
874 | n_args >= n_params fun = \b -> b -- Enough args
875 | otherwise = \b -> zapLamIdInfo b
877 -- NB: we count all the args incl type args
878 -- so we must count all the binders (incl type lambdas)
879 n_params (Note _ e) = n_params e
880 n_params (Lam b e) = 1 + n_params e
881 n_params other = 0::Int
885 %************************************************************************
889 %************************************************************************
894 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
895 -- inlining. All other CCCSs are mapped to currentCCS.
896 simplNote env (SCC cc) e cont
897 = simplExpr (setEnclosingCC env currentCCS) e `thenSmpl` \ e' ->
898 rebuild env (mkSCC cc e') cont
900 -- See notes with SimplMonad.inlineMode
901 simplNote env InlineMe e cont
902 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
903 = -- Don't inline inside an INLINE expression
904 simplExpr (setMode inlineMode env ) e `thenSmpl` \ e' ->
905 rebuild env (mkInlineMe e') cont
907 | otherwise -- Dissolve the InlineMe note if there's
908 -- an interesting context of any kind to combine with
909 -- (even a type application -- anything except Stop)
910 = simplExprF env e cont
912 simplNote env (CoreNote s) e cont
913 = simplExpr env e `thenSmpl` \ e' ->
914 rebuild env (Note (CoreNote s) e') cont
918 %************************************************************************
920 \subsection{Dealing with calls}
922 %************************************************************************
925 simplVar env var cont
926 = case substId env var of
927 DoneEx e -> simplExprF (zapSubstEnv env) e cont
928 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
929 DoneId var1 occ -> completeCall (zapSubstEnv env) var1 occ cont
930 -- Note [zapSubstEnv]
931 -- The template is already simplified, so don't re-substitute.
932 -- This is VITAL. Consider
934 -- let y = \z -> ...x... in
936 -- We'll clone the inner \x, adding x->x' in the id_subst
937 -- Then when we inline y, we must *not* replace x by x' in
938 -- the inlined copy!!
940 ---------------------------------------------------------
941 -- Dealing with a call site
943 completeCall env var occ_info cont
944 = -- Simplify the arguments
945 getDOptsSmpl `thenSmpl` \ dflags ->
947 chkr = getSwitchChecker env
948 (args, call_cont) = getContArgs chkr var cont
951 simplifyArgs env fn_ty (interestingArgContext var call_cont) args
952 (contResultType call_cont) $ \ env args ->
954 -- Next, look for rules or specialisations that match
956 -- It's important to simplify the args first, because the rule-matcher
957 -- doesn't do substitution as it goes. We don't want to use subst_args
958 -- (defined in the 'where') because that throws away useful occurrence info,
959 -- and perhaps-very-important specialisations.
961 -- Some functions have specialisations *and* are strict; in this case,
962 -- we don't want to inline the wrapper of the non-specialised thing; better
963 -- to call the specialised thing instead.
964 -- We used to use the black-listing mechanism to ensure that inlining of
965 -- the wrapper didn't occur for things that have specialisations till a
966 -- later phase, so but now we just try RULES first
968 -- You might think that we shouldn't apply rules for a loop breaker:
969 -- doing so might give rise to an infinite loop, because a RULE is
970 -- rather like an extra equation for the function:
971 -- RULE: f (g x) y = x+y
974 -- But it's too drastic to disable rules for loop breakers.
975 -- Even the foldr/build rule would be disabled, because foldr
976 -- is recursive, and hence a loop breaker:
977 -- foldr k z (build g) = g k z
978 -- So it's up to the programmer: rules can cause divergence
981 in_scope = getInScope env
983 maybe_rule = case activeRule env of
984 Nothing -> Nothing -- No rules apply
985 Just act_fn -> lookupRule act_fn in_scope rules var args
988 Just (rule_name, rule_rhs) ->
989 tick (RuleFired rule_name) `thenSmpl_`
990 (if dopt Opt_D_dump_inlinings dflags then
991 pprTrace "Rule fired" (vcat [
992 text "Rule:" <+> ftext rule_name,
993 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
994 text "After: " <+> pprCoreExpr rule_rhs,
995 text "Cont: " <+> ppr call_cont])
998 simplExprF env rule_rhs call_cont ;
1000 Nothing -> -- No rules
1002 -- Next, look for an inlining
1004 arg_infos = [ interestingArg arg | arg <- args, isValArg arg]
1005 interesting_cont = interestingCallContext (notNull args)
1008 active_inline = activeInline env var occ_info
1009 maybe_inline = callSiteInline dflags active_inline occ_info
1010 var arg_infos interesting_cont
1012 case maybe_inline of {
1013 Just unfolding -- There is an inlining!
1014 -> tick (UnfoldingDone var) `thenSmpl_`
1015 (if dopt Opt_D_dump_inlinings dflags then
1016 pprTrace "Inlining done" (vcat [
1017 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1018 text "Inlined fn: " <+> ppr unfolding,
1019 text "Cont: " <+> ppr call_cont])
1022 simplExprF env unfolding (pushContArgs args call_cont)
1025 Nothing -> -- No inlining!
1028 rebuild env (mkApps (Var var) args) call_cont
1032 %************************************************************************
1034 \subsection{Arguments}
1036 %************************************************************************
1039 ---------------------------------------------------------
1040 -- Simplifying the arguments of a call
1042 simplifyArgs :: SimplEnv
1043 -> OutType -- Type of the function
1044 -> Bool -- True if the fn has RULES
1045 -> [(InExpr, Maybe SimplEnv, Bool)] -- Details of the arguments
1046 -> OutType -- Type of the continuation
1047 -> (SimplEnv -> [OutExpr] -> SimplM FloatsWithExpr)
1048 -> SimplM FloatsWithExpr
1050 -- [CPS-like because of strict arguments]
1052 -- Simplify the arguments to a call.
1053 -- This part of the simplifier may break the no-shadowing invariant
1055 -- f (...(\a -> e)...) (case y of (a,b) -> e')
1056 -- where f is strict in its second arg
1057 -- If we simplify the innermost one first we get (...(\a -> e)...)
1058 -- Simplifying the second arg makes us float the case out, so we end up with
1059 -- case y of (a,b) -> f (...(\a -> e)...) e'
1060 -- So the output does not have the no-shadowing invariant. However, there is
1061 -- no danger of getting name-capture, because when the first arg was simplified
1062 -- we used an in-scope set that at least mentioned all the variables free in its
1063 -- static environment, and that is enough.
1065 -- We can't just do innermost first, or we'd end up with a dual problem:
1066 -- case x of (a,b) -> f e (...(\a -> e')...)
1068 -- I spent hours trying to recover the no-shadowing invariant, but I just could
1069 -- not think of an elegant way to do it. The simplifier is already knee-deep in
1070 -- continuations. We have to keep the right in-scope set around; AND we have
1071 -- to get the effect that finding (error "foo") in a strict arg position will
1072 -- discard the entire application and replace it with (error "foo"). Getting
1073 -- all this at once is TOO HARD!
1075 simplifyArgs env fn_ty has_rules args cont_ty thing_inside
1076 = go env fn_ty args thing_inside
1078 go env fn_ty [] thing_inside = thing_inside env []
1079 go env fn_ty (arg:args) thing_inside = simplifyArg env fn_ty has_rules arg cont_ty $ \ env arg' ->
1080 go env (applyTypeToArg fn_ty arg') args $ \ env args' ->
1081 thing_inside env (arg':args')
1083 simplifyArg env fn_ty has_rules (arg, Nothing, _) cont_ty thing_inside
1084 = thing_inside env arg -- Already simplified
1086 simplifyArg env fn_ty has_rules (Type ty_arg, Just se, _) cont_ty thing_inside
1087 = simplType (setInScope se env) ty_arg `thenSmpl` \ new_ty_arg ->
1088 thing_inside env (Type new_ty_arg)
1090 simplifyArg env fn_ty has_rules (val_arg, Just arg_se, is_strict) cont_ty thing_inside
1092 = simplStrictArg AnArg env val_arg arg_se arg_ty cont_ty thing_inside
1094 | otherwise -- Lazy argument
1095 -- DO NOT float anything outside, hence simplExprC
1096 -- There is no benefit (unlike in a let-binding), and we'd
1097 -- have to be very careful about bogus strictness through
1098 -- floating a demanded let.
1099 = simplExprC (setInScope arg_se env) val_arg
1100 (mkLazyArgStop arg_ty has_rules) `thenSmpl` \ arg1 ->
1101 thing_inside env arg1
1103 arg_ty = funArgTy fn_ty
1106 simplStrictArg :: LetRhsFlag
1107 -> SimplEnv -- The env of the call
1108 -> InExpr -> SimplEnv -- The arg plus its env
1109 -> OutType -- arg_ty: type of the argument
1110 -> OutType -- cont_ty: Type of thing computed by the context
1111 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)
1112 -- Takes an expression of type rhs_ty,
1113 -- returns an expression of type cont_ty
1114 -- The env passed to this continuation is the
1115 -- env of the call, plus any new in-scope variables
1116 -> SimplM FloatsWithExpr -- An expression of type cont_ty
1118 simplStrictArg is_rhs call_env arg arg_env arg_ty cont_ty thing_inside
1119 = simplExprF (setInScope arg_env call_env) arg
1120 (ArgOf is_rhs arg_ty cont_ty (\ new_env -> thing_inside (setInScope call_env new_env)))
1121 -- Notice the way we use arg_env (augmented with in-scope vars from call_env)
1122 -- to simplify the argument
1123 -- and call-env (augmented with in-scope vars from the arg) to pass to the continuation
1127 %************************************************************************
1129 \subsection{mkAtomicArgs}
1131 %************************************************************************
1133 mkAtomicArgs takes a putative RHS, checks whether it's a PAP or
1134 constructor application and, if so, converts it to ANF, so that the
1135 resulting thing can be inlined more easily. Thus
1142 There are three sorts of binding context, specified by the two
1148 N N Top-level or recursive Only bind args of lifted type
1150 N Y Non-top-level and non-recursive, Bind args of lifted type, or
1151 but lazy unlifted-and-ok-for-speculation
1153 Y Y Non-top-level, non-recursive, Bind all args
1154 and strict (demanded)
1161 there is no point in transforming to
1163 x = case (y div# z) of r -> MkC r
1165 because the (y div# z) can't float out of the let. But if it was
1166 a *strict* let, then it would be a good thing to do. Hence the
1167 context information.
1170 mkAtomicArgsE :: SimplEnv
1171 -> Bool -- A strict binding
1172 -> OutExpr -- The rhs
1173 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)
1174 -> SimplM FloatsWithExpr
1176 mkAtomicArgsE env is_strict rhs thing_inside
1177 | (Var fun, args) <- collectArgs rhs, -- It's an application
1178 isDataConWorkId fun || valArgCount args < idArity fun -- And it's a constructor or PAP
1179 = go env (Var fun) args
1181 | otherwise = thing_inside env rhs
1184 go env fun [] = thing_inside env fun
1186 go env fun (arg : args)
1187 | exprIsTrivial arg -- Easy case
1188 || no_float_arg -- Can't make it atomic
1189 = go env (App fun arg) args
1192 = do { arg_id <- newId FSLIT("a") arg_ty
1193 ; completeNonRecX env False {- pessimistic -} arg_id arg_id arg $ \env ->
1194 go env (App fun (Var arg_id)) args }
1196 arg_ty = exprType arg
1197 no_float_arg = not is_strict && (isUnLiftedType arg_ty) && not (exprOkForSpeculation arg)
1200 -- Old code: consider rewriting to be more like mkAtomicArgsE
1202 mkAtomicArgs :: Bool -- A strict binding
1203 -> Bool -- OK to float unlifted args
1205 -> SimplM (OrdList (OutId,OutExpr), -- The floats (unusually) may include
1206 OutExpr) -- things that need case-binding,
1207 -- if the strict-binding flag is on
1209 mkAtomicArgs is_strict ok_float_unlifted rhs
1210 | (Var fun, args) <- collectArgs rhs, -- It's an application
1211 isDataConWorkId fun || valArgCount args < idArity fun -- And it's a constructor or PAP
1212 = go fun nilOL [] args -- Have a go
1214 | otherwise = bale_out -- Give up
1217 bale_out = returnSmpl (nilOL, rhs)
1219 go fun binds rev_args []
1220 = returnSmpl (binds, mkApps (Var fun) (reverse rev_args))
1222 go fun binds rev_args (arg : args)
1223 | exprIsTrivial arg -- Easy case
1224 = go fun binds (arg:rev_args) args
1226 | not can_float_arg -- Can't make this arg atomic
1227 = bale_out -- ... so give up
1229 | otherwise -- Don't forget to do it recursively
1230 -- E.g. x = a:b:c:[]
1231 = mkAtomicArgs is_strict ok_float_unlifted arg `thenSmpl` \ (arg_binds, arg') ->
1232 newId FSLIT("a") arg_ty `thenSmpl` \ arg_id ->
1233 go fun ((arg_binds `snocOL` (arg_id,arg')) `appOL` binds)
1234 (Var arg_id : rev_args) args
1236 arg_ty = exprType arg
1237 can_float_arg = is_strict
1238 || not (isUnLiftedType arg_ty)
1239 || (ok_float_unlifted && exprOkForSpeculation arg)
1242 addAtomicBinds :: SimplEnv -> [(OutId,OutExpr)]
1243 -> (SimplEnv -> SimplM (FloatsWith a))
1244 -> SimplM (FloatsWith a)
1245 addAtomicBinds env [] thing_inside = thing_inside env
1246 addAtomicBinds env ((v,r):bs) thing_inside = addAuxiliaryBind env (NonRec v r) $ \ env ->
1247 addAtomicBinds env bs thing_inside
1251 %************************************************************************
1253 \subsection{The main rebuilder}
1255 %************************************************************************
1258 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
1260 rebuild env expr (Stop _ _ _) = rebuildDone env expr
1261 rebuild env expr (ArgOf _ _ _ cont_fn) = cont_fn env expr
1262 rebuild env expr (CoerceIt co cont) = rebuild env (mkCoerce co expr) cont
1263 rebuild env expr (Select _ bndr alts se cont) = rebuildCase (setInScope se env) expr bndr alts cont
1264 rebuild env expr (ApplyTo _ arg mb_se cont) = rebuildApp env expr arg mb_se cont
1266 rebuildApp env fun arg mb_se cont
1267 = do { arg' <- simplArg env arg mb_se
1268 ; rebuild env (App fun arg') cont }
1270 simplArg :: SimplEnv -> CoreExpr -> Maybe SimplEnv -> SimplM CoreExpr
1271 simplArg env arg Nothing = return arg -- The arg is already simplified
1272 simplArg env arg (Just arg_env) = simplExpr (setInScope arg_env env) arg
1274 rebuildDone env expr = returnSmpl (emptyFloats env, expr)
1278 %************************************************************************
1280 \subsection{Functions dealing with a case}
1282 %************************************************************************
1284 Blob of helper functions for the "case-of-something-else" situation.
1287 ---------------------------------------------------------
1288 -- Eliminate the case if possible
1290 rebuildCase :: SimplEnv
1291 -> OutExpr -- Scrutinee
1292 -> InId -- Case binder
1293 -> [InAlt] -- Alternatives (inceasing order)
1295 -> SimplM FloatsWithExpr
1297 rebuildCase env scrut case_bndr alts cont
1298 | Just (con,args) <- exprIsConApp_maybe scrut
1299 -- Works when the scrutinee is a variable with a known unfolding
1300 -- as well as when it's an explicit constructor application
1301 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1303 | Lit lit <- scrut -- No need for same treatment as constructors
1304 -- because literals are inlined more vigorously
1305 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1308 = -- Prepare the continuation;
1309 -- The new subst_env is in place
1310 prepareCaseCont env alts cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1311 addFloats env floats $ \ env ->
1314 -- The case expression is annotated with the result type of the continuation
1315 -- This may differ from the type originally on the case. For example
1316 -- case(T) (case(Int#) a of { True -> 1#; False -> 0# }) of
1319 -- let j a# = <blob>
1320 -- in case(T) a of { True -> j 1#; False -> j 0# }
1321 -- Note that the case that scrutinises a now returns a T not an Int#
1322 res_ty' = contResultType dup_cont
1325 -- Deal with case binder
1326 simplCaseBinder env scrut case_bndr `thenSmpl` \ (alt_env, case_bndr') ->
1328 -- Deal with the case alternatives
1329 simplAlts alt_env scrut case_bndr' alts dup_cont `thenSmpl` \ alts' ->
1331 -- Put the case back together
1332 mkCase scrut case_bndr' res_ty' alts' `thenSmpl` \ case_expr ->
1334 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1335 -- The case binder *not* scope over the whole returned case-expression
1336 rebuild env case_expr nondup_cont
1339 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1340 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1341 way, there's a chance that v will now only be used once, and hence
1346 There is a time we *don't* want to do that, namely when
1347 -fno-case-of-case is on. This happens in the first simplifier pass,
1348 and enhances full laziness. Here's the bad case:
1349 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1350 If we eliminate the inner case, we trap it inside the I# v -> arm,
1351 which might prevent some full laziness happening. I've seen this
1352 in action in spectral/cichelli/Prog.hs:
1353 [(m,n) | m <- [1..max], n <- [1..max]]
1354 Hence the check for NoCaseOfCase.
1358 There is another situation when we don't want to do it. If we have
1360 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1361 ...other cases .... }
1363 We'll perform the binder-swap for the outer case, giving
1365 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1366 ...other cases .... }
1368 But there is no point in doing it for the inner case, because w1 can't
1369 be inlined anyway. Furthermore, doing the case-swapping involves
1370 zapping w2's occurrence info (see paragraphs that follow), and that
1371 forces us to bind w2 when doing case merging. So we get
1373 case x of w1 { A -> let w2 = w1 in e1
1374 B -> let w2 = w1 in e2
1375 ...other cases .... }
1377 This is plain silly in the common case where w2 is dead.
1379 Even so, I can't see a good way to implement this idea. I tried
1380 not doing the binder-swap if the scrutinee was already evaluated
1381 but that failed big-time:
1385 case v of w { MkT x ->
1386 case x of x1 { I# y1 ->
1387 case x of x2 { I# y2 -> ...
1389 Notice that because MkT is strict, x is marked "evaluated". But to
1390 eliminate the last case, we must either make sure that x (as well as
1391 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1392 the binder-swap. So this whole note is a no-op.
1396 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1397 any occurrence info (eg IAmDead) in the case binder, because the
1398 case-binder now effectively occurs whenever v does. AND we have to do
1399 the same for the pattern-bound variables! Example:
1401 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1403 Here, b and p are dead. But when we move the argment inside the first
1404 case RHS, and eliminate the second case, we get
1406 case x of { (a,b) -> a b }
1408 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1411 Indeed, this can happen anytime the case binder isn't dead:
1412 case <any> of x { (a,b) ->
1413 case x of { (p,q) -> p } }
1414 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1415 The point is that we bring into the envt a binding
1417 after the outer case, and that makes (a,b) alive. At least we do unless
1418 the case binder is guaranteed dead.
1421 simplCaseBinder env (Var v) case_bndr
1422 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
1424 -- Failed try [see Note 2 above]
1425 -- not (isEvaldUnfolding (idUnfolding v))
1427 = simplBinder env (zapOccInfo case_bndr) `thenSmpl` \ (env, case_bndr') ->
1428 returnSmpl (modifyInScope env v case_bndr', case_bndr')
1429 -- We could extend the substitution instead, but it would be
1430 -- a hack because then the substitution wouldn't be idempotent
1431 -- any more (v is an OutId). And this does just as well.
1433 simplCaseBinder env other_scrut case_bndr
1434 = simplBinder env case_bndr `thenSmpl` \ (env, case_bndr') ->
1435 returnSmpl (env, case_bndr')
1437 zapOccInfo :: InId -> InId
1438 zapOccInfo b = b `setIdOccInfo` NoOccInfo
1442 simplAlts does two things:
1444 1. Eliminate alternatives that cannot match, including the
1445 DEFAULT alternative.
1447 2. If the DEFAULT alternative can match only one possible constructor,
1448 then make that constructor explicit.
1450 case e of x { DEFAULT -> rhs }
1452 case e of x { (a,b) -> rhs }
1453 where the type is a single constructor type. This gives better code
1454 when rhs also scrutinises x or e.
1456 Here "cannot match" includes knowledge from GADTs
1458 It's a good idea do do this stuff before simplifying the alternatives, to
1459 avoid simplifying alternatives we know can't happen, and to come up with
1460 the list of constructors that are handled, to put into the IdInfo of the
1461 case binder, for use when simplifying the alternatives.
1463 Eliminating the default alternative in (1) isn't so obvious, but it can
1466 data Colour = Red | Green | Blue
1475 DEFAULT -> [ case y of ... ]
1477 If we inline h into f, the default case of the inlined h can't happen.
1478 If we don't notice this, we may end up filtering out *all* the cases
1479 of the inner case y, which give us nowhere to go!
1483 simplAlts :: SimplEnv
1485 -> OutId -- Case binder
1486 -> [InAlt] -> SimplCont
1487 -> SimplM [OutAlt] -- Includes the continuation
1489 simplAlts env scrut case_bndr' alts cont'
1490 = do { mb_alts <- mapSmpl (simplAlt env imposs_cons case_bndr' cont') alts_wo_default
1491 ; default_alts <- simplDefault env case_bndr' imposs_deflt_cons cont' maybe_deflt
1492 ; return (mergeAlts default_alts [alt' | Just (_, alt') <- mb_alts]) }
1493 -- We need the mergeAlts in case the new default_alt
1494 -- has turned into a constructor alternative.
1496 (alts_wo_default, maybe_deflt) = findDefault alts
1497 imposs_cons = case scrut of
1498 Var v -> otherCons (idUnfolding v)
1501 -- "imposs_deflt_cons" are handled either by the context,
1502 -- OR by a branch in this case expression. (Don't include DEFAULT!!)
1503 imposs_deflt_cons = nub (imposs_cons ++ [con | (con,_,_) <- alts_wo_default])
1505 simplDefault :: SimplEnv
1506 -> OutId -- Case binder; need just for its type. Note that as an
1507 -- OutId, it has maximum information; this is important.
1508 -- Test simpl013 is an example
1509 -> [AltCon] -- These cons can't happen when matching the default
1512 -> SimplM [OutAlt] -- One branch or none; we use a list because it's what
1513 -- mergeAlts expects
1516 simplDefault env case_bndr' imposs_cons cont Nothing
1517 = return [] -- No default branch
1519 simplDefault env case_bndr' imposs_cons cont (Just rhs)
1520 | -- This branch handles the case where we are
1521 -- scrutinisng an algebraic data type
1522 Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr'),
1523 isAlgTyCon tycon, -- It's a data type, tuple, or unboxed tuples.
1524 not (isNewTyCon tycon), -- We can have a newtype, if we are just doing an eval:
1525 -- case x of { DEFAULT -> e }
1526 -- and we don't want to fill in a default for them!
1527 Just all_cons <- tyConDataCons_maybe tycon,
1528 not (null all_cons), -- This is a tricky corner case. If the data type has no constructors,
1529 -- which GHC allows, then the case expression will have at most a default
1530 -- alternative. We don't want to eliminate that alternative, because the
1531 -- invariant is that there's always one alternative. It's more convenient
1533 -- case x of { DEFAULT -> e }
1534 -- as it is, rather than transform it to
1535 -- error "case cant match"
1536 -- which would be quite legitmate. But it's a really obscure corner, and
1537 -- not worth wasting code on.
1539 let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1540 poss_data_cons = filterOut (`elem` imposs_data_cons) all_cons
1541 gadt_imposs | all isTyVarTy inst_tys = []
1542 | otherwise = filter (cant_match inst_tys) poss_data_cons
1543 final_poss = filterOut (`elem` gadt_imposs) poss_data_cons
1545 = case final_poss of
1546 [] -> returnSmpl [] -- Eliminate the default alternative
1547 -- altogether if it can't match
1549 [con] -> -- It matches exactly one constructor, so fill it in
1550 do { tick (FillInCaseDefault case_bndr')
1551 ; us <- getUniquesSmpl
1552 ; let (ex_tvs, co_tvs, arg_ids) =
1553 dataConRepInstPat us con inst_tys
1554 ; let con_alt = (DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, rhs)
1555 ; Just (_, alt') <- simplAlt env [] case_bndr' cont con_alt
1556 -- The simplAlt must succeed with Just because we have
1557 -- already filtered out construtors that can't match
1560 two_or_more -> simplify_default (map DataAlt gadt_imposs ++ imposs_cons)
1563 = simplify_default imposs_cons
1565 cant_match tys data_con = not (dataConCanMatch data_con tys)
1567 simplify_default imposs_cons
1568 = do { let env' = mk_rhs_env env case_bndr' (mkOtherCon imposs_cons)
1569 -- Record the constructors that the case-binder *can't* be.
1570 ; rhs' <- simplExprC env' rhs cont
1571 ; return [(DEFAULT, [], rhs')] }
1573 simplAlt :: SimplEnv
1574 -> [AltCon] -- These constructors can't be present when
1575 -- matching this alternative
1576 -> OutId -- The case binder
1579 -> SimplM (Maybe (TvSubstEnv, OutAlt))
1581 -- Simplify an alternative, returning the type refinement for the
1582 -- alternative, if the alternative does any refinement at all
1583 -- Nothing => the alternative is inaccessible
1585 simplAlt env imposs_cons case_bndr' cont' (con, bndrs, rhs)
1586 | con `elem` imposs_cons -- This case can't match
1589 simplAlt env handled_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1590 -- TURGID DUPLICATION, needed only for the simplAlt call
1591 -- in mkDupableAlt. Clean this up when moving to FC
1592 = ASSERT( null bndrs )
1593 simplExprC env' rhs cont' `thenSmpl` \ rhs' ->
1594 returnSmpl (Just (emptyVarEnv, (DEFAULT, [], rhs')))
1596 env' = mk_rhs_env env case_bndr' (mkOtherCon handled_cons)
1597 -- Record the constructors that the case-binder *can't* be.
1599 simplAlt env handled_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1600 = ASSERT( null bndrs )
1601 simplExprC env' rhs cont' `thenSmpl` \ rhs' ->
1602 returnSmpl (Just (emptyVarEnv, (LitAlt lit, [], rhs')))
1604 env' = mk_rhs_env env case_bndr' (mkUnfolding False (Lit lit))
1606 simplAlt env handled_cons case_bndr' cont' (DataAlt con, vs, rhs)
1607 = -- Deal with the pattern-bound variables
1608 -- Mark the ones that are in ! positions in the data constructor
1609 -- as certainly-evaluated.
1610 -- NB: it happens that simplBinders does *not* erase the OtherCon
1611 -- form of unfolding, so it's ok to add this info before
1612 -- doing simplBinders
1613 simplBinders env (add_evals con vs) `thenSmpl` \ (env, vs') ->
1615 -- Bind the case-binder to (con args)
1616 let unf = mkUnfolding False (mkConApp con con_args)
1617 inst_tys' = tyConAppArgs (idType case_bndr')
1618 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1619 env' = mk_rhs_env env case_bndr' unf
1621 simplExprC env' rhs cont' `thenSmpl` \ rhs' ->
1622 returnSmpl (Just (emptyVarEnv, (DataAlt con, vs', rhs')))
1624 -- add_evals records the evaluated-ness of the bound variables of
1625 -- a case pattern. This is *important*. Consider
1626 -- data T = T !Int !Int
1628 -- case x of { T a b -> T (a+1) b }
1630 -- We really must record that b is already evaluated so that we don't
1631 -- go and re-evaluate it when constructing the result.
1632 add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1634 cat_evals dc vs strs
1638 go (v:vs) strs | isTyVar v = v : go vs strs
1639 go (v:vs) (str:strs)
1640 | isMarkedStrict str = evald_v : go vs strs
1641 | otherwise = zapped_v : go vs strs
1643 zapped_v = zap_occ_info v
1644 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1645 go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1647 -- If the case binder is alive, then we add the unfolding
1649 -- to the envt; so vs are now very much alive
1650 -- Note [Aug06] I can't see why this actually matters
1651 zap_occ_info | isDeadBinder case_bndr' = \id -> id
1652 | otherwise = zapOccInfo
1654 mk_rhs_env env case_bndr' case_bndr_unf
1655 = modifyInScope env case_bndr' (case_bndr' `setIdUnfolding` case_bndr_unf)
1659 %************************************************************************
1661 \subsection{Known constructor}
1663 %************************************************************************
1665 We are a bit careful with occurrence info. Here's an example
1667 (\x* -> case x of (a*, b) -> f a) (h v, e)
1669 where the * means "occurs once". This effectively becomes
1670 case (h v, e) of (a*, b) -> f a)
1672 let a* = h v; b = e in f a
1676 All this should happen in one sweep.
1679 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1680 -> InId -> [InAlt] -> SimplCont
1681 -> SimplM FloatsWithExpr
1683 knownCon env scrut con args bndr alts cont
1684 = tick (KnownBranch bndr) `thenSmpl_`
1685 case findAlt con alts of
1686 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1687 simplNonRecX env bndr scrut $ \ env ->
1688 -- This might give rise to a binding with non-atomic args
1689 -- like x = Node (f x) (g x)
1690 -- but simplNonRecX will atomic-ify it
1691 simplExprF env rhs cont
1693 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1694 simplNonRecX env bndr scrut $ \ env ->
1695 simplExprF env rhs cont
1697 (DataAlt dc, bs, rhs)
1698 -> -- ASSERT( n_drop_tys + length bs == length args )
1699 bind_args env dead_bndr bs (drop n_drop_tys args) $ \ env ->
1701 -- It's useful to bind bndr to scrut, rather than to a fresh
1702 -- binding x = Con arg1 .. argn
1703 -- because very often the scrut is a variable, so we avoid
1704 -- creating, and then subsequently eliminating, a let-binding
1705 -- BUT, if scrut is a not a variable, we must be careful
1706 -- about duplicating the arg redexes; in that case, make
1707 -- a new con-app from the args
1708 bndr_rhs = case scrut of
1711 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1712 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1713 -- args are aready OutExprs, but bs are InIds
1715 simplNonRecX env bndr bndr_rhs $ \ env ->
1716 simplExprF env rhs cont
1718 dead_bndr = isDeadBinder bndr
1719 n_drop_tys = tyConArity (dataConTyCon dc)
1722 bind_args env dead_bndr [] _ thing_inside = thing_inside env
1724 bind_args env dead_bndr (b:bs) (Type ty : args) thing_inside
1725 = ASSERT( isTyVar b )
1726 bind_args (extendTvSubst env b ty) dead_bndr bs args thing_inside
1728 bind_args env dead_bndr (b:bs) (arg : args) thing_inside
1731 b' = if dead_bndr then b else zapOccInfo b
1732 -- Note that the binder might be "dead", because it doesn't occur
1733 -- in the RHS; and simplNonRecX may therefore discard it via postInlineUnconditionally
1734 -- Nevertheless we must keep it if the case-binder is alive, because it may
1735 -- be used in teh con_app
1737 simplNonRecX env b' arg $ \ env ->
1738 bind_args env dead_bndr bs args thing_inside
1742 %************************************************************************
1744 \subsection{Duplicating continuations}
1746 %************************************************************************
1749 prepareCaseCont :: SimplEnv
1750 -> [InAlt] -> SimplCont
1751 -> SimplM (FloatsWith (SimplCont,SimplCont))
1752 -- Return a duplicatable continuation, a non-duplicable part
1753 -- plus some extra bindings (that scope over the entire
1756 -- No need to make it duplicatable if there's only one alternative
1757 prepareCaseCont env [alt] cont = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1758 prepareCaseCont env alts cont = mkDupableCont env cont
1762 mkDupableCont :: SimplEnv -> SimplCont
1763 -> SimplM (FloatsWith (SimplCont, SimplCont))
1765 mkDupableCont env cont
1766 | contIsDupable cont
1767 = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1769 mkDupableCont env (CoerceIt ty cont)
1770 = mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1771 returnSmpl (floats, (CoerceIt ty dup_cont, nondup_cont))
1773 mkDupableCont env cont@(ArgOf _ arg_ty _ _)
1774 = returnSmpl (emptyFloats env, (mkBoringStop arg_ty, cont))
1775 -- Do *not* duplicate an ArgOf continuation
1776 -- Because ArgOf continuations are opaque, we gain nothing by
1777 -- propagating them into the expressions, and we do lose a lot.
1778 -- Here's an example:
1779 -- && (case x of { T -> F; F -> T }) E
1780 -- Now, && is strict so we end up simplifying the case with
1781 -- an ArgOf continuation. If we let-bind it, we get
1783 -- let $j = \v -> && v E
1784 -- in simplExpr (case x of { T -> F; F -> T })
1785 -- (ArgOf (\r -> $j r)
1786 -- And after simplifying more we get
1788 -- let $j = \v -> && v E
1789 -- in case of { T -> $j F; F -> $j T }
1790 -- Which is a Very Bad Thing
1792 -- The desire not to duplicate is the entire reason that
1793 -- mkDupableCont returns a pair of continuations.
1795 -- The original plan had:
1796 -- e.g. (...strict-fn...) [...hole...]
1798 -- let $j = \a -> ...strict-fn...
1799 -- in $j [...hole...]
1801 mkDupableCont env (ApplyTo _ arg mb_se cont)
1802 = -- e.g. [...hole...] (...arg...)
1804 -- let a = ...arg...
1805 -- in [...hole...] a
1806 do { (floats, (dup_cont, nondup_cont)) <- mkDupableCont env cont
1807 ; addFloats env floats $ \ env -> do
1808 { arg1 <- simplArg env arg mb_se
1809 ; (floats2, arg2) <- mkDupableArg env arg1
1810 ; return (floats2, (ApplyTo OkToDup arg2 Nothing dup_cont, nondup_cont)) }}
1812 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1813 -- | not (exprIsDupable rhs && contIsDupable case_cont) -- See notes below
1814 -- | not (isDeadBinder case_bndr)
1815 | all isDeadBinder bs
1816 = returnSmpl (emptyFloats env, (mkBoringStop scrut_ty, cont))
1818 scrut_ty = substTy se (idType case_bndr)
1820 {- Note [Single-alternative cases]
1821 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1822 This case is just like the ArgOf case. Here's an example:
1826 case (case x of I# x' ->
1828 True -> I# (negate# x')
1829 False -> I# x') of y {
1831 Because the (case x) has only one alternative, we'll transform to
1833 case (case x' <# 0# of
1834 True -> I# (negate# x')
1835 False -> I# x') of y {
1837 But now we do *NOT* want to make a join point etc, giving
1839 let $j = \y -> MkT y
1841 True -> $j (I# (negate# x'))
1843 In this case the $j will inline again, but suppose there was a big
1844 strict computation enclosing the orginal call to MkT. Then, it won't
1845 "see" the MkT any more, because it's big and won't get duplicated.
1846 And, what is worse, nothing was gained by the case-of-case transform.
1848 When should use this case of mkDupableCont?
1849 However, matching on *any* single-alternative case is a *disaster*;
1850 e.g. case (case ....) of (a,b) -> (# a,b #)
1851 We must push the outer case into the inner one!
1854 * Match [(DEFAULT,_,_)], but in the common case of Int,
1855 the alternative-filling-in code turned the outer case into
1856 case (...) of y { I# _ -> MkT y }
1858 * Match on single alternative plus (not (isDeadBinder case_bndr))
1859 Rationale: pushing the case inwards won't eliminate the construction.
1860 But there's a risk of
1861 case (...) of y { (a,b) -> let z=(a,b) in ... }
1862 Now y looks dead, but it'll come alive again. Still, this
1863 seems like the best option at the moment.
1865 * Match on single alternative plus (all (isDeadBinder bndrs))
1866 Rationale: this is essentially seq.
1868 * Match when the rhs is *not* duplicable, and hence would lead to a
1869 join point. This catches the disaster-case above. We can test
1870 the *un-simplified* rhs, which is fine. It might get bigger or
1871 smaller after simplification; if it gets smaller, this case might
1872 fire next time round. NB also that we must test contIsDupable
1873 case_cont *btoo, because case_cont might be big!
1875 HOWEVER: I found that this version doesn't work well, because
1876 we can get let x = case (...) of { small } in ...case x...
1877 When x is inlined into its full context, we find that it was a bad
1878 idea to have pushed the outer case inside the (...) case.
1881 mkDupableCont env (Select _ case_bndr alts se cont)
1882 = -- e.g. (case [...hole...] of { pi -> ei })
1884 -- let ji = \xij -> ei
1885 -- in case [...hole...] of { pi -> ji xij }
1886 do { tick (CaseOfCase case_bndr)
1887 ; let alt_env = setInScope se env
1888 ; (floats1, (dup_cont, nondup_cont)) <- mkDupableCont alt_env cont
1889 -- NB: call mkDupableCont here, *not* prepareCaseCont
1890 -- We must make a duplicable continuation, whereas prepareCaseCont
1891 -- doesn't when there is a single case branch
1892 ; addFloats alt_env floats1 $ \ alt_env -> do
1894 { (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1895 -- NB: simplBinder does not zap deadness occ-info, so
1896 -- a dead case_bndr' will still advertise its deadness
1897 -- This is really important because in
1898 -- case e of b { (# a,b #) -> ... }
1899 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1900 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1901 -- In the new alts we build, we have the new case binder, so it must retain
1904 ; (floats2, alts') <- mkDupableAlts alt_env case_bndr' alts dup_cont
1905 ; return (floats2, (Select OkToDup case_bndr' alts' (zapSubstEnv se)
1906 (mkBoringStop (contResultType dup_cont)),
1910 mkDupableArg :: SimplEnv -> OutExpr -> SimplM (FloatsWith OutExpr)
1911 -- Let-bind the thing if necessary
1912 mkDupableArg env arg
1914 = return (emptyFloats env, arg)
1916 = do { arg_id <- newId FSLIT("a") (exprType arg)
1917 ; tick (CaseOfCase arg_id)
1918 -- Want to tick here so that we go round again,
1919 -- and maybe copy or inline the code.
1920 -- Not strictly CaseOfCase, but never mind
1921 ; return (unitFloat env arg_id arg, Var arg_id) }
1922 -- What if the arg should be case-bound?
1923 -- This has been this way for a long time, so I'll leave it,
1924 -- but I can't convince myself that it's right.
1926 mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplCont
1927 -> SimplM (FloatsWith [InAlt])
1928 -- Absorbs the continuation into the new alternatives
1930 mkDupableAlts env case_bndr' alts dupable_cont
1933 go env [] = returnSmpl (emptyFloats env, [])
1935 = do { (floats1, mb_alt') <- mkDupableAlt env case_bndr' dupable_cont alt
1936 ; addFloats env floats1 $ \ env -> do
1937 { (floats2, alts') <- go env alts
1938 ; returnSmpl (floats2, case mb_alt' of
1939 Just alt' -> alt' : alts'
1943 mkDupableAlt env case_bndr' cont alt
1944 = simplAlt env [] case_bndr' cont alt `thenSmpl` \ mb_stuff ->
1946 Nothing -> returnSmpl (emptyFloats env, Nothing) ;
1948 Just (reft, (con, bndrs', rhs')) ->
1949 -- Safe to say that there are no handled-cons for the DEFAULT case
1951 if exprIsDupable rhs' then
1952 returnSmpl (emptyFloats env, Just (con, bndrs', rhs'))
1953 -- It is worth checking for a small RHS because otherwise we
1954 -- get extra let bindings that may cause an extra iteration of the simplifier to
1955 -- inline back in place. Quite often the rhs is just a variable or constructor.
1956 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1957 -- iterations because the version with the let bindings looked big, and so wasn't
1958 -- inlined, but after the join points had been inlined it looked smaller, and so
1961 -- NB: we have to check the size of rhs', not rhs.
1962 -- Duplicating a small InAlt might invalidate occurrence information
1963 -- However, if it *is* dupable, we return the *un* simplified alternative,
1964 -- because otherwise we'd need to pair it up with an empty subst-env....
1965 -- but we only have one env shared between all the alts.
1966 -- (Remember we must zap the subst-env before re-simplifying something).
1967 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1971 rhs_ty' = exprType rhs'
1972 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1974 | isTyVar bndr = not (bndr `elemVarEnv` reft)
1975 -- Don't abstract over tyvar binders which are refined away
1976 -- See Note [Refinement] below
1977 | otherwise = not (isDeadBinder bndr)
1978 -- The deadness info on the new Ids is preserved by simplBinders
1980 -- If we try to lift a primitive-typed something out
1981 -- for let-binding-purposes, we will *caseify* it (!),
1982 -- with potentially-disastrous strictness results. So
1983 -- instead we turn it into a function: \v -> e
1984 -- where v::State# RealWorld#. The value passed to this function
1985 -- is realworld#, which generates (almost) no code.
1987 -- There's a slight infelicity here: we pass the overall
1988 -- case_bndr to all the join points if it's used in *any* RHS,
1989 -- because we don't know its usage in each RHS separately
1991 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1992 -- we make the join point into a function whenever used_bndrs'
1993 -- is empty. This makes the join-point more CPR friendly.
1994 -- Consider: let j = if .. then I# 3 else I# 4
1995 -- in case .. of { A -> j; B -> j; C -> ... }
1997 -- Now CPR doesn't w/w j because it's a thunk, so
1998 -- that means that the enclosing function can't w/w either,
1999 -- which is a lose. Here's the example that happened in practice:
2000 -- kgmod :: Int -> Int -> Int
2001 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2005 -- I have seen a case alternative like this:
2006 -- True -> \v -> ...
2007 -- It's a bit silly to add the realWorld dummy arg in this case, making
2010 -- (the \v alone is enough to make CPR happy) but I think it's rare
2012 ( if not (any isId used_bndrs')
2013 then newId FSLIT("w") realWorldStatePrimTy `thenSmpl` \ rw_id ->
2014 returnSmpl ([rw_id], [Var realWorldPrimId])
2016 returnSmpl (used_bndrs', varsToCoreExprs used_bndrs')
2017 ) `thenSmpl` \ (final_bndrs', final_args) ->
2019 -- See comment about "$j" name above
2020 newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty') `thenSmpl` \ join_bndr ->
2021 -- Notice the funky mkPiTypes. If the contructor has existentials
2022 -- it's possible that the join point will be abstracted over
2023 -- type varaibles as well as term variables.
2024 -- Example: Suppose we have
2025 -- data T = forall t. C [t]
2027 -- case (case e of ...) of
2028 -- C t xs::[t] -> rhs
2029 -- We get the join point
2030 -- let j :: forall t. [t] -> ...
2031 -- j = /\t \xs::[t] -> rhs
2033 -- case (case e of ...) of
2034 -- C t xs::[t] -> j t xs
2036 -- We make the lambdas into one-shot-lambdas. The
2037 -- join point is sure to be applied at most once, and doing so
2038 -- prevents the body of the join point being floated out by
2039 -- the full laziness pass
2040 really_final_bndrs = map one_shot final_bndrs'
2041 one_shot v | isId v = setOneShotLambda v
2043 join_rhs = mkLams really_final_bndrs rhs'
2044 join_call = mkApps (Var join_bndr) final_args
2046 returnSmpl (unitFloat env join_bndr join_rhs, Just (con, bndrs', join_call)) }
2053 MkT :: a -> b -> T a
2057 MkT a' b (p::a') (q::b) -> [p,w]
2059 The danger is that we'll make a join point
2063 and that's ill-typed, because (p::a') but (w::a).
2065 Solution so far: don't abstract over a', because the type refinement
2066 maps [a' -> a] . Ultimately that won't work when real refinement goes on.
2068 Then we must abstract over any refined free variables. Hmm. Maybe we
2069 could just abstract over *all* free variables, thereby lambda-lifting
2070 the join point? We should try this.