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 CmdLineOpts ( dopt, DynFlag(Opt_D_dump_inlinings),
15 import SimplUtils ( mkCase, mkLam, newId,
16 simplBinder, simplBinders, simplLamBndrs, simplRecBndrs, simplLetBndr,
17 SimplCont(..), DupFlag(..), LetRhsFlag(..),
18 mkStop, mkBoringStop, pushContArgs,
19 contResultType, countArgs, contIsDupable, contIsRhsOrArg,
20 getContArgs, interestingCallContext, interestingArg, isStrictType
22 import Var ( mustHaveLocalBinding )
24 import Id ( Id, idType, idInfo, idArity, isDataConId,
25 idUnfolding, setIdUnfolding, isDeadBinder,
26 idNewDemandInfo, setIdInfo,
27 setIdOccInfo, zapLamIdInfo, setOneShotLambda,
29 import IdInfo ( OccInfo(..), isLoopBreaker,
34 import NewDemand ( isStrictDmd )
35 import DataCon ( dataConNumInstArgs, dataConRepStrictness )
37 import PprCore ( pprParendExpr, pprCoreExpr )
38 import CoreUnfold ( mkOtherCon, mkUnfolding, otherCons, callSiteInline )
39 import CoreUtils ( exprIsDupable, exprIsTrivial, needsCaseBinding,
40 exprIsConApp_maybe, mkPiTypes, findAlt,
41 exprType, exprIsValue,
42 exprOkForSpeculation, exprArity, findDefault,
43 mkCoerce, mkSCC, mkInlineMe, mkAltExpr, applyTypeToArg
45 import Rules ( lookupRule )
46 import BasicTypes ( isMarkedStrict )
47 import CostCentre ( currentCCS )
48 import Type ( isUnLiftedType, seqType, tyConAppArgs, funArgTy,
49 splitFunTy_maybe, splitFunTy, eqType
51 import Subst ( mkSubst, substTy, substExpr,
52 isInScope, lookupIdSubst, simplIdInfo
54 import TysPrim ( realWorldStatePrimTy )
55 import PrelInfo ( realWorldPrimId )
56 import BasicTypes ( TopLevelFlag(..), isTopLevel,
60 import Maybe ( Maybe )
65 The guts of the simplifier is in this module, but the driver loop for
66 the simplifier is in SimplCore.lhs.
69 -----------------------------------------
70 *** IMPORTANT NOTE ***
71 -----------------------------------------
72 The simplifier used to guarantee that the output had no shadowing, but
73 it does not do so any more. (Actually, it never did!) The reason is
74 documented with simplifyArgs.
77 -----------------------------------------
78 *** IMPORTANT NOTE ***
79 -----------------------------------------
80 Many parts of the simplifier return a bunch of "floats" as well as an
81 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
83 All "floats" are let-binds, not case-binds, but some non-rec lets may
84 be unlifted (with RHS ok-for-speculation).
88 -----------------------------------------
89 ORGANISATION OF FUNCTIONS
90 -----------------------------------------
92 - simplify all top-level binders
93 - for NonRec, call simplRecOrTopPair
94 - for Rec, call simplRecBind
97 ------------------------------
98 simplExpr (applied lambda) ==> simplNonRecBind
99 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
100 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
102 ------------------------------
103 simplRecBind [binders already simplfied]
104 - use simplRecOrTopPair on each pair in turn
106 simplRecOrTopPair [binder already simplified]
107 Used for: recursive bindings (top level and nested)
108 top-level non-recursive bindings
110 - check for PreInlineUnconditionally
114 Used for: non-top-level non-recursive bindings
115 beta reductions (which amount to the same thing)
116 Because it can deal with strict arts, it takes a
117 "thing-inside" and returns an expression
119 - check for PreInlineUnconditionally
120 - simplify binder, including its IdInfo
129 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
130 Used for: binding case-binder and constr args in a known-constructor case
131 - check for PreInLineUnconditionally
135 ------------------------------
136 simplLazyBind: [binder already simplified, RHS not]
137 Used for: recursive bindings (top level and nested)
138 top-level non-recursive bindings
139 non-top-level, but *lazy* non-recursive bindings
140 [must not be strict or unboxed]
141 Returns floats + an augmented environment, not an expression
142 - substituteIdInfo and add result to in-scope
143 [so that rules are available in rec rhs]
146 - float if exposes constructor or PAP
150 completeNonRecX: [binder and rhs both simplified]
151 - if the the thing needs case binding (unlifted and not ok-for-spec)
157 completeLazyBind: [given a simplified RHS]
158 [used for both rec and non-rec bindings, top level and not]
159 - try PostInlineUnconditionally
160 - add unfolding [this is the only place we add an unfolding]
165 Right hand sides and arguments
166 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167 In many ways we want to treat
168 (a) the right hand side of a let(rec), and
169 (b) a function argument
170 in the same way. But not always! In particular, we would
171 like to leave these arguments exactly as they are, so they
172 will match a RULE more easily.
177 It's harder to make the rule match if we ANF-ise the constructor,
178 or eta-expand the PAP:
180 f (let { a = g x; b = h x } in (a,b))
183 On the other hand if we see the let-defns
188 then we *do* want to ANF-ise and eta-expand, so that p and q
189 can be safely inlined.
191 Even floating lets out is a bit dubious. For let RHS's we float lets
192 out if that exposes a value, so that the value can be inlined more vigorously.
195 r = let x = e in (x,x)
197 Here, if we float the let out we'll expose a nice constructor. We did experiments
198 that showed this to be a generally good thing. But it was a bad thing to float
199 lets out unconditionally, because that meant they got allocated more often.
201 For function arguments, there's less reason to expose a constructor (it won't
202 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
203 So for the moment we don't float lets out of function arguments either.
208 For eta expansion, we want to catch things like
210 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
212 If the \x was on the RHS of a let, we'd eta expand to bring the two
213 lambdas together. And in general that's a good thing to do. Perhaps
214 we should eta expand wherever we find a (value) lambda? Then the eta
215 expansion at a let RHS can concentrate solely on the PAP case.
218 %************************************************************************
220 \subsection{Bindings}
222 %************************************************************************
225 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
227 simplTopBinds env binds
228 = -- Put all the top-level binders into scope at the start
229 -- so that if a transformation rule has unexpectedly brought
230 -- anything into scope, then we don't get a complaint about that.
231 -- It's rather as if the top-level binders were imported.
232 simplRecBndrs env (bindersOfBinds binds) `thenSmpl` \ (env, bndrs') ->
233 simpl_binds env binds bndrs' `thenSmpl` \ (floats, _) ->
234 freeTick SimplifierDone `thenSmpl_`
235 returnSmpl (floatBinds floats)
237 -- We need to track the zapped top-level binders, because
238 -- they should have their fragile IdInfo zapped (notably occurrence info)
239 -- That's why we run down binds and bndrs' simultaneously.
240 simpl_binds :: SimplEnv -> [InBind] -> [OutId] -> SimplM (FloatsWith ())
241 simpl_binds env [] bs = ASSERT( null bs ) returnSmpl (emptyFloats env, ())
242 simpl_binds env (bind:binds) bs = simpl_bind env bind bs `thenSmpl` \ (floats,env) ->
243 addFloats env floats $ \env ->
244 simpl_binds env binds (drop_bs bind bs)
246 drop_bs (NonRec _ _) (_ : bs) = bs
247 drop_bs (Rec prs) bs = drop (length prs) bs
249 simpl_bind env (NonRec b r) (b':_) = simplRecOrTopPair env TopLevel b b' r
250 simpl_bind env (Rec pairs) bs' = simplRecBind env TopLevel pairs bs'
254 %************************************************************************
256 \subsection{simplNonRec}
258 %************************************************************************
260 simplNonRecBind is used for
261 * non-top-level non-recursive lets in expressions
265 * An unsimplified (binder, rhs) pair
266 * The env for the RHS. It may not be the same as the
267 current env because the bind might occur via (\x.E) arg
269 It uses the CPS form because the binding might be strict, in which
270 case we might discard the continuation:
271 let x* = error "foo" in (...x...)
273 It needs to turn unlifted bindings into a @case@. They can arise
274 from, say: (\x -> e) (4# + 3#)
277 simplNonRecBind :: SimplEnv
279 -> InExpr -> SimplEnv -- Arg, with its subst-env
280 -> OutType -- Type of thing computed by the context
281 -> (SimplEnv -> SimplM FloatsWithExpr) -- The body
282 -> SimplM FloatsWithExpr
284 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
286 = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
289 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
290 | preInlineUnconditionally env NotTopLevel bndr
291 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
292 thing_inside (extendSubst env bndr (ContEx (getSubstEnv rhs_se) rhs))
295 | isStrictDmd (idNewDemandInfo bndr) || isStrictType (idType bndr) -- A strict let
296 = -- Don't use simplBinder because that doesn't keep
297 -- fragile occurrence info in the substitution
298 simplLetBndr env bndr `thenSmpl` \ (env, bndr') ->
300 -- simplLetBndr doesn't deal with the IdInfo, so we must
301 -- do so here (c.f. simplLazyBind)
302 bndr'' = bndr' `setIdInfo` simplIdInfo (getSubst env) (idInfo bndr)
303 env1 = modifyInScope env bndr'' bndr''
305 simplStrictArg AnRhs env1 rhs rhs_se (idType bndr') cont_ty $ \ env rhs1 ->
307 -- Now complete the binding and simplify the body
308 completeNonRecX env True {- strict -} bndr bndr'' rhs1 thing_inside
310 | otherwise -- Normal, lazy case
311 = -- Don't use simplBinder because that doesn't keep
312 -- fragile occurrence info in the substitution
313 simplLetBndr env bndr `thenSmpl` \ (env, bndr') ->
314 simplLazyBind env NotTopLevel NonRecursive
315 bndr bndr' rhs rhs_se `thenSmpl` \ (floats, env) ->
316 addFloats env floats thing_inside
319 A specialised variant of simplNonRec used when the RHS is already simplified, notably
320 in knownCon. It uses case-binding where necessary.
323 simplNonRecX :: SimplEnv
324 -> InId -- Old binder
325 -> OutExpr -- Simplified RHS
326 -> (SimplEnv -> SimplM FloatsWithExpr)
327 -> SimplM FloatsWithExpr
329 simplNonRecX env bndr new_rhs thing_inside
330 | preInlineUnconditionally env NotTopLevel bndr
331 -- This happens; for example, the case_bndr during case of
332 -- known constructor: case (a,b) of x { (p,q) -> ... }
333 -- Here x isn't mentioned in the RHS, so we don't want to
334 -- create the (dead) let-binding let x = (a,b) in ...
336 -- Similarly, single occurrences can be inlined vigourously
337 -- e.g. case (f x, g y) of (a,b) -> ....
338 -- If a,b occur once we can avoid constructing the let binding for them.
339 = thing_inside (extendSubst env bndr (ContEx emptySubstEnv new_rhs))
342 = simplBinder env bndr `thenSmpl` \ (env, bndr') ->
343 completeNonRecX env False {- Non-strict; pessimistic -}
344 bndr bndr' new_rhs thing_inside
346 completeNonRecX env is_strict old_bndr new_bndr new_rhs thing_inside
347 | needsCaseBinding (idType new_bndr) new_rhs
348 = thing_inside env `thenSmpl` \ (floats, body) ->
349 returnSmpl (emptyFloats env, Case new_rhs new_bndr [(DEFAULT, [], wrapFloats floats body)])
352 = mkAtomicArgs is_strict
353 True {- OK to float unlifted -}
354 new_rhs `thenSmpl` \ (aux_binds, rhs2) ->
356 -- Make the arguments atomic if necessary,
357 -- adding suitable bindings
358 addAtomicBindsE env (fromOL aux_binds) $ \ env ->
359 completeLazyBind env NotTopLevel
360 old_bndr new_bndr rhs2 `thenSmpl` \ (floats, env) ->
361 addFloats env floats thing_inside
365 %************************************************************************
367 \subsection{Lazy bindings}
369 %************************************************************************
371 simplRecBind is used for
372 * recursive bindings only
375 simplRecBind :: SimplEnv -> TopLevelFlag
376 -> [(InId, InExpr)] -> [OutId]
377 -> SimplM (FloatsWith SimplEnv)
378 simplRecBind env top_lvl pairs bndrs'
379 = go env pairs bndrs' `thenSmpl` \ (floats, env) ->
380 returnSmpl (flattenFloats floats, env)
382 go env [] _ = returnSmpl (emptyFloats env, env)
384 go env ((bndr, rhs) : pairs) (bndr' : bndrs')
385 = simplRecOrTopPair env top_lvl bndr bndr' rhs `thenSmpl` \ (floats, env) ->
386 addFloats env floats (\env -> go env pairs bndrs')
390 simplRecOrTopPair is used for
391 * recursive bindings (whether top level or not)
392 * top-level non-recursive bindings
394 It assumes the binder has already been simplified, but not its IdInfo.
397 simplRecOrTopPair :: SimplEnv
399 -> InId -> OutId -- Binder, both pre-and post simpl
400 -> InExpr -- The RHS and its environment
401 -> SimplM (FloatsWith SimplEnv)
403 simplRecOrTopPair env top_lvl bndr bndr' rhs
404 | preInlineUnconditionally env top_lvl bndr -- Check for unconditional inline
405 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
406 returnSmpl (emptyFloats env, extendSubst env bndr (ContEx (getSubstEnv env) rhs))
409 = simplLazyBind env top_lvl Recursive bndr bndr' rhs env
410 -- May not actually be recursive, but it doesn't matter
414 simplLazyBind is used for
415 * recursive bindings (whether top level or not)
416 * top-level non-recursive bindings
417 * non-top-level *lazy* non-recursive bindings
419 [Thus it deals with the lazy cases from simplNonRecBind, and all cases
420 from SimplRecOrTopBind]
423 1. It assumes that the binder is *already* simplified,
424 and is in scope, but not its IdInfo
426 2. It assumes that the binder type is lifted.
428 3. It does not check for pre-inline-unconditionallly;
429 that should have been done already.
432 simplLazyBind :: SimplEnv
433 -> TopLevelFlag -> RecFlag
434 -> InId -> OutId -- Binder, both pre-and post simpl
435 -> InExpr -> SimplEnv -- The RHS and its environment
436 -> SimplM (FloatsWith SimplEnv)
438 simplLazyBind env top_lvl is_rec bndr bndr' rhs rhs_se
439 = -- Substitute IdInfo on binder, in the light of earlier
440 -- substitutions in this very letrec, and extend the
441 -- in-scope env, so that the IdInfo for this binder extends
442 -- over the RHS for the binder itself.
444 -- This is important. Manuel found cases where he really, really
445 -- wanted a RULE for a recursive function to apply in that function's
446 -- own right-hand side.
448 -- NB: does no harm for non-recursive bindings
450 bndr'' = bndr' `setIdInfo` simplIdInfo (getSubst rhs_se) (idInfo bndr)
451 env1 = modifyInScope env bndr'' bndr''
452 rhs_env = setInScope rhs_se env1
453 is_top_level = isTopLevel top_lvl
454 ok_float_unlifted = not is_top_level && isNonRec is_rec
455 rhs_cont = mkStop (idType bndr') AnRhs
457 -- Simplify the RHS; note the mkStop, which tells
458 -- the simplifier that this is the RHS of a let.
459 simplExprF rhs_env rhs rhs_cont `thenSmpl` \ (floats, rhs1) ->
461 -- If any of the floats can't be floated, give up now
462 -- (The allLifted predicate says True for empty floats.)
463 if (not ok_float_unlifted && not (allLifted floats)) then
464 completeLazyBind env1 top_lvl bndr bndr''
465 (wrapFloats floats rhs1)
468 -- ANF-ise a constructor or PAP rhs
469 mkAtomicArgs False {- Not strict -}
470 ok_float_unlifted rhs1 `thenSmpl` \ (aux_binds, rhs2) ->
472 -- If the result is a PAP, float the floats out, else wrap them
473 -- By this time it's already been ANF-ised (if necessary)
474 if isEmptyFloats floats && isNilOL aux_binds then -- Shortcut a common case
475 completeLazyBind env1 top_lvl bndr bndr'' rhs2
477 -- We use exprIsTrivial here because we want to reveal lone variables.
478 -- E.g. let { x = letrec { y = E } in y } in ...
479 -- Here we definitely want to float the y=E defn.
480 -- exprIsValue definitely isn't right for that.
482 -- BUT we can't use "exprIsCheap", because that causes a strictness bug.
483 -- x = let y* = E in case (scc y) of { T -> F; F -> T}
484 -- The case expression is 'cheap', but it's wrong to transform to
485 -- y* = E; x = case (scc y) of {...}
486 -- Either we must be careful not to float demanded non-values, or
487 -- we must use exprIsValue for the test, which ensures that the
488 -- thing is non-strict. I think. The WARN below tests for this.
489 else if is_top_level || exprIsTrivial rhs2 || exprIsValue rhs2 then
491 -- There's a subtlety here. There may be a binding (x* = e) in the
492 -- floats, where the '*' means 'will be demanded'. So is it safe
493 -- to float it out? Answer no, but it won't matter because
494 -- we only float if arg' is a WHNF,
495 -- and so there can't be any 'will be demanded' bindings in the floats.
497 WARN( any demanded_float (floatBinds floats),
498 ppr (filter demanded_float (floatBinds floats)) )
500 tick LetFloatFromLet `thenSmpl_` (
501 addFloats env1 floats $ \ env2 ->
502 addAtomicBinds env2 (fromOL aux_binds) $ \ env3 ->
503 completeLazyBind env3 top_lvl bndr bndr'' rhs2)
506 completeLazyBind env1 top_lvl bndr bndr'' (wrapFloats floats rhs1)
509 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
510 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
511 demanded_float (Rec _) = False
516 %************************************************************************
518 \subsection{Completing a lazy binding}
520 %************************************************************************
523 * deals only with Ids, not TyVars
524 * takes an already-simplified binder and RHS
525 * is used for both recursive and non-recursive bindings
526 * is used for both top-level and non-top-level bindings
528 It does the following:
529 - tries discarding a dead binding
530 - tries PostInlineUnconditionally
531 - add unfolding [this is the only place we add an unfolding]
534 It does *not* attempt to do let-to-case. Why? Because it is used for
535 - top-level bindings (when let-to-case is impossible)
536 - many situations where the "rhs" is known to be a WHNF
537 (so let-to-case is inappropriate).
540 completeLazyBind :: SimplEnv
541 -> TopLevelFlag -- Flag stuck into unfolding
542 -> InId -- Old binder
543 -> OutId -- New binder
544 -> OutExpr -- Simplified RHS
545 -> SimplM (FloatsWith SimplEnv)
546 -- We return a new SimplEnv, because completeLazyBind may choose to do its work
547 -- by extending the substitution (e.g. let x = y in ...)
548 -- The new binding (if any) is returned as part of the floats.
549 -- NB: the returned SimplEnv has the right SubstEnv, but you should
550 -- (as usual) use the in-scope-env from the floats
552 completeLazyBind env top_lvl old_bndr new_bndr new_rhs
553 | postInlineUnconditionally env new_bndr loop_breaker new_rhs
554 = -- Drop the binding
555 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
556 returnSmpl (emptyFloats env, extendSubst env old_bndr (DoneEx new_rhs))
557 -- Use the substitution to make quite, quite sure that the substitution
558 -- will happen, since we are going to discard the binding
563 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
565 -- Add the unfolding *only* for non-loop-breakers
566 -- Making loop breakers not have an unfolding at all
567 -- means that we can avoid tests in exprIsConApp, for example.
568 -- This is important: if exprIsConApp says 'yes' for a recursive
569 -- thing, then we can get into an infinite loop
570 info_w_unf | loop_breaker = new_bndr_info
571 | otherwise = new_bndr_info `setUnfoldingInfo` unfolding
572 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
574 final_id = new_bndr `setIdInfo` info_w_unf
576 -- These seqs forces the Id, and hence its IdInfo,
577 -- and hence any inner substitutions
579 returnSmpl (unitFloat env final_id new_rhs, env)
582 loop_breaker = isLoopBreaker occ_info
583 old_info = idInfo old_bndr
584 occ_info = occInfo old_info
589 %************************************************************************
591 \subsection[Simplify-simplExpr]{The main function: simplExpr}
593 %************************************************************************
595 The reason for this OutExprStuff stuff is that we want to float *after*
596 simplifying a RHS, not before. If we do so naively we get quadratic
597 behaviour as things float out.
599 To see why it's important to do it after, consider this (real) example:
613 a -- Can't inline a this round, cos it appears twice
617 Each of the ==> steps is a round of simplification. We'd save a
618 whole round if we float first. This can cascade. Consider
623 let f = let d1 = ..d.. in \y -> e
627 in \x -> ...(\y ->e)...
629 Only in this second round can the \y be applied, and it
630 might do the same again.
634 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
635 simplExpr env expr = simplExprC env expr (mkStop expr_ty' AnArg)
637 expr_ty' = substTy (getSubst env) (exprType expr)
638 -- The type in the Stop continuation, expr_ty', is usually not used
639 -- It's only needed when discarding continuations after finding
640 -- a function that returns bottom.
641 -- Hence the lazy substitution
644 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
645 -- Simplify an expression, given a continuation
646 simplExprC env expr cont
647 = simplExprF env expr cont `thenSmpl` \ (floats, expr) ->
648 returnSmpl (wrapFloats floats expr)
650 simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM FloatsWithExpr
651 -- Simplify an expression, returning floated binds
653 simplExprF env (Var v) cont = simplVar env v cont
654 simplExprF env (Lit lit) cont = rebuild env (Lit lit) cont
655 simplExprF env expr@(Lam _ _) cont = simplLam env expr cont
656 simplExprF env (Note note expr) cont = simplNote env note expr cont
657 simplExprF env (App fun arg) cont = simplExprF env fun (ApplyTo NoDup arg env cont)
659 simplExprF env (Type ty) cont
660 = ASSERT( contIsRhsOrArg cont )
661 simplType env ty `thenSmpl` \ ty' ->
662 rebuild env (Type ty') cont
664 simplExprF env (Case scrut bndr alts) cont
665 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
666 = -- Simplify the scrutinee with a Select continuation
667 simplExprF env scrut (Select NoDup bndr alts env cont)
670 = -- If case-of-case is off, simply simplify the case expression
671 -- in a vanilla Stop context, and rebuild the result around it
672 simplExprC env scrut case_cont `thenSmpl` \ case_expr' ->
673 rebuild env case_expr' cont
675 case_cont = Select NoDup bndr alts env (mkBoringStop (contResultType cont))
677 simplExprF env (Let (Rec pairs) body) cont
678 = simplRecBndrs env (map fst pairs) `thenSmpl` \ (env, bndrs') ->
679 -- NB: bndrs' don't have unfoldings or spec-envs
680 -- We add them as we go down, using simplPrags
682 simplRecBind env NotTopLevel pairs bndrs' `thenSmpl` \ (floats, env) ->
683 addFloats env floats $ \ env ->
684 simplExprF env body cont
686 -- A non-recursive let is dealt with by simplNonRecBind
687 simplExprF env (Let (NonRec bndr rhs) body) cont
688 = simplNonRecBind env bndr rhs env (contResultType cont) $ \ env ->
689 simplExprF env body cont
692 ---------------------------------
693 simplType :: SimplEnv -> InType -> SimplM OutType
694 -- Kept monadic just so we can do the seqType
696 = seqType new_ty `seq` returnSmpl new_ty
698 new_ty = substTy (getSubst env) ty
702 %************************************************************************
706 %************************************************************************
709 simplLam env fun cont
712 zap_it = mkLamBndrZapper fun (countArgs cont)
713 cont_ty = contResultType cont
715 -- Type-beta reduction
716 go env (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
717 = ASSERT( isTyVar bndr )
718 tick (BetaReduction bndr) `thenSmpl_`
719 simplType (setInScope arg_se env) ty_arg `thenSmpl` \ ty_arg' ->
720 go (extendSubst env bndr (DoneTy ty_arg')) body body_cont
722 -- Ordinary beta reduction
723 go env (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
724 = tick (BetaReduction bndr) `thenSmpl_`
725 simplNonRecBind env (zap_it bndr) arg arg_se cont_ty $ \ env ->
726 go env body body_cont
728 -- Not enough args, so there are real lambdas left to put in the result
729 go env lam@(Lam _ _) cont
730 = simplLamBndrs env bndrs `thenSmpl` \ (env, bndrs') ->
731 simplExpr env body `thenSmpl` \ body' ->
732 mkLam env bndrs' body' cont `thenSmpl` \ (floats, new_lam) ->
733 addFloats env floats $ \ env ->
734 rebuild env new_lam cont
736 (bndrs,body) = collectBinders lam
738 -- Exactly enough args
739 go env expr cont = simplExprF env expr cont
741 mkLamBndrZapper :: CoreExpr -- Function
742 -> Int -- Number of args supplied, *including* type args
743 -> Id -> Id -- Use this to zap the binders
744 mkLamBndrZapper fun n_args
745 | n_args >= n_params fun = \b -> b -- Enough args
746 | otherwise = \b -> zapLamIdInfo b
748 -- NB: we count all the args incl type args
749 -- so we must count all the binders (incl type lambdas)
750 n_params (Note _ e) = n_params e
751 n_params (Lam b e) = 1 + n_params e
752 n_params other = 0::Int
756 %************************************************************************
760 %************************************************************************
763 simplNote env (Coerce to from) body cont
765 in_scope = getInScope env
767 addCoerce s1 k1 (CoerceIt t1 cont)
768 -- coerce T1 S1 (coerce S1 K1 e)
771 -- coerce T1 K1 e, otherwise
773 -- For example, in the initial form of a worker
774 -- we may find (coerce T (coerce S (\x.e))) y
775 -- and we'd like it to simplify to e[y/x] in one round
777 | t1 `eqType` k1 = cont -- The coerces cancel out
778 | otherwise = CoerceIt t1 cont -- They don't cancel, but
779 -- the inner one is redundant
781 addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
782 | Just (s1, s2) <- splitFunTy_maybe s1s2
783 -- (coerce (T1->T2) (S1->S2) F) E
785 -- coerce T2 S2 (F (coerce S1 T1 E))
787 -- t1t2 must be a function type, T1->T2
788 -- but s1s2 might conceivably not be
790 -- When we build the ApplyTo we can't mix the out-types
791 -- with the InExpr in the argument, so we simply substitute
792 -- to make it all consistent. It's a bit messy.
793 -- But it isn't a common case.
795 (t1,t2) = splitFunTy t1t2
796 new_arg = mkCoerce s1 t1 (substExpr (mkSubst in_scope (getSubstEnv arg_se)) arg)
798 ApplyTo dup new_arg (zapSubstEnv env) (addCoerce t2 s2 cont)
800 addCoerce to' _ cont = CoerceIt to' cont
802 simplType env to `thenSmpl` \ to' ->
803 simplType env from `thenSmpl` \ from' ->
804 simplExprF env body (addCoerce to' from' cont)
807 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
808 -- inlining. All other CCCSs are mapped to currentCCS.
809 simplNote env (SCC cc) e cont
810 = simplExpr (setEnclosingCC env currentCCS) e `thenSmpl` \ e' ->
811 rebuild env (mkSCC cc e') cont
813 simplNote env InlineCall e cont
814 = simplExprF env e (InlinePlease cont)
816 -- See notes with SimplMonad.inlineMode
817 simplNote env InlineMe e cont
818 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
819 = -- Don't inline inside an INLINE expression
820 simplExpr (setMode inlineMode env ) e `thenSmpl` \ e' ->
821 rebuild env (mkInlineMe e') cont
823 | otherwise -- Dissolve the InlineMe note if there's
824 -- an interesting context of any kind to combine with
825 -- (even a type application -- anything except Stop)
826 = simplExprF env e cont
830 %************************************************************************
832 \subsection{Dealing with calls}
834 %************************************************************************
837 simplVar env var cont
838 = case lookupIdSubst (getSubst env) var of
839 DoneEx e -> simplExprF (zapSubstEnv env) e cont
840 ContEx se e -> simplExprF (setSubstEnv env se) e cont
841 DoneId var1 occ -> WARN( not (isInScope var1 (getSubst env)) && mustHaveLocalBinding var1,
842 text "simplVar:" <+> ppr var )
843 completeCall (zapSubstEnv env) var1 occ cont
844 -- The template is already simplified, so don't re-substitute.
845 -- This is VITAL. Consider
847 -- let y = \z -> ...x... in
849 -- We'll clone the inner \x, adding x->x' in the id_subst
850 -- Then when we inline y, we must *not* replace x by x' in
851 -- the inlined copy!!
853 ---------------------------------------------------------
854 -- Dealing with a call site
856 completeCall env var occ_info cont
857 = -- Simplify the arguments
858 getDOptsSmpl `thenSmpl` \ dflags ->
860 chkr = getSwitchChecker env
861 (args, call_cont, inline_call) = getContArgs chkr var cont
864 simplifyArgs env fn_ty args (contResultType call_cont) $ \ env args ->
866 -- Next, look for rules or specialisations that match
868 -- It's important to simplify the args first, because the rule-matcher
869 -- doesn't do substitution as it goes. We don't want to use subst_args
870 -- (defined in the 'where') because that throws away useful occurrence info,
871 -- and perhaps-very-important specialisations.
873 -- Some functions have specialisations *and* are strict; in this case,
874 -- we don't want to inline the wrapper of the non-specialised thing; better
875 -- to call the specialised thing instead.
876 -- We used to use the black-listing mechanism to ensure that inlining of
877 -- the wrapper didn't occur for things that have specialisations till a
878 -- later phase, so but now we just try RULES first
880 -- You might think that we shouldn't apply rules for a loop breaker:
881 -- doing so might give rise to an infinite loop, because a RULE is
882 -- rather like an extra equation for the function:
883 -- RULE: f (g x) y = x+y
886 -- But it's too drastic to disable rules for loop breakers.
887 -- Even the foldr/build rule would be disabled, because foldr
888 -- is recursive, and hence a loop breaker:
889 -- foldr k z (build g) = g k z
890 -- So it's up to the programmer: rules can cause divergence
893 in_scope = getInScope env
894 maybe_rule = case activeRule env of
895 Nothing -> Nothing -- No rules apply
896 Just act_fn -> lookupRule act_fn in_scope var args
899 Just (rule_name, rule_rhs) ->
900 tick (RuleFired rule_name) `thenSmpl_`
901 (if dopt Opt_D_dump_inlinings dflags then
902 pprTrace "Rule fired" (vcat [
903 text "Rule:" <+> ptext rule_name,
904 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
905 text "After: " <+> pprCoreExpr rule_rhs,
906 text "Cont: " <+> ppr call_cont])
909 simplExprF env rule_rhs call_cont ;
911 Nothing -> -- No rules
913 -- Next, look for an inlining
915 arg_infos = [ interestingArg arg | arg <- args, isValArg arg]
917 interesting_cont = interestingCallContext (not (null args))
918 (not (null arg_infos))
921 active_inline = activeInline env var occ_info
922 maybe_inline = callSiteInline dflags active_inline inline_call occ_info
923 var arg_infos interesting_cont
925 case maybe_inline of {
926 Just unfolding -- There is an inlining!
927 -> tick (UnfoldingDone var) `thenSmpl_`
928 makeThatCall env var unfolding args call_cont
931 Nothing -> -- No inlining!
934 rebuild env (mkApps (Var var) args) call_cont
937 makeThatCall :: SimplEnv
939 -> InExpr -- Inlined function rhs
940 -> [OutExpr] -- Arguments, already simplified
941 -> SimplCont -- After the call
942 -> SimplM FloatsWithExpr
943 -- Similar to simplLam, but this time
944 -- the arguments are already simplified
945 makeThatCall orig_env var fun@(Lam _ _) args cont
946 = go orig_env fun args
948 zap_it = mkLamBndrZapper fun (length args)
950 -- Type-beta reduction
951 go env (Lam bndr body) (Type ty_arg : args)
952 = ASSERT( isTyVar bndr )
953 tick (BetaReduction bndr) `thenSmpl_`
954 go (extendSubst env bndr (DoneTy ty_arg)) body args
956 -- Ordinary beta reduction
957 go env (Lam bndr body) (arg : args)
958 = tick (BetaReduction bndr) `thenSmpl_`
959 simplNonRecX env (zap_it bndr) arg $ \ env ->
962 -- Not enough args, so there are real lambdas left to put in the result
964 = simplExprF env fun (pushContArgs orig_env args cont)
965 -- NB: orig_env; the correct environment to capture with
966 -- the arguments.... env has been augmented with substitutions
967 -- from the beta reductions.
969 makeThatCall env var fun args cont
970 = simplExprF env fun (pushContArgs env args cont)
974 %************************************************************************
976 \subsection{Arguments}
978 %************************************************************************
981 ---------------------------------------------------------
982 -- Simplifying the arguments of a call
984 simplifyArgs :: SimplEnv
985 -> OutType -- Type of the function
986 -> [(InExpr, SimplEnv, Bool)] -- Details of the arguments
987 -> OutType -- Type of the continuation
988 -> (SimplEnv -> [OutExpr] -> SimplM FloatsWithExpr)
989 -> SimplM FloatsWithExpr
991 -- [CPS-like because of strict arguments]
993 -- Simplify the arguments to a call.
994 -- This part of the simplifier may break the no-shadowing invariant
996 -- f (...(\a -> e)...) (case y of (a,b) -> e')
997 -- where f is strict in its second arg
998 -- If we simplify the innermost one first we get (...(\a -> e)...)
999 -- Simplifying the second arg makes us float the case out, so we end up with
1000 -- case y of (a,b) -> f (...(\a -> e)...) e'
1001 -- So the output does not have the no-shadowing invariant. However, there is
1002 -- no danger of getting name-capture, because when the first arg was simplified
1003 -- we used an in-scope set that at least mentioned all the variables free in its
1004 -- static environment, and that is enough.
1006 -- We can't just do innermost first, or we'd end up with a dual problem:
1007 -- case x of (a,b) -> f e (...(\a -> e')...)
1009 -- I spent hours trying to recover the no-shadowing invariant, but I just could
1010 -- not think of an elegant way to do it. The simplifier is already knee-deep in
1011 -- continuations. We have to keep the right in-scope set around; AND we have
1012 -- to get the effect that finding (error "foo") in a strict arg position will
1013 -- discard the entire application and replace it with (error "foo"). Getting
1014 -- all this at once is TOO HARD!
1016 simplifyArgs env fn_ty args cont_ty thing_inside
1017 = go env fn_ty args thing_inside
1019 go env fn_ty [] thing_inside = thing_inside env []
1020 go env fn_ty (arg:args) thing_inside = simplifyArg env fn_ty arg cont_ty $ \ env arg' ->
1021 go env (applyTypeToArg fn_ty arg') args $ \ env args' ->
1022 thing_inside env (arg':args')
1024 simplifyArg env fn_ty (Type ty_arg, se, _) cont_ty thing_inside
1025 = simplType (setInScope se env) ty_arg `thenSmpl` \ new_ty_arg ->
1026 thing_inside env (Type new_ty_arg)
1028 simplifyArg env fn_ty (val_arg, arg_se, is_strict) cont_ty thing_inside
1030 = simplStrictArg AnArg env val_arg arg_se arg_ty cont_ty thing_inside
1033 = simplExprF (setInScope arg_se env) val_arg
1034 (mkStop arg_ty AnArg) `thenSmpl` \ (floats, arg1) ->
1035 addFloats env floats $ \ env ->
1036 thing_inside env arg1
1038 arg_ty = funArgTy fn_ty
1041 simplStrictArg :: LetRhsFlag
1042 -> SimplEnv -- The env of the call
1043 -> InExpr -> SimplEnv -- The arg plus its env
1044 -> OutType -- arg_ty: type of the argument
1045 -> OutType -- cont_ty: Type of thing computed by the context
1046 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)
1047 -- Takes an expression of type rhs_ty,
1048 -- returns an expression of type cont_ty
1049 -- The env passed to this continuation is the
1050 -- env of the call, plus any new in-scope variables
1051 -> SimplM FloatsWithExpr -- An expression of type cont_ty
1053 simplStrictArg is_rhs call_env arg arg_env arg_ty cont_ty thing_inside
1054 = simplExprF (setInScope arg_env call_env) arg
1055 (ArgOf is_rhs arg_ty cont_ty (\ new_env -> thing_inside (setInScope call_env new_env)))
1056 -- Notice the way we use arg_env (augmented with in-scope vars from call_env)
1057 -- to simplify the argument
1058 -- and call-env (augmented with in-scope vars from the arg) to pass to the continuation
1062 %************************************************************************
1064 \subsection{mkAtomicArgs}
1066 %************************************************************************
1068 mkAtomicArgs takes a putative RHS, checks whether it's a PAP or
1069 constructor application and, if so, converts it to ANF, so that the
1070 resulting thing can be inlined more easily. Thus
1077 There are three sorts of binding context, specified by the two
1083 N N Top-level or recursive Only bind args of lifted type
1085 N Y Non-top-level and non-recursive, Bind args of lifted type, or
1086 but lazy unlifted-and-ok-for-speculation
1088 Y Y Non-top-level, non-recursive, Bind all args
1089 and strict (demanded)
1096 there is no point in transforming to
1098 x = case (y div# z) of r -> MkC r
1100 because the (y div# z) can't float out of the let. But if it was
1101 a *strict* let, then it would be a good thing to do. Hence the
1102 context information.
1105 mkAtomicArgs :: Bool -- A strict binding
1106 -> Bool -- OK to float unlifted args
1108 -> SimplM (OrdList (OutId,OutExpr), -- The floats (unusually) may include
1109 OutExpr) -- things that need case-binding,
1110 -- if the strict-binding flag is on
1112 mkAtomicArgs is_strict ok_float_unlifted rhs
1113 | (Var fun, args) <- collectArgs rhs, -- It's an application
1114 isDataConId fun || valArgCount args < idArity fun -- And it's a constructor or PAP
1115 = go fun nilOL [] args -- Have a go
1117 | otherwise = bale_out -- Give up
1120 bale_out = returnSmpl (nilOL, rhs)
1122 go fun binds rev_args []
1123 = returnSmpl (binds, mkApps (Var fun) (reverse rev_args))
1125 go fun binds rev_args (arg : args)
1126 | exprIsTrivial arg -- Easy case
1127 = go fun binds (arg:rev_args) args
1129 | not can_float_arg -- Can't make this arg atomic
1130 = bale_out -- ... so give up
1132 | otherwise -- Don't forget to do it recursively
1133 -- E.g. x = a:b:c:[]
1134 = mkAtomicArgs is_strict ok_float_unlifted arg `thenSmpl` \ (arg_binds, arg') ->
1135 newId SLIT("a") arg_ty `thenSmpl` \ arg_id ->
1136 go fun ((arg_binds `snocOL` (arg_id,arg')) `appOL` binds)
1137 (Var arg_id : rev_args) args
1139 arg_ty = exprType arg
1140 can_float_arg = is_strict
1141 || not (isUnLiftedType arg_ty)
1142 || (ok_float_unlifted && exprOkForSpeculation arg)
1145 addAtomicBinds :: SimplEnv -> [(OutId,OutExpr)]
1146 -> (SimplEnv -> SimplM (FloatsWith a))
1147 -> SimplM (FloatsWith a)
1148 addAtomicBinds env [] thing_inside = thing_inside env
1149 addAtomicBinds env ((v,r):bs) thing_inside = addAuxiliaryBind env (NonRec v r) $ \ env ->
1150 addAtomicBinds env bs thing_inside
1152 addAtomicBindsE :: SimplEnv -> [(OutId,OutExpr)]
1153 -> (SimplEnv -> SimplM FloatsWithExpr)
1154 -> SimplM FloatsWithExpr
1155 -- Same again, but this time we're in an expression context,
1156 -- and may need to do some case bindings
1158 addAtomicBindsE env [] thing_inside
1160 addAtomicBindsE env ((v,r):bs) thing_inside
1161 | needsCaseBinding (idType v) r
1162 = addAtomicBindsE (addNewInScopeIds env [v]) bs thing_inside `thenSmpl` \ (floats, expr) ->
1163 WARN( exprIsTrivial expr, ppr v <+> pprCoreExpr expr )
1164 returnSmpl (emptyFloats env, Case r v [(DEFAULT,[], wrapFloats floats expr)])
1167 = addAuxiliaryBind env (NonRec v r) $ \ env ->
1168 addAtomicBindsE env bs thing_inside
1172 %************************************************************************
1174 \subsection{The main rebuilder}
1176 %************************************************************************
1179 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
1181 rebuild env expr (Stop _ _ _) = rebuildDone env expr
1182 rebuild env expr (ArgOf _ _ _ cont_fn) = cont_fn env expr
1183 rebuild env expr (CoerceIt to_ty cont) = rebuild env (mkCoerce to_ty (exprType expr) expr) cont
1184 rebuild env expr (InlinePlease cont) = rebuild env (Note InlineCall expr) cont
1185 rebuild env expr (Select _ bndr alts se cont) = rebuildCase (setInScope se env) expr bndr alts cont
1186 rebuild env expr (ApplyTo _ arg se cont) = rebuildApp (setInScope se env) expr arg cont
1188 rebuildApp env fun arg cont
1189 = simplExpr env arg `thenSmpl` \ arg' ->
1190 rebuild env (App fun arg') cont
1192 rebuildDone env expr = returnSmpl (emptyFloats env, expr)
1196 %************************************************************************
1198 \subsection{Functions dealing with a case}
1200 %************************************************************************
1202 Blob of helper functions for the "case-of-something-else" situation.
1205 ---------------------------------------------------------
1206 -- Eliminate the case if possible
1208 rebuildCase :: SimplEnv
1209 -> OutExpr -- Scrutinee
1210 -> InId -- Case binder
1211 -> [InAlt] -- Alternatives
1213 -> SimplM FloatsWithExpr
1215 rebuildCase env scrut case_bndr alts cont
1216 | Just (con,args) <- exprIsConApp_maybe scrut
1217 -- Works when the scrutinee is a variable with a known unfolding
1218 -- as well as when it's an explicit constructor application
1219 = knownCon env (DataAlt con) args case_bndr alts cont
1221 | Lit lit <- scrut -- No need for same treatment as constructors
1222 -- because literals are inlined more vigorously
1223 = knownCon env (LitAlt lit) [] case_bndr alts cont
1226 = -- Prepare case alternatives
1227 -- Filter out alternatives that can't possibly match
1229 impossible_cons = case scrut of
1230 Var v -> otherCons (idUnfolding v)
1232 better_alts = case impossible_cons of
1234 other -> [alt | alt@(con,_,_) <- alts,
1235 not (con `elem` impossible_cons)]
1237 -- "handled_cons" are handled either by the context,
1238 -- or by a branch in this case expression
1239 -- Don't add DEFAULT to the handled_cons!!
1240 (alts_wo_default, _) = findDefault better_alts
1241 handled_cons = impossible_cons ++ [con | (con,_,_) <- alts_wo_default]
1244 -- Deal with the case binder, and prepare the continuation;
1245 -- The new subst_env is in place
1246 prepareCaseCont env better_alts cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1247 addFloats env floats $ \ env ->
1249 -- Deal with variable scrutinee
1250 simplCaseBinder env scrut case_bndr `thenSmpl` \ (alt_env, case_bndr', zap_occ_info) ->
1252 -- Deal with the case alternatives
1253 simplAlts alt_env zap_occ_info handled_cons
1254 case_bndr' better_alts dup_cont `thenSmpl` \ alts' ->
1256 -- Put the case back together
1257 mkCase scrut handled_cons case_bndr' alts' `thenSmpl` \ case_expr ->
1259 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1260 -- The case binder *not* scope over the whole returned case-expression
1261 rebuild env case_expr nondup_cont
1264 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1265 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1266 way, there's a chance that v will now only be used once, and hence
1271 There is a time we *don't* want to do that, namely when
1272 -fno-case-of-case is on. This happens in the first simplifier pass,
1273 and enhances full laziness. Here's the bad case:
1274 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1275 If we eliminate the inner case, we trap it inside the I# v -> arm,
1276 which might prevent some full laziness happening. I've seen this
1277 in action in spectral/cichelli/Prog.hs:
1278 [(m,n) | m <- [1..max], n <- [1..max]]
1279 Hence the check for NoCaseOfCase.
1283 There is another situation when we don't want to do it. If we have
1285 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1286 ...other cases .... }
1288 We'll perform the binder-swap for the outer case, giving
1290 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1291 ...other cases .... }
1293 But there is no point in doing it for the inner case,
1294 because w1 can't be inlined anyway. Furthermore, doing the case-swapping
1295 involves zapping w2's occurrence info (see paragraphs that follow),
1296 and that forces us to bind w2 when doing case merging. So we get
1298 case x of w1 { A -> let w2 = w1 in e1
1299 B -> let w2 = w1 in e2
1300 ...other cases .... }
1302 This is plain silly in the common case where w2 is dead.
1304 Even so, I can't see a good way to implement this idea. I tried
1305 not doing the binder-swap if the scrutinee was already evaluated
1306 but that failed big-time:
1310 case v of w { MkT x ->
1311 case x of x1 { I# y1 ->
1312 case x of x2 { I# y2 -> ...
1314 Notice that because MkT is strict, x is marked "evaluated". But to
1315 eliminate the last case, we must either make sure that x (as well as
1316 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1317 the binder-swap. So this whole note is a no-op.
1321 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1322 any occurrence info (eg IAmDead) in the case binder, because the
1323 case-binder now effectively occurs whenever v does. AND we have to do
1324 the same for the pattern-bound variables! Example:
1326 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1328 Here, b and p are dead. But when we move the argment inside the first
1329 case RHS, and eliminate the second case, we get
1331 case x or { (a,b) -> a b }
1333 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1334 happened. Hence the zap_occ_info function returned by simplCaseBinder
1337 simplCaseBinder env (Var v) case_bndr
1338 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
1340 -- Failed try [see Note 2 above]
1341 -- not (isEvaldUnfolding (idUnfolding v))
1343 = simplBinder env (zap case_bndr) `thenSmpl` \ (env, case_bndr') ->
1344 returnSmpl (modifyInScope env v case_bndr', case_bndr', zap)
1345 -- We could extend the substitution instead, but it would be
1346 -- a hack because then the substitution wouldn't be idempotent
1347 -- any more (v is an OutId). And this just just as well.
1349 zap b = b `setIdOccInfo` NoOccInfo
1351 simplCaseBinder env other_scrut case_bndr
1352 = simplBinder env case_bndr `thenSmpl` \ (env, case_bndr') ->
1353 returnSmpl (env, case_bndr', \ bndr -> bndr) -- NoOp on bndr
1359 simplAlts :: SimplEnv
1360 -> (InId -> InId) -- Occ-info zapper
1361 -> [AltCon] -- Alternatives the scrutinee can't be
1362 -- in the default case
1363 -> OutId -- Case binder
1364 -> [InAlt] -> SimplCont
1365 -> SimplM [OutAlt] -- Includes the continuation
1367 simplAlts env zap_occ_info handled_cons case_bndr' alts cont'
1368 = mapSmpl simpl_alt alts
1370 inst_tys' = tyConAppArgs (idType case_bndr')
1372 simpl_alt (DEFAULT, _, rhs)
1374 -- In the default case we record the constructors that the
1375 -- case-binder *can't* be.
1376 -- We take advantage of any OtherCon info in the case scrutinee
1377 case_bndr_w_unf = case_bndr' `setIdUnfolding` mkOtherCon handled_cons
1378 env_with_unf = modifyInScope env case_bndr' case_bndr_w_unf
1380 simplExprC env_with_unf rhs cont' `thenSmpl` \ rhs' ->
1381 returnSmpl (DEFAULT, [], rhs')
1383 simpl_alt (con, vs, rhs)
1384 = -- Deal with the pattern-bound variables
1385 -- Mark the ones that are in ! positions in the data constructor
1386 -- as certainly-evaluated.
1387 -- NB: it happens that simplBinders does *not* erase the OtherCon
1388 -- form of unfolding, so it's ok to add this info before
1389 -- doing simplBinders
1390 simplBinders env (add_evals con vs) `thenSmpl` \ (env, vs') ->
1392 -- Bind the case-binder to (con args)
1394 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1395 env_with_unf = modifyInScope env case_bndr' (case_bndr' `setIdUnfolding` unfolding)
1397 simplExprC env_with_unf rhs cont' `thenSmpl` \ rhs' ->
1398 returnSmpl (con, vs', rhs')
1401 -- add_evals records the evaluated-ness of the bound variables of
1402 -- a case pattern. This is *important*. Consider
1403 -- data T = T !Int !Int
1405 -- case x of { T a b -> T (a+1) b }
1407 -- We really must record that b is already evaluated so that we don't
1408 -- go and re-evaluate it when constructing the result.
1410 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1411 add_evals other_con vs = vs
1413 cat_evals [] [] = []
1414 cat_evals (v:vs) (str:strs)
1415 | isTyVar v = v : cat_evals vs (str:strs)
1416 | isMarkedStrict str = evald_v : cat_evals vs strs
1417 | otherwise = zapped_v : cat_evals vs strs
1419 zapped_v = zap_occ_info v
1420 evald_v = zapped_v `setIdUnfolding` mkOtherCon []
1424 %************************************************************************
1426 \subsection{Known constructor}
1428 %************************************************************************
1430 We are a bit careful with occurrence info. Here's an example
1432 (\x* -> case x of (a*, b) -> f a) (h v, e)
1434 where the * means "occurs once". This effectively becomes
1435 case (h v, e) of (a*, b) -> f a)
1437 let a* = h v; b = e in f a
1441 All this should happen in one sweep.
1444 knownCon :: SimplEnv -> AltCon -> [OutExpr]
1445 -> InId -> [InAlt] -> SimplCont
1446 -> SimplM FloatsWithExpr
1448 knownCon env con args bndr alts cont
1449 = tick (KnownBranch bndr) `thenSmpl_`
1450 case findAlt con alts of
1451 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1452 simplNonRecX env bndr scrut $ \ env ->
1453 -- This might give rise to a binding with non-atomic args
1454 -- like x = Node (f x) (g x)
1455 -- but no harm will be done
1456 simplExprF env rhs cont
1459 LitAlt lit -> Lit lit
1460 DataAlt dc -> mkConApp dc args
1462 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1463 simplNonRecX env bndr (Lit lit) $ \ env ->
1464 simplExprF env rhs cont
1466 (DataAlt dc, bs, rhs) -> ASSERT( length bs + n_tys == length args )
1467 bind_args env bs (drop n_tys args) $ \ env ->
1469 con_app = mkConApp dc (take n_tys args ++ con_args)
1470 con_args = [substExpr (getSubst env) (varToCoreExpr b) | b <- bs]
1471 -- args are aready OutExprs, but bs are InIds
1473 simplNonRecX env bndr con_app $ \ env ->
1474 simplExprF env rhs cont
1476 n_tys = dataConNumInstArgs dc -- Non-existential type args
1478 bind_args env [] _ thing_inside = thing_inside env
1480 bind_args env (b:bs) (Type ty : args) thing_inside
1481 = bind_args (extendSubst env b (DoneTy ty)) bs args thing_inside
1483 bind_args env (b:bs) (arg : args) thing_inside
1484 = simplNonRecX env b arg $ \ env ->
1485 bind_args env bs args thing_inside
1489 %************************************************************************
1491 \subsection{Duplicating continuations}
1493 %************************************************************************
1496 prepareCaseCont :: SimplEnv
1497 -> [InAlt] -> SimplCont
1498 -> SimplM (FloatsWith (SimplCont,SimplCont))
1499 -- Return a duplicatable continuation, a non-duplicable part
1500 -- plus some extra bindings
1502 -- No need to make it duplicatable if there's only one alternative
1503 prepareCaseCont env [alt] cont = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1504 prepareCaseCont env alts cont = mkDupableCont env cont
1508 mkDupableCont :: SimplEnv -> SimplCont
1509 -> SimplM (FloatsWith (SimplCont, SimplCont))
1511 mkDupableCont env cont
1512 | contIsDupable cont
1513 = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1515 mkDupableCont env (CoerceIt ty cont)
1516 = mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1517 returnSmpl (floats, (CoerceIt ty dup_cont, nondup_cont))
1519 mkDupableCont env (InlinePlease cont)
1520 = mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1521 returnSmpl (floats, (InlinePlease dup_cont, nondup_cont))
1523 mkDupableCont env cont@(ArgOf _ arg_ty _ _)
1524 = returnSmpl (emptyFloats env, (mkBoringStop arg_ty, cont))
1525 -- Do *not* duplicate an ArgOf continuation
1526 -- Because ArgOf continuations are opaque, we gain nothing by
1527 -- propagating them into the expressions, and we do lose a lot.
1528 -- Here's an example:
1529 -- && (case x of { T -> F; F -> T }) E
1530 -- Now, && is strict so we end up simplifying the case with
1531 -- an ArgOf continuation. If we let-bind it, we get
1533 -- let $j = \v -> && v E
1534 -- in simplExpr (case x of { T -> F; F -> T })
1535 -- (ArgOf (\r -> $j r)
1536 -- And after simplifying more we get
1538 -- let $j = \v -> && v E
1539 -- in case of { T -> $j F; F -> $j T }
1540 -- Which is a Very Bad Thing
1542 -- The desire not to duplicate is the entire reason that
1543 -- mkDupableCont returns a pair of continuations.
1545 -- The original plan had:
1546 -- e.g. (...strict-fn...) [...hole...]
1548 -- let $j = \a -> ...strict-fn...
1549 -- in $j [...hole...]
1551 mkDupableCont env (ApplyTo _ arg se cont)
1552 = -- e.g. [...hole...] (...arg...)
1554 -- let a = ...arg...
1555 -- in [...hole...] a
1556 simplExpr (setInScope se env) arg `thenSmpl` \ arg' ->
1558 mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1559 addFloats env floats $ \ env ->
1561 if exprIsDupable arg' then
1562 returnSmpl (emptyFloats env, (ApplyTo OkToDup arg' (zapSubstEnv se) dup_cont, nondup_cont))
1564 newId SLIT("a") (exprType arg') `thenSmpl` \ arg_id ->
1566 tick (CaseOfCase arg_id) `thenSmpl_`
1567 -- Want to tick here so that we go round again,
1568 -- and maybe copy or inline the code.
1569 -- Not strictly CaseOfCase, but never mind
1571 returnSmpl (unitFloat env arg_id arg',
1572 (ApplyTo OkToDup (Var arg_id) (zapSubstEnv se) dup_cont,
1574 -- But what if the arg should be case-bound?
1575 -- This has been this way for a long time, so I'll leave it,
1576 -- but I can't convince myself that it's right.
1579 mkDupableCont env (Select _ case_bndr alts se cont)
1580 = -- e.g. (case [...hole...] of { pi -> ei })
1582 -- let ji = \xij -> ei
1583 -- in case [...hole...] of { pi -> ji xij }
1584 tick (CaseOfCase case_bndr) `thenSmpl_`
1586 alt_env = setInScope se env
1588 prepareCaseCont alt_env alts cont `thenSmpl` \ (floats1, (dup_cont, nondup_cont)) ->
1589 addFloats alt_env floats1 $ \ alt_env ->
1591 simplBinder alt_env case_bndr `thenSmpl` \ (alt_env, case_bndr') ->
1592 -- NB: simplBinder does not zap deadness occ-info, so
1593 -- a dead case_bndr' will still advertise its deadness
1594 -- This is really important because in
1595 -- case e of b { (# a,b #) -> ... }
1596 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1597 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1598 -- In the new alts we build, we have the new case binder, so it must retain
1601 mkDupableAlts alt_env case_bndr' alts dup_cont `thenSmpl` \ (floats2, alts') ->
1602 addFloats alt_env floats2 $ \ alt_env ->
1603 returnSmpl (emptyFloats alt_env,
1604 (Select OkToDup case_bndr' alts' (zapSubstEnv se)
1605 (mkBoringStop (contResultType dup_cont)),
1608 mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplCont
1609 -> SimplM (FloatsWith [InAlt])
1610 -- Absorbs the continuation into the new alternatives
1612 mkDupableAlts env case_bndr' alts dupable_cont
1615 go env [] = returnSmpl (emptyFloats env, [])
1617 = mkDupableAlt env case_bndr' dupable_cont alt `thenSmpl` \ (floats1, alt') ->
1618 addFloats env floats1 $ \ env ->
1619 go env alts `thenSmpl` \ (floats2, alts') ->
1620 returnSmpl (floats2, alt' : alts')
1622 mkDupableAlt env case_bndr' cont alt@(con, bndrs, rhs)
1623 = simplBinders env bndrs `thenSmpl` \ (env, bndrs') ->
1624 simplExprC env rhs cont `thenSmpl` \ rhs' ->
1626 if exprIsDupable rhs' then
1627 returnSmpl (emptyFloats env, (con, bndrs', rhs'))
1628 -- It is worth checking for a small RHS because otherwise we
1629 -- get extra let bindings that may cause an extra iteration of the simplifier to
1630 -- inline back in place. Quite often the rhs is just a variable or constructor.
1631 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1632 -- iterations because the version with the let bindings looked big, and so wasn't
1633 -- inlined, but after the join points had been inlined it looked smaller, and so
1636 -- NB: we have to check the size of rhs', not rhs.
1637 -- Duplicating a small InAlt might invalidate occurrence information
1638 -- However, if it *is* dupable, we return the *un* simplified alternative,
1639 -- because otherwise we'd need to pair it up with an empty subst-env....
1640 -- but we only have one env shared between all the alts.
1641 -- (Remember we must zap the subst-env before re-simplifying something).
1642 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1646 rhs_ty' = exprType rhs'
1647 used_bndrs' = filter (not . isDeadBinder) (case_bndr' : bndrs')
1648 -- The deadness info on the new binders is unscathed
1650 -- If we try to lift a primitive-typed something out
1651 -- for let-binding-purposes, we will *caseify* it (!),
1652 -- with potentially-disastrous strictness results. So
1653 -- instead we turn it into a function: \v -> e
1654 -- where v::State# RealWorld#. The value passed to this function
1655 -- is realworld#, which generates (almost) no code.
1657 -- There's a slight infelicity here: we pass the overall
1658 -- case_bndr to all the join points if it's used in *any* RHS,
1659 -- because we don't know its usage in each RHS separately
1661 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1662 -- we make the join point into a function whenever used_bndrs'
1663 -- is empty. This makes the join-point more CPR friendly.
1664 -- Consider: let j = if .. then I# 3 else I# 4
1665 -- in case .. of { A -> j; B -> j; C -> ... }
1667 -- Now CPR doesn't w/w j because it's a thunk, so
1668 -- that means that the enclosing function can't w/w either,
1669 -- which is a lose. Here's the example that happened in practice:
1670 -- kgmod :: Int -> Int -> Int
1671 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1675 -- I have seen a case alternative like this:
1676 -- True -> \v -> ...
1677 -- It's a bit silly to add the realWorld dummy arg in this case, making
1680 -- (the \v alone is enough to make CPR happy) but I think it's rare
1682 ( if null used_bndrs'
1683 then newId SLIT("w") realWorldStatePrimTy `thenSmpl` \ rw_id ->
1684 returnSmpl ([rw_id], [Var realWorldPrimId])
1686 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs')
1687 ) `thenSmpl` \ (final_bndrs', final_args) ->
1689 -- See comment about "$j" name above
1690 newId SLIT("$j") (mkPiTypes final_bndrs' rhs_ty') `thenSmpl` \ join_bndr ->
1691 -- Notice the funky mkPiTypes. If the contructor has existentials
1692 -- it's possible that the join point will be abstracted over
1693 -- type varaibles as well as term variables.
1694 -- Example: Suppose we have
1695 -- data T = forall t. C [t]
1697 -- case (case e of ...) of
1698 -- C t xs::[t] -> rhs
1699 -- We get the join point
1700 -- let j :: forall t. [t] -> ...
1701 -- j = /\t \xs::[t] -> rhs
1703 -- case (case e of ...) of
1704 -- C t xs::[t] -> j t xs
1706 -- We make the lambdas into one-shot-lambdas. The
1707 -- join point is sure to be applied at most once, and doing so
1708 -- prevents the body of the join point being floated out by
1709 -- the full laziness pass
1710 really_final_bndrs = map one_shot final_bndrs'
1711 one_shot v | isId v = setOneShotLambda v
1713 join_rhs = mkLams really_final_bndrs rhs'
1714 join_call = mkApps (Var join_bndr) final_args
1716 returnSmpl (unitFloat env join_bndr join_rhs, (con, bndrs', join_call))