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"
13 import Type hiding ( substTy, extendTvSubst )
16 import MkId ( rUNTIME_ERROR_ID )
17 import FamInstEnv ( FamInstEnv )
22 import FamInstEnv ( topNormaliseType )
23 import DataCon ( dataConRepStrictness, dataConUnivTyVars )
25 import NewDemand ( isStrictDmd, splitStrictSig )
26 import PprCore ( pprParendExpr, pprCoreExpr )
27 import CoreUnfold ( mkUnfolding, callSiteInline, CallCtxt(..) )
29 import Rules ( lookupRule, getRules )
30 import BasicTypes ( isMarkedStrict )
31 import CostCentre ( currentCCS )
32 import TysPrim ( realWorldStatePrimTy )
33 import PrelInfo ( realWorldPrimId )
34 import BasicTypes ( TopLevelFlag(..), isTopLevel,
35 RecFlag(..), isNonRuleLoopBreaker )
36 import Maybes ( orElse )
37 import Data.List ( mapAccumL )
43 The guts of the simplifier is in this module, but the driver loop for
44 the simplifier is in SimplCore.lhs.
47 -----------------------------------------
48 *** IMPORTANT NOTE ***
49 -----------------------------------------
50 The simplifier used to guarantee that the output had no shadowing, but
51 it does not do so any more. (Actually, it never did!) The reason is
52 documented with simplifyArgs.
55 -----------------------------------------
56 *** IMPORTANT NOTE ***
57 -----------------------------------------
58 Many parts of the simplifier return a bunch of "floats" as well as an
59 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
61 All "floats" are let-binds, not case-binds, but some non-rec lets may
62 be unlifted (with RHS ok-for-speculation).
66 -----------------------------------------
67 ORGANISATION OF FUNCTIONS
68 -----------------------------------------
70 - simplify all top-level binders
71 - for NonRec, call simplRecOrTopPair
72 - for Rec, call simplRecBind
75 ------------------------------
76 simplExpr (applied lambda) ==> simplNonRecBind
77 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
78 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
80 ------------------------------
81 simplRecBind [binders already simplfied]
82 - use simplRecOrTopPair on each pair in turn
84 simplRecOrTopPair [binder already simplified]
85 Used for: recursive bindings (top level and nested)
86 top-level non-recursive bindings
88 - check for PreInlineUnconditionally
92 Used for: non-top-level non-recursive bindings
93 beta reductions (which amount to the same thing)
94 Because it can deal with strict arts, it takes a
95 "thing-inside" and returns an expression
97 - check for PreInlineUnconditionally
98 - simplify binder, including its IdInfo
107 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
108 Used for: binding case-binder and constr args in a known-constructor case
109 - check for PreInLineUnconditionally
113 ------------------------------
114 simplLazyBind: [binder already simplified, RHS not]
115 Used for: recursive bindings (top level and nested)
116 top-level non-recursive bindings
117 non-top-level, but *lazy* non-recursive bindings
118 [must not be strict or unboxed]
119 Returns floats + an augmented environment, not an expression
120 - substituteIdInfo and add result to in-scope
121 [so that rules are available in rec rhs]
124 - float if exposes constructor or PAP
128 completeNonRecX: [binder and rhs both simplified]
129 - if the the thing needs case binding (unlifted and not ok-for-spec)
135 completeBind: [given a simplified RHS]
136 [used for both rec and non-rec bindings, top level and not]
137 - try PostInlineUnconditionally
138 - add unfolding [this is the only place we add an unfolding]
143 Right hand sides and arguments
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
145 In many ways we want to treat
146 (a) the right hand side of a let(rec), and
147 (b) a function argument
148 in the same way. But not always! In particular, we would
149 like to leave these arguments exactly as they are, so they
150 will match a RULE more easily.
155 It's harder to make the rule match if we ANF-ise the constructor,
156 or eta-expand the PAP:
158 f (let { a = g x; b = h x } in (a,b))
161 On the other hand if we see the let-defns
166 then we *do* want to ANF-ise and eta-expand, so that p and q
167 can be safely inlined.
169 Even floating lets out is a bit dubious. For let RHS's we float lets
170 out if that exposes a value, so that the value can be inlined more vigorously.
173 r = let x = e in (x,x)
175 Here, if we float the let out we'll expose a nice constructor. We did experiments
176 that showed this to be a generally good thing. But it was a bad thing to float
177 lets out unconditionally, because that meant they got allocated more often.
179 For function arguments, there's less reason to expose a constructor (it won't
180 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
181 So for the moment we don't float lets out of function arguments either.
186 For eta expansion, we want to catch things like
188 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
190 If the \x was on the RHS of a let, we'd eta expand to bring the two
191 lambdas together. And in general that's a good thing to do. Perhaps
192 we should eta expand wherever we find a (value) lambda? Then the eta
193 expansion at a let RHS can concentrate solely on the PAP case.
196 %************************************************************************
198 \subsection{Bindings}
200 %************************************************************************
203 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
205 simplTopBinds env0 binds0
206 = do { -- Put all the top-level binders into scope at the start
207 -- so that if a transformation rule has unexpectedly brought
208 -- anything into scope, then we don't get a complaint about that.
209 -- It's rather as if the top-level binders were imported.
210 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
211 ; dflags <- getDOptsSmpl
212 ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
213 dopt Opt_D_dump_rule_firings dflags
214 ; env2 <- simpl_binds dump_flag env1 binds0
215 ; freeTick SimplifierDone
216 ; return (getFloats env2) }
218 -- We need to track the zapped top-level binders, because
219 -- they should have their fragile IdInfo zapped (notably occurrence info)
220 -- That's why we run down binds and bndrs' simultaneously.
222 -- The dump-flag emits a trace for each top-level binding, which
223 -- helps to locate the tracing for inlining and rule firing
224 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
225 simpl_binds _ env [] = return env
226 simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
228 ; simpl_binds dump env' binds }
230 trace_bind True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
231 trace_bind False _ = \x -> x
233 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
234 simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
236 (env', b') = addBndrRules env b (lookupRecBndr env b)
240 %************************************************************************
242 \subsection{Lazy bindings}
244 %************************************************************************
246 simplRecBind is used for
247 * recursive bindings only
250 simplRecBind :: SimplEnv -> TopLevelFlag
253 simplRecBind env0 top_lvl pairs0
254 = do { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
255 ; env1 <- go (zapFloats env_with_info) triples
256 ; return (env0 `addRecFloats` env1) }
257 -- addFloats adds the floats from env1,
258 -- _and_ updates env0 with the in-scope set from env1
260 add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
261 -- Add the (substituted) rules to the binder
262 add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
264 (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
266 go env [] = return env
268 go env ((old_bndr, new_bndr, rhs) : pairs)
269 = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
273 simplOrTopPair is used for
274 * recursive bindings (whether top level or not)
275 * top-level non-recursive bindings
277 It assumes the binder has already been simplified, but not its IdInfo.
280 simplRecOrTopPair :: SimplEnv
282 -> InId -> OutBndr -> InExpr -- Binder and rhs
283 -> SimplM SimplEnv -- Returns an env that includes the binding
285 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
286 | preInlineUnconditionally env top_lvl old_bndr rhs -- Check for unconditional inline
287 = do { tick (PreInlineUnconditionally old_bndr)
288 ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
291 = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
292 -- May not actually be recursive, but it doesn't matter
296 simplLazyBind is used for
297 * [simplRecOrTopPair] recursive bindings (whether top level or not)
298 * [simplRecOrTopPair] top-level non-recursive bindings
299 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
302 1. It assumes that the binder is *already* simplified,
303 and is in scope, and its IdInfo too, except unfolding
305 2. It assumes that the binder type is lifted.
307 3. It does not check for pre-inline-unconditionallly;
308 that should have been done already.
311 simplLazyBind :: SimplEnv
312 -> TopLevelFlag -> RecFlag
313 -> InId -> OutId -- Binder, both pre-and post simpl
314 -- The OutId has IdInfo, except arity, unfolding
315 -> InExpr -> SimplEnv -- The RHS and its environment
318 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
319 = do { let rhs_env = rhs_se `setInScope` env
320 (tvs, body) = case collectTyBinders rhs of
321 (tvs, body) | not_lam body -> (tvs,body)
322 | otherwise -> ([], rhs)
323 not_lam (Lam _ _) = False
325 -- Do not do the "abstract tyyvar" thing if there's
326 -- a lambda inside, becuase it defeats eta-reduction
327 -- f = /\a. \x. g a x
330 ; (body_env, tvs') <- simplBinders rhs_env tvs
331 -- See Note [Floating and type abstraction] in SimplUtils
334 ; (body_env1, body1) <- simplExprF body_env body mkBoringStop
336 -- ANF-ise a constructor or PAP rhs
337 ; (body_env2, body2) <- prepareRhs body_env1 body1
340 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
341 then -- No floating, just wrap up!
342 do { rhs' <- mkLam tvs' (wrapFloats body_env2 body2)
343 ; return (env, rhs') }
345 else if null tvs then -- Simple floating
346 do { tick LetFloatFromLet
347 ; return (addFloats env body_env2, body2) }
349 else -- Do type-abstraction first
350 do { tick LetFloatFromLet
351 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
352 ; rhs' <- mkLam tvs' body3
353 ; let env' = foldl (addPolyBind top_lvl) env poly_binds
354 ; return (env', rhs') }
356 ; completeBind env' top_lvl bndr bndr1 rhs' }
359 A specialised variant of simplNonRec used when the RHS is already simplified,
360 notably in knownCon. It uses case-binding where necessary.
363 simplNonRecX :: SimplEnv
364 -> InId -- Old binder
365 -> OutExpr -- Simplified RHS
368 simplNonRecX env bndr new_rhs
369 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
370 = return env -- Here b is dead, and we avoid creating
371 | otherwise -- the binding b = (a,b)
372 = do { (env', bndr') <- simplBinder env bndr
373 ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
375 completeNonRecX :: SimplEnv
377 -> InId -- Old binder
378 -> OutId -- New binder
379 -> OutExpr -- Simplified RHS
382 completeNonRecX env is_strict old_bndr new_bndr new_rhs
383 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
385 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
386 then do { tick LetFloatFromLet
387 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
388 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
389 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
392 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
393 Doing so risks exponential behaviour, because new_rhs has been simplified once already
394 In the cases described by the folowing commment, postInlineUnconditionally will
395 catch many of the relevant cases.
396 -- This happens; for example, the case_bndr during case of
397 -- known constructor: case (a,b) of x { (p,q) -> ... }
398 -- Here x isn't mentioned in the RHS, so we don't want to
399 -- create the (dead) let-binding let x = (a,b) in ...
401 -- Similarly, single occurrences can be inlined vigourously
402 -- e.g. case (f x, g y) of (a,b) -> ....
403 -- If a,b occur once we can avoid constructing the let binding for them.
405 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
406 -- Consider case I# (quotInt# x y) of
407 -- I# v -> let w = J# v in ...
408 -- If we gaily inline (quotInt# x y) for v, we end up building an
410 -- let w = J# (quotInt# x y) in ...
411 -- because quotInt# can fail.
413 | preInlineUnconditionally env NotTopLevel bndr new_rhs
414 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
417 ----------------------------------
418 prepareRhs takes a putative RHS, checks whether it's a PAP or
419 constructor application and, if so, converts it to ANF, so that the
420 resulting thing can be inlined more easily. Thus
427 We also want to deal well cases like this
428 v = (f e1 `cast` co) e2
429 Here we want to make e1,e2 trivial and get
430 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
431 That's what the 'go' loop in prepareRhs does
434 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
435 -- Adds new floats to the env iff that allows us to return a good RHS
436 prepareRhs env (Cast rhs co) -- Note [Float coercions]
437 | (ty1, _ty2) <- coercionKind co -- Do *not* do this if rhs has an unlifted type
438 , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
439 = do { (env', rhs') <- makeTrivial env rhs
440 ; return (env', Cast rhs' co) }
443 = do { (_is_val, env1, rhs1) <- go 0 env0 rhs0
444 ; return (env1, rhs1) }
446 go n_val_args env (Cast rhs co)
447 = do { (is_val, env', rhs') <- go n_val_args env rhs
448 ; return (is_val, env', Cast rhs' co) }
449 go n_val_args env (App fun (Type ty))
450 = do { (is_val, env', rhs') <- go n_val_args env fun
451 ; return (is_val, env', App rhs' (Type ty)) }
452 go n_val_args env (App fun arg)
453 = do { (is_val, env', fun') <- go (n_val_args+1) env fun
455 True -> do { (env'', arg') <- makeTrivial env' arg
456 ; return (True, env'', App fun' arg') }
457 False -> return (False, env, App fun arg) }
458 go n_val_args env (Var fun)
459 = return (is_val, env, Var fun)
461 is_val = n_val_args > 0 -- There is at least one arg
462 -- ...and the fun a constructor or PAP
463 && (isDataConWorkId fun || n_val_args < idArity fun)
465 = return (False, env, other)
469 Note [Float coercions]
470 ~~~~~~~~~~~~~~~~~~~~~~
471 When we find the binding
473 we'd like to transform it to
475 x = x `cast` co -- A trivial binding
476 There's a chance that e will be a constructor application or function, or something
477 like that, so moving the coerion to the usage site may well cancel the coersions
478 and lead to further optimisation. Example:
481 data instance T Int = T Int
483 foo :: Int -> Int -> Int
488 go n = case x of { T m -> go (n-m) }
489 -- This case should optimise
491 Note [Float coercions (unlifted)]
492 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
493 BUT don't do [Float coercions] if 'e' has an unlifted type.
496 foo :: Int = (error (# Int,Int #) "urk")
497 `cast` CoUnsafe (# Int,Int #) Int
499 If do the makeTrivial thing to the error call, we'll get
500 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
501 But 'v' isn't in scope!
503 These strange casts can happen as a result of case-of-case
504 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
509 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
510 -- Binds the expression to a variable, if it's not trivial, returning the variable
514 | otherwise -- See Note [Take care] below
515 = do { var <- newId (fsLit "a") (exprType expr)
516 ; env' <- completeNonRecX env False var var expr
517 -- pprTrace "makeTrivial" (vcat [ppr var <+> ppr (exprArity (substExpr env' (Var var)))
519 -- , ppr (substExpr env' (Var var))
520 -- , ppr (idArity (fromJust (lookupInScope (seInScope env') var))) ]) $
521 ; return (env', substExpr env' (Var var)) }
522 -- The substitution is needed becase we're constructing a new binding
524 -- And if rhs is of form (rhs1 |> co), then we might get
527 -- and now a's RHS is trivial and can be substituted out, and that
528 -- is what completeNonRecX will do
532 %************************************************************************
534 \subsection{Completing a lazy binding}
536 %************************************************************************
539 * deals only with Ids, not TyVars
540 * takes an already-simplified binder and RHS
541 * is used for both recursive and non-recursive bindings
542 * is used for both top-level and non-top-level bindings
544 It does the following:
545 - tries discarding a dead binding
546 - tries PostInlineUnconditionally
547 - add unfolding [this is the only place we add an unfolding]
550 It does *not* attempt to do let-to-case. Why? Because it is used for
551 - top-level bindings (when let-to-case is impossible)
552 - many situations where the "rhs" is known to be a WHNF
553 (so let-to-case is inappropriate).
555 Nor does it do the atomic-argument thing
558 completeBind :: SimplEnv
559 -> TopLevelFlag -- Flag stuck into unfolding
560 -> InId -- Old binder
561 -> OutId -> OutExpr -- New binder and RHS
563 -- completeBind may choose to do its work
564 -- * by extending the substitution (e.g. let x = y in ...)
565 -- * or by adding to the floats in the envt
567 completeBind env top_lvl old_bndr new_bndr new_rhs
568 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
569 -- Inline and discard the binding
570 = do { tick (PostInlineUnconditionally old_bndr)
571 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
572 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
573 -- Use the substitution to make quite, quite sure that the
574 -- substitution will happen, since we are going to discard the binding
577 = return (addNonRecWithUnf env new_bndr new_rhs unfolding wkr)
579 unfolding | omit_unfolding = NoUnfolding
580 | otherwise = mkUnfolding (isTopLevel top_lvl) new_rhs
581 old_info = idInfo old_bndr
582 occ_info = occInfo old_info
583 wkr = substWorker env (workerInfo old_info)
584 omit_unfolding = isNonRuleLoopBreaker occ_info
585 -- or not (activeInline env old_bndr)
586 -- Do *not* trim the unfolding in SimplGently, else
587 -- the specialiser can't see it!
590 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplEnv
591 -- Add a new binding to the environment, complete with its unfolding
592 -- but *do not* do postInlineUnconditionally, because we have already
593 -- processed some of the scope of the binding
594 -- We still want the unfolding though. Consider
596 -- x = /\a. let y = ... in Just y
598 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
599 -- but 'x' may well then be inlined in 'body' in which case we'd like the
600 -- opportunity to inline 'y' too.
602 addPolyBind top_lvl env (NonRec poly_id rhs)
603 = addNonRecWithUnf env poly_id rhs unfolding NoWorker
605 unfolding | not (activeInline env poly_id) = NoUnfolding
606 | otherwise = mkUnfolding (isTopLevel top_lvl) rhs
607 -- addNonRecWithInfo adds the new binding in the
608 -- proper way (ie complete with unfolding etc),
609 -- and extends the in-scope set
611 addPolyBind _ env bind@(Rec _) = extendFloats env bind
612 -- Hack: letrecs are more awkward, so we extend "by steam"
613 -- without adding unfoldings etc. At worst this leads to
614 -- more simplifier iterations
617 addNonRecWithUnf :: SimplEnv
618 -> OutId -> OutExpr -- New binder and RHS
619 -> Unfolding -> WorkerInfo -- and unfolding
621 -- Add suitable IdInfo to the Id, add the binding to the floats, and extend the in-scope set
622 addNonRecWithUnf env new_bndr rhs unfolding wkr
623 = ASSERT( isId new_bndr )
624 WARN( new_arity < old_arity || new_arity < dmd_arity,
625 (ppr final_id <+> ppr old_arity <+> ppr new_arity <+> ppr dmd_arity) $$ ppr rhs )
626 final_id `seq` -- This seq forces the Id, and hence its IdInfo,
627 -- and hence any inner substitutions
628 addNonRec env final_id rhs
629 -- The addNonRec adds it to the in-scope set too
631 dmd_arity = length $ fst $ splitStrictSig $ idNewStrictness new_bndr
632 old_arity = idArity new_bndr
635 new_arity = exprArity rhs
636 new_bndr_info = idInfo new_bndr `setArityInfo` new_arity
639 -- Add the unfolding *only* for non-loop-breakers
640 -- Making loop breakers not have an unfolding at all
641 -- means that we can avoid tests in exprIsConApp, for example.
642 -- This is important: if exprIsConApp says 'yes' for a recursive
643 -- thing, then we can get into an infinite loop
646 -- If the unfolding is a value, the demand info may
647 -- go pear-shaped, so we nuke it. Example:
649 -- case x of (p,q) -> h p q x
650 -- Here x is certainly demanded. But after we've nuked
651 -- the case, we'll get just
652 -- let x = (a,b) in h a b x
653 -- and now x is not demanded (I'm assuming h is lazy)
654 -- This really happens. Similarly
655 -- let f = \x -> e in ...f..f...
656 -- After inlining f at some of its call sites the original binding may
657 -- (for example) be no longer strictly demanded.
658 -- The solution here is a bit ad hoc...
659 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
662 final_info | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
663 | otherwise = info_w_unf
665 final_id = new_bndr `setIdInfo` final_info
670 %************************************************************************
672 \subsection[Simplify-simplExpr]{The main function: simplExpr}
674 %************************************************************************
676 The reason for this OutExprStuff stuff is that we want to float *after*
677 simplifying a RHS, not before. If we do so naively we get quadratic
678 behaviour as things float out.
680 To see why it's important to do it after, consider this (real) example:
694 a -- Can't inline a this round, cos it appears twice
698 Each of the ==> steps is a round of simplification. We'd save a
699 whole round if we float first. This can cascade. Consider
704 let f = let d1 = ..d.. in \y -> e
708 in \x -> ...(\y ->e)...
710 Only in this second round can the \y be applied, and it
711 might do the same again.
715 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
716 simplExpr env expr = simplExprC env expr mkBoringStop
718 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
719 -- Simplify an expression, given a continuation
720 simplExprC env expr cont
721 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
722 do { (env', expr') <- simplExprF (zapFloats env) expr cont
723 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
724 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
725 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
726 return (wrapFloats env' expr') }
728 --------------------------------------------------
729 simplExprF :: SimplEnv -> InExpr -> SimplCont
730 -> SimplM (SimplEnv, OutExpr)
732 simplExprF env e cont
733 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
734 simplExprF' env e cont
736 simplExprF' :: SimplEnv -> InExpr -> SimplCont
737 -> SimplM (SimplEnv, OutExpr)
738 simplExprF' env (Var v) cont = simplVar env v cont
739 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
740 simplExprF' env (Note n expr) cont = simplNote env n expr cont
741 simplExprF' env (Cast body co) cont = simplCast env body co cont
742 simplExprF' env (App fun arg) cont = simplExprF env fun $
743 ApplyTo NoDup arg env cont
745 simplExprF' env expr@(Lam _ _) cont
746 = simplLam env (map zap bndrs) body cont
747 -- The main issue here is under-saturated lambdas
748 -- (\x1. \x2. e) arg1
749 -- Here x1 might have "occurs-once" occ-info, because occ-info
750 -- is computed assuming that a group of lambdas is applied
751 -- all at once. If there are too few args, we must zap the
754 n_args = countArgs cont
755 n_params = length bndrs
756 (bndrs, body) = collectBinders expr
757 zap | n_args >= n_params = \b -> b
758 | otherwise = \b -> if isTyVar b then b
760 -- NB: we count all the args incl type args
761 -- so we must count all the binders (incl type lambdas)
763 simplExprF' env (Type ty) cont
764 = ASSERT( contIsRhsOrArg cont )
765 do { ty' <- simplType env ty
766 ; rebuild env (Type ty') cont }
768 simplExprF' env (Case scrut bndr _ alts) cont
769 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
770 = -- Simplify the scrutinee with a Select continuation
771 simplExprF env scrut (Select NoDup bndr alts env cont)
774 = -- If case-of-case is off, simply simplify the case expression
775 -- in a vanilla Stop context, and rebuild the result around it
776 do { case_expr' <- simplExprC env scrut case_cont
777 ; rebuild env case_expr' cont }
779 case_cont = Select NoDup bndr alts env mkBoringStop
781 simplExprF' env (Let (Rec pairs) body) cont
782 = do { env' <- simplRecBndrs env (map fst pairs)
783 -- NB: bndrs' don't have unfoldings or rules
784 -- We add them as we go down
786 ; env'' <- simplRecBind env' NotTopLevel pairs
787 ; simplExprF env'' body cont }
789 simplExprF' env (Let (NonRec bndr rhs) body) cont
790 = simplNonRecE env bndr (rhs, env) ([], body) cont
792 ---------------------------------
793 simplType :: SimplEnv -> InType -> SimplM OutType
794 -- Kept monadic just so we can do the seqType
796 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
797 seqType new_ty `seq` return new_ty
799 new_ty = substTy env ty
803 %************************************************************************
805 \subsection{The main rebuilder}
807 %************************************************************************
810 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
811 -- At this point the substitution in the SimplEnv should be irrelevant
812 -- only the in-scope set and floats should matter
813 rebuild env expr cont0
814 = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
816 Stop {} -> return (env, expr)
817 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
818 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
819 StrictArg fun _ info cont -> rebuildCall env (fun `App` expr) info cont
820 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
821 ; simplLam env' bs body cont }
822 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
823 ; rebuild env (App expr arg') cont }
827 %************************************************************************
831 %************************************************************************
834 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
835 -> SimplM (SimplEnv, OutExpr)
836 simplCast env body co0 cont0
837 = do { co1 <- simplType env co0
838 ; simplExprF env body (addCoerce co1 cont0) }
840 addCoerce co cont = add_coerce co (coercionKind co) cont
842 add_coerce _co (s1, k1) cont -- co :: ty~ty
843 | s1 `coreEqType` k1 = cont -- is a no-op
845 add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
846 | (_l1, t1) <- coercionKind co2
847 -- e |> (g1 :: S1~L) |> (g2 :: L~T1)
850 -- e |> (g1 . g2 :: T1~T2) otherwise
852 -- For example, in the initial form of a worker
853 -- we may find (coerce T (coerce S (\x.e))) y
854 -- and we'd like it to simplify to e[y/x] in one round
856 , s1 `coreEqType` t1 = cont -- The coerces cancel out
857 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
859 add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
860 -- (f |> g) ty ---> (f ty) |> (g @ ty)
861 -- This implements the PushT rule from the paper
862 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
863 , not (isCoVar tyvar)
864 = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
866 ty' = substTy (arg_se `setInScope` env) arg_ty
868 -- ToDo: the PushC rule is not implemented at all
870 add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
871 | not (isTypeArg arg) -- This implements the Push rule from the paper
872 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
873 -- (e |> (g :: s1s2 ~ t1->t2)) f
875 -- (e (f |> (arg g :: t1~s1))
876 -- |> (res g :: s2->t2)
878 -- t1t2 must be a function type, t1->t2, because it's applied
879 -- to something but s1s2 might conceivably not be
881 -- When we build the ApplyTo we can't mix the out-types
882 -- with the InExpr in the argument, so we simply substitute
883 -- to make it all consistent. It's a bit messy.
884 -- But it isn't a common case.
886 -- Example of use: Trac #995
887 = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
889 -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
890 -- t2 ~ s2 with left and right on the curried form:
891 -- (->) t1 t2 ~ (->) s1 s2
892 [co1, co2] = decomposeCo 2 co
893 new_arg = mkCoerce (mkSymCoercion co1) arg'
894 arg' = substExpr (arg_se `setInScope` env) arg
896 add_coerce co _ cont = CoerceIt co cont
900 %************************************************************************
904 %************************************************************************
907 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
908 -> SimplM (SimplEnv, OutExpr)
910 simplLam env [] body cont = simplExprF env body cont
913 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
914 = do { tick (BetaReduction bndr)
915 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
917 -- Not enough args, so there are real lambdas left to put in the result
918 simplLam env bndrs body cont
919 = do { (env', bndrs') <- simplLamBndrs env bndrs
920 ; body' <- simplExpr env' body
921 ; new_lam <- mkLam bndrs' body'
922 ; rebuild env' new_lam cont }
925 simplNonRecE :: SimplEnv
926 -> InId -- The binder
927 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
928 -> ([InBndr], InExpr) -- Body of the let/lambda
931 -> SimplM (SimplEnv, OutExpr)
933 -- simplNonRecE is used for
934 -- * non-top-level non-recursive lets in expressions
937 -- It deals with strict bindings, via the StrictBind continuation,
938 -- which may abort the whole process
940 -- The "body" of the binding comes as a pair of ([InId],InExpr)
941 -- representing a lambda; so we recurse back to simplLam
942 -- Why? Because of the binder-occ-info-zapping done before
943 -- the call to simplLam in simplExprF (Lam ...)
945 -- First deal with type applications and type lets
946 -- (/\a. e) (Type ty) and (let a = Type ty in e)
947 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
948 = ASSERT( isTyVar bndr )
949 do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
950 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
952 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
953 | preInlineUnconditionally env NotTopLevel bndr rhs
954 = do { tick (PreInlineUnconditionally bndr)
955 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
958 = do { simplExprF (rhs_se `setFloats` env) rhs
959 (StrictBind bndr bndrs body env cont) }
962 = ASSERT( not (isTyVar bndr) )
963 do { (env1, bndr1) <- simplNonRecBndr env bndr
964 ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
965 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
966 ; simplLam env3 bndrs body cont }
970 %************************************************************************
974 %************************************************************************
977 -- Hack alert: we only distinguish subsumed cost centre stacks for the
978 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
979 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
980 -> SimplM (SimplEnv, OutExpr)
981 simplNote env (SCC cc) e cont
982 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
983 ; rebuild env (mkSCC cc e') cont }
985 -- See notes with SimplMonad.inlineMode
986 simplNote env InlineMe e cont
987 | Just (inside, outside) <- splitInlineCont cont -- Boring boring continuation; see notes above
988 = do { -- Don't inline inside an INLINE expression
989 e' <- simplExprC (setMode inlineMode env) e inside
990 ; rebuild env (mkInlineMe e') outside }
992 | otherwise -- Dissolve the InlineMe note if there's
993 -- an interesting context of any kind to combine with
994 -- (even a type application -- anything except Stop)
995 = simplExprF env e cont
997 simplNote env (CoreNote s) e cont = do
998 e' <- simplExpr env e
999 rebuild env (Note (CoreNote s) e') cont
1003 %************************************************************************
1005 \subsection{Dealing with calls}
1007 %************************************************************************
1010 simplVar :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1011 simplVar env var cont
1012 = case substId env var of
1013 DoneEx e -> simplExprF (zapSubstEnv env) e cont
1014 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1015 DoneId var1 -> completeCall (zapSubstEnv env) var1 cont
1016 -- Note [zapSubstEnv]
1017 -- The template is already simplified, so don't re-substitute.
1018 -- This is VITAL. Consider
1020 -- let y = \z -> ...x... in
1022 -- We'll clone the inner \x, adding x->x' in the id_subst
1023 -- Then when we inline y, we must *not* replace x by x' in
1024 -- the inlined copy!!
1026 ---------------------------------------------------------
1027 -- Dealing with a call site
1029 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1030 completeCall env var cont
1031 = do { dflags <- getDOptsSmpl
1032 ; let (args,call_cont) = contArgs cont
1033 -- The args are OutExprs, obtained by *lazily* substituting
1034 -- in the args found in cont. These args are only examined
1035 -- to limited depth (unless a rule fires). But we must do
1036 -- the substitution; rule matching on un-simplified args would
1039 ------------- First try rules ----------------
1040 -- Do this before trying inlining. Some functions have
1041 -- rules *and* are strict; in this case, we don't want to
1042 -- inline the wrapper of the non-specialised thing; better
1043 -- to call the specialised thing instead.
1045 -- We used to use the black-listing mechanism to ensure that inlining of
1046 -- the wrapper didn't occur for things that have specialisations till a
1047 -- later phase, so but now we just try RULES first
1049 -- Note [Rules for recursive functions]
1050 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1051 -- You might think that we shouldn't apply rules for a loop breaker:
1052 -- doing so might give rise to an infinite loop, because a RULE is
1053 -- rather like an extra equation for the function:
1054 -- RULE: f (g x) y = x+y
1057 -- But it's too drastic to disable rules for loop breakers.
1058 -- Even the foldr/build rule would be disabled, because foldr
1059 -- is recursive, and hence a loop breaker:
1060 -- foldr k z (build g) = g k z
1061 -- So it's up to the programmer: rules can cause divergence
1062 ; rule_base <- getSimplRules
1063 ; let in_scope = getInScope env
1064 rules = getRules rule_base var
1065 maybe_rule = case activeRule dflags env of
1066 Nothing -> Nothing -- No rules apply
1067 Just act_fn -> lookupRule act_fn in_scope
1069 ; case maybe_rule of {
1070 Just (rule, rule_rhs) -> do
1071 tick (RuleFired (ru_name rule))
1072 (if dopt Opt_D_dump_rule_firings dflags then
1073 pprTrace "Rule fired" (vcat [
1074 text "Rule:" <+> ftext (ru_name rule),
1075 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1076 text "After: " <+> pprCoreExpr rule_rhs,
1077 text "Cont: " <+> ppr call_cont])
1080 simplExprF env rule_rhs (dropArgs (ruleArity rule) cont)
1081 -- The ruleArity says how many args the rule consumed
1083 ; Nothing -> do -- No rules
1085 ------------- Next try inlining ----------------
1086 { let arg_infos = [interestingArg arg | arg <- args, isValArg arg]
1087 n_val_args = length arg_infos
1088 interesting_cont = interestingCallContext call_cont
1089 active_inline = activeInline env var
1090 maybe_inline = callSiteInline dflags active_inline var
1091 (null args) arg_infos interesting_cont
1092 ; case maybe_inline of {
1093 Just unfolding -- There is an inlining!
1094 -> do { tick (UnfoldingDone var)
1095 ; (if dopt Opt_D_dump_inlinings dflags then
1096 pprTrace ("Inlining done" ++ showSDoc (ppr var)) (vcat [
1097 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1098 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1099 text "Cont: " <+> ppr call_cont])
1102 simplExprF env unfolding cont }
1104 ; Nothing -> -- No inlining!
1106 ------------- No inlining! ----------------
1107 -- Next, look for rules or specialisations that match
1109 rebuildCall env (Var var)
1110 (mkArgInfo var n_val_args call_cont) cont
1113 rebuildCall :: SimplEnv
1114 -> OutExpr -- Function
1117 -> SimplM (SimplEnv, OutExpr)
1118 rebuildCall env fun (ArgInfo { ai_strs = [] }) cont
1119 -- When we run out of strictness args, it means
1120 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1121 -- Then we want to discard the entire strict continuation. E.g.
1122 -- * case (error "hello") of { ... }
1123 -- * (error "Hello") arg
1124 -- * f (error "Hello") where f is strict
1126 -- Then, especially in the first of these cases, we'd like to discard
1127 -- the continuation, leaving just the bottoming expression. But the
1128 -- type might not be right, so we may have to add a coerce.
1129 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1130 = return (env, mk_coerce fun) -- contination to discard, else we do it
1131 where -- again and again!
1132 fun_ty = exprType fun
1133 cont_ty = contResultType env fun_ty cont
1134 co = mkUnsafeCoercion fun_ty cont_ty
1135 mk_coerce expr | cont_ty `coreEqType` fun_ty = expr
1136 | otherwise = mkCoerce co expr
1138 rebuildCall env fun info (ApplyTo _ (Type arg_ty) se cont)
1139 = do { ty' <- simplType (se `setInScope` env) arg_ty
1140 ; rebuildCall env (fun `App` Type ty') info cont }
1143 (ArgInfo { ai_rules = has_rules, ai_strs = str:strs, ai_discs = disc:discs })
1144 (ApplyTo _ arg arg_se cont)
1145 | str -- Strict argument
1146 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1147 simplExprF (arg_se `setFloats` env) arg
1148 (StrictArg fun cci arg_info' cont)
1151 | otherwise -- Lazy argument
1152 -- DO NOT float anything outside, hence simplExprC
1153 -- There is no benefit (unlike in a let-binding), and we'd
1154 -- have to be very careful about bogus strictness through
1155 -- floating a demanded let.
1156 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1158 ; rebuildCall env (fun `App` arg') arg_info' cont }
1160 arg_info' = ArgInfo { ai_rules = has_rules, ai_strs = strs, ai_discs = discs }
1161 cci | has_rules || disc > 0 = ArgCtxt has_rules disc -- Be keener here
1162 | otherwise = BoringCtxt -- Nothing interesting
1164 rebuildCall env fun _ cont
1165 = rebuild env fun cont
1170 This part of the simplifier may break the no-shadowing invariant
1172 f (...(\a -> e)...) (case y of (a,b) -> e')
1173 where f is strict in its second arg
1174 If we simplify the innermost one first we get (...(\a -> e)...)
1175 Simplifying the second arg makes us float the case out, so we end up with
1176 case y of (a,b) -> f (...(\a -> e)...) e'
1177 So the output does not have the no-shadowing invariant. However, there is
1178 no danger of getting name-capture, because when the first arg was simplified
1179 we used an in-scope set that at least mentioned all the variables free in its
1180 static environment, and that is enough.
1182 We can't just do innermost first, or we'd end up with a dual problem:
1183 case x of (a,b) -> f e (...(\a -> e')...)
1185 I spent hours trying to recover the no-shadowing invariant, but I just could
1186 not think of an elegant way to do it. The simplifier is already knee-deep in
1187 continuations. We have to keep the right in-scope set around; AND we have
1188 to get the effect that finding (error "foo") in a strict arg position will
1189 discard the entire application and replace it with (error "foo"). Getting
1190 all this at once is TOO HARD!
1192 %************************************************************************
1194 Rebuilding a cse expression
1196 %************************************************************************
1198 Note [Case elimination]
1199 ~~~~~~~~~~~~~~~~~~~~~~~
1200 The case-elimination transformation discards redundant case expressions.
1201 Start with a simple situation:
1203 case x# of ===> e[x#/y#]
1206 (when x#, y# are of primitive type, of course). We can't (in general)
1207 do this for algebraic cases, because we might turn bottom into
1210 The code in SimplUtils.prepareAlts has the effect of generalise this
1211 idea to look for a case where we're scrutinising a variable, and we
1212 know that only the default case can match. For example:
1216 DEFAULT -> ...(case x of
1220 Here the inner case is first trimmed to have only one alternative, the
1221 DEFAULT, after which it's an instance of the previous case. This
1222 really only shows up in eliminating error-checking code.
1224 We also make sure that we deal with this very common case:
1229 Here we are using the case as a strict let; if x is used only once
1230 then we want to inline it. We have to be careful that this doesn't
1231 make the program terminate when it would have diverged before, so we
1233 - e is already evaluated (it may so if e is a variable)
1234 - x is used strictly, or
1236 Lastly, the code in SimplUtils.mkCase combines identical RHSs. So
1238 case e of ===> case e of DEFAULT -> r
1242 Now again the case may be elminated by the CaseElim transformation.
1245 Further notes about case elimination
1246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1247 Consider: test :: Integer -> IO ()
1250 Turns out that this compiles to:
1253 eta1 :: State# RealWorld ->
1254 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1256 (PrelNum.jtos eta ($w[] @ Char))
1258 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1260 Notice the strange '<' which has no effect at all. This is a funny one.
1261 It started like this:
1263 f x y = if x < 0 then jtos x
1264 else if y==0 then "" else jtos x
1266 At a particular call site we have (f v 1). So we inline to get
1268 if v < 0 then jtos x
1269 else if 1==0 then "" else jtos x
1271 Now simplify the 1==0 conditional:
1273 if v<0 then jtos v else jtos v
1275 Now common-up the two branches of the case:
1277 case (v<0) of DEFAULT -> jtos v
1279 Why don't we drop the case? Because it's strict in v. It's technically
1280 wrong to drop even unnecessary evaluations, and in practice they
1281 may be a result of 'seq' so we *definitely* don't want to drop those.
1282 I don't really know how to improve this situation.
1285 ---------------------------------------------------------
1286 -- Eliminate the case if possible
1288 rebuildCase :: SimplEnv
1289 -> OutExpr -- Scrutinee
1290 -> InId -- Case binder
1291 -> [InAlt] -- Alternatives (inceasing order)
1293 -> SimplM (SimplEnv, OutExpr)
1295 --------------------------------------------------
1296 -- 1. Eliminate the case if there's a known constructor
1297 --------------------------------------------------
1299 rebuildCase env scrut case_bndr alts cont
1300 | Just (con,args) <- exprIsConApp_maybe scrut
1301 -- Works when the scrutinee is a variable with a known unfolding
1302 -- as well as when it's an explicit constructor application
1303 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1305 | Lit lit <- scrut -- No need for same treatment as constructors
1306 -- because literals are inlined more vigorously
1307 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1310 --------------------------------------------------
1311 -- 2. Eliminate the case if scrutinee is evaluated
1312 --------------------------------------------------
1314 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1315 -- See if we can get rid of the case altogether
1316 -- See Note [Case eliminiation]
1317 -- mkCase made sure that if all the alternatives are equal,
1318 -- then there is now only one (DEFAULT) rhs
1319 | all isDeadBinder bndrs -- bndrs are [InId]
1321 -- Check that the scrutinee can be let-bound instead of case-bound
1322 , exprOkForSpeculation scrut
1323 -- OK not to evaluate it
1324 -- This includes things like (==# a# b#)::Bool
1325 -- so that we simplify
1326 -- case ==# a# b# of { True -> x; False -> x }
1329 -- This particular example shows up in default methods for
1330 -- comparision operations (e.g. in (>=) for Int.Int32)
1331 || exprIsHNF scrut -- It's already evaluated
1332 || var_demanded_later scrut -- It'll be demanded later
1334 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1335 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1336 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1337 -- its argument: case x of { y -> dataToTag# y }
1338 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1339 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1341 -- Also we don't want to discard 'seq's
1342 = do { tick (CaseElim case_bndr)
1343 ; env' <- simplNonRecX env case_bndr scrut
1344 ; simplExprF env' rhs cont }
1346 -- The case binder is going to be evaluated later,
1347 -- and the scrutinee is a simple variable
1348 var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1349 && not (isTickBoxOp v)
1350 -- ugly hack; covering this case is what
1351 -- exprOkForSpeculation was intended for.
1352 var_demanded_later _ = False
1355 --------------------------------------------------
1356 -- 3. Catch-all case
1357 --------------------------------------------------
1359 rebuildCase env scrut case_bndr alts cont
1360 = do { -- Prepare the continuation;
1361 -- The new subst_env is in place
1362 (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1364 -- Simplify the alternatives
1365 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1367 -- Check for empty alternatives
1368 ; if null alts' then
1369 -- This isn't strictly an error, although it is unusual.
1370 -- It's possible that the simplifer might "see" that
1371 -- an inner case has no accessible alternatives before
1372 -- it "sees" that the entire branch of an outer case is
1373 -- inaccessible. So we simply put an error case here instead.
1374 pprTrace "mkCase: null alts" (ppr case_bndr <+> ppr scrut) $
1375 let res_ty' = contResultType env' (substTy env' (coreAltsType alts)) dup_cont
1376 lit = mkStringLit "Impossible alternative"
1377 in return (env', mkApps (Var rUNTIME_ERROR_ID) [Type res_ty', lit])
1380 { case_expr <- mkCase scrut' case_bndr' alts'
1382 -- Notice that rebuild gets the in-scope set from env, not alt_env
1383 -- The case binder *not* scope over the whole returned case-expression
1384 ; rebuild env' case_expr nodup_cont } }
1387 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1388 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1389 way, there's a chance that v will now only be used once, and hence
1392 Historical note: we use to do the "case binder swap" in the Simplifier
1393 so there were additional complications if the scrutinee was a variable.
1394 Now the binder-swap stuff is done in the occurrence analyer; see
1395 OccurAnal Note [Binder swap].
1399 If the case binder is not dead, then neither are the pattern bound
1401 case <any> of x { (a,b) ->
1402 case x of { (p,q) -> p } }
1403 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1404 The point is that we bring into the envt a binding
1406 after the outer case, and that makes (a,b) alive. At least we do unless
1407 the case binder is guaranteed dead.
1409 Note [Improving seq]
1412 type family F :: * -> *
1413 type instance F Int = Int
1415 ... case e of x { DEFAULT -> rhs } ...
1417 where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
1419 case e `cast` co of x'::Int
1420 I# x# -> let x = x' `cast` sym co
1423 so that 'rhs' can take advantage of the form of x'. Notice that Note
1424 [Case of cast] may then apply to the result.
1426 This showed up in Roman's experiments. Example:
1427 foo :: F Int -> Int -> Int
1428 foo t n = t `seq` bar n
1431 bar n = bar (n - case t of TI i -> i)
1432 Here we'd like to avoid repeated evaluating t inside the loop, by
1433 taking advantage of the `seq`.
1435 At one point I did transformation in LiberateCase, but it's more robust here.
1436 (Otherwise, there's a danger that we'll simply drop the 'seq' altogether, before
1437 LiberateCase gets to see it.)
1440 Historical note [no-case-of-case]
1441 ~~~~~~~~~~~~~~~~~~~~~~
1442 We *used* to suppress the binder-swap in case expressoins when
1443 -fno-case-of-case is on. Old remarks:
1444 "This happens in the first simplifier pass,
1445 and enhances full laziness. Here's the bad case:
1446 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1447 If we eliminate the inner case, we trap it inside the I# v -> arm,
1448 which might prevent some full laziness happening. I've seen this
1449 in action in spectral/cichelli/Prog.hs:
1450 [(m,n) | m <- [1..max], n <- [1..max]]
1451 Hence the check for NoCaseOfCase."
1452 However, now the full-laziness pass itself reverses the binder-swap, so this
1453 check is no longer necessary.
1455 Historical note [Suppressing the case binder-swap]
1456 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1457 There is another situation when it might make sense to suppress the
1458 case-expression binde-swap. If we have
1460 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1461 ...other cases .... }
1463 We'll perform the binder-swap for the outer case, giving
1465 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1466 ...other cases .... }
1468 But there is no point in doing it for the inner case, because w1 can't
1469 be inlined anyway. Furthermore, doing the case-swapping involves
1470 zapping w2's occurrence info (see paragraphs that follow), and that
1471 forces us to bind w2 when doing case merging. So we get
1473 case x of w1 { A -> let w2 = w1 in e1
1474 B -> let w2 = w1 in e2
1475 ...other cases .... }
1477 This is plain silly in the common case where w2 is dead.
1479 Even so, I can't see a good way to implement this idea. I tried
1480 not doing the binder-swap if the scrutinee was already evaluated
1481 but that failed big-time:
1485 case v of w { MkT x ->
1486 case x of x1 { I# y1 ->
1487 case x of x2 { I# y2 -> ...
1489 Notice that because MkT is strict, x is marked "evaluated". But to
1490 eliminate the last case, we must either make sure that x (as well as
1491 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1492 the binder-swap. So this whole note is a no-op.
1496 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1497 -> OutExpr -> InId -> OutId -> [InAlt]
1498 -> SimplM (SimplEnv, OutExpr, OutId)
1499 -- Note [Improving seq]
1500 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1501 | Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1502 = do { case_bndr2 <- newId (fsLit "nt") ty2
1503 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1504 env2 = extendIdSubst env case_bndr rhs
1505 ; return (env2, scrut `Cast` co, case_bndr2) }
1507 improveSeq _ env scrut _ case_bndr1 _
1508 = return (env, scrut, case_bndr1)
1511 improve_case_bndr env scrut case_bndr
1512 -- See Note [no-case-of-case]
1513 -- | switchIsOn (getSwitchChecker env) NoCaseOfCase
1514 -- = (env, case_bndr)
1516 | otherwise -- Failed try; see Note [Suppressing the case binder-swap]
1517 -- not (isEvaldUnfolding (idUnfolding v))
1519 Var v -> (modifyInScope env1 v case_bndr', case_bndr')
1520 -- Note about using modifyInScope for v here
1521 -- We could extend the substitution instead, but it would be
1522 -- a hack because then the substitution wouldn't be idempotent
1523 -- any more (v is an OutId). And this does just as well.
1525 Cast (Var v) co -> (addBinderUnfolding env1 v rhs, case_bndr')
1527 rhs = Cast (Var case_bndr') (mkSymCoercion co)
1529 _ -> (env, case_bndr)
1531 case_bndr' = zapIdOccInfo case_bndr
1532 env1 = modifyInScope env case_bndr case_bndr'
1537 simplAlts does two things:
1539 1. Eliminate alternatives that cannot match, including the
1540 DEFAULT alternative.
1542 2. If the DEFAULT alternative can match only one possible constructor,
1543 then make that constructor explicit.
1545 case e of x { DEFAULT -> rhs }
1547 case e of x { (a,b) -> rhs }
1548 where the type is a single constructor type. This gives better code
1549 when rhs also scrutinises x or e.
1551 Here "cannot match" includes knowledge from GADTs
1553 It's a good idea do do this stuff before simplifying the alternatives, to
1554 avoid simplifying alternatives we know can't happen, and to come up with
1555 the list of constructors that are handled, to put into the IdInfo of the
1556 case binder, for use when simplifying the alternatives.
1558 Eliminating the default alternative in (1) isn't so obvious, but it can
1561 data Colour = Red | Green | Blue
1570 DEFAULT -> [ case y of ... ]
1572 If we inline h into f, the default case of the inlined h can't happen.
1573 If we don't notice this, we may end up filtering out *all* the cases
1574 of the inner case y, which give us nowhere to go!
1578 simplAlts :: SimplEnv
1580 -> InId -- Case binder
1581 -> [InAlt] -- Non-empty
1583 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
1584 -- Like simplExpr, this just returns the simplified alternatives;
1585 -- it not return an environment
1587 simplAlts env scrut case_bndr alts cont'
1588 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1589 do { let env0 = zapFloats env
1591 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1593 ; fam_envs <- getFamEnvs
1594 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
1595 case_bndr case_bndr1 alts
1597 ; (imposs_deflt_cons, in_alts) <- prepareAlts alt_env' scrut' case_bndr' alts
1599 ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1600 ; return (scrut', case_bndr', alts') }
1602 ------------------------------------
1603 simplAlt :: SimplEnv
1604 -> [AltCon] -- These constructors can't be present when
1605 -- matching the DEFAULT alternative
1606 -> OutId -- The case binder
1611 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1612 = ASSERT( null bndrs )
1613 do { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1614 -- Record the constructors that the case-binder *can't* be.
1615 ; rhs' <- simplExprC env' rhs cont'
1616 ; return (DEFAULT, [], rhs') }
1618 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1619 = ASSERT( null bndrs )
1620 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1621 ; rhs' <- simplExprC env' rhs cont'
1622 ; return (LitAlt lit, [], rhs') }
1624 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1625 = do { -- Deal with the pattern-bound variables
1626 -- Mark the ones that are in ! positions in the
1627 -- data constructor as certainly-evaluated.
1628 -- NB: simplLamBinders preserves this eval info
1629 let vs_with_evals = add_evals (dataConRepStrictness con)
1630 ; (env', vs') <- simplLamBndrs env vs_with_evals
1632 -- Bind the case-binder to (con args)
1633 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1634 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1635 env'' = addBinderUnfolding env' case_bndr'
1636 (mkConApp con con_args)
1638 ; rhs' <- simplExprC env'' rhs cont'
1639 ; return (DataAlt con, vs', rhs') }
1641 -- add_evals records the evaluated-ness of the bound variables of
1642 -- a case pattern. This is *important*. Consider
1643 -- data T = T !Int !Int
1645 -- case x of { T a b -> T (a+1) b }
1647 -- We really must record that b is already evaluated so that we don't
1648 -- go and re-evaluate it when constructing the result.
1649 -- See Note [Data-con worker strictness] in MkId.lhs
1654 go (v:vs') strs | isTyVar v = v : go vs' strs
1655 go (v:vs') (str:strs)
1656 | isMarkedStrict str = evald_v : go vs' strs
1657 | otherwise = zapped_v : go vs' strs
1659 zapped_v = zap_occ_info v
1660 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1661 go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1663 -- See Note [zapOccInfo]
1664 -- zap_occ_info: if the case binder is alive, then we add the unfolding
1666 -- to the envt; so vs are now very much alive
1667 -- Note [Aug06] I can't see why this actually matters, but it's neater
1668 -- case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1669 -- ==> case e of t { (a,b) -> ...(a)... }
1670 -- Look, Ma, a is alive now.
1671 zap_occ_info | isDeadBinder case_bndr' = \ident -> ident
1672 | otherwise = zapIdOccInfo
1674 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1675 addBinderUnfolding env bndr rhs
1676 = modifyInScope env (bndr `setIdUnfolding` mkUnfolding False rhs)
1678 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1679 addBinderOtherCon env bndr cons
1680 = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1684 %************************************************************************
1686 \subsection{Known constructor}
1688 %************************************************************************
1690 We are a bit careful with occurrence info. Here's an example
1692 (\x* -> case x of (a*, b) -> f a) (h v, e)
1694 where the * means "occurs once". This effectively becomes
1695 case (h v, e) of (a*, b) -> f a)
1697 let a* = h v; b = e in f a
1701 All this should happen in one sweep.
1704 knownCon :: SimplEnv -> OutExpr -> AltCon
1705 -> [OutExpr] -- Args *including* the universal args
1706 -> InId -> [InAlt] -> SimplCont
1707 -> SimplM (SimplEnv, OutExpr)
1709 knownCon env scrut con args bndr alts cont
1710 = do { tick (KnownBranch bndr)
1711 ; knownAlt env scrut args bndr (findAlt con alts) cont }
1713 knownAlt :: SimplEnv -> OutExpr -> [OutExpr]
1714 -> InId -> (AltCon, [CoreBndr], InExpr) -> SimplCont
1715 -> SimplM (SimplEnv, OutExpr)
1716 knownAlt env scrut _ bndr (DEFAULT, bs, rhs) cont
1718 do { env' <- simplNonRecX env bndr scrut
1719 -- This might give rise to a binding with non-atomic args
1720 -- like x = Node (f x) (g x)
1721 -- but simplNonRecX will atomic-ify it
1722 ; simplExprF env' rhs cont }
1724 knownAlt env scrut _ bndr (LitAlt _, bs, rhs) cont
1726 do { env' <- simplNonRecX env bndr scrut
1727 ; simplExprF env' rhs cont }
1729 knownAlt env scrut the_args bndr (DataAlt dc, bs, rhs) cont
1730 = do { let dead_bndr = isDeadBinder bndr -- bndr is an InId
1731 n_drop_tys = length (dataConUnivTyVars dc)
1732 ; env' <- bind_args env dead_bndr bs (drop n_drop_tys the_args)
1734 -- It's useful to bind bndr to scrut, rather than to a fresh
1735 -- binding x = Con arg1 .. argn
1736 -- because very often the scrut is a variable, so we avoid
1737 -- creating, and then subsequently eliminating, a let-binding
1738 -- BUT, if scrut is a not a variable, we must be careful
1739 -- about duplicating the arg redexes; in that case, make
1740 -- a new con-app from the args
1741 bndr_rhs = case scrut of
1744 con_app = mkConApp dc (take n_drop_tys the_args ++ con_args)
1745 con_args = [substExpr env' (varToCoreExpr b) | b <- bs]
1746 -- args are aready OutExprs, but bs are InIds
1748 ; env'' <- simplNonRecX env' bndr bndr_rhs
1749 ; simplExprF env'' rhs cont }
1752 bind_args env' _ [] _ = return env'
1754 bind_args env' dead_bndr (b:bs') (Type ty : args)
1755 = ASSERT( isTyVar b )
1756 bind_args (extendTvSubst env' b ty) dead_bndr bs' args
1758 bind_args env' dead_bndr (b:bs') (arg : args)
1760 do { let b' = if dead_bndr then b else zapIdOccInfo b
1761 -- Note that the binder might be "dead", because it doesn't
1762 -- occur in the RHS; and simplNonRecX may therefore discard
1763 -- it via postInlineUnconditionally.
1764 -- Nevertheless we must keep it if the case-binder is alive,
1765 -- because it may be used in the con_app. See Note [zapOccInfo]
1766 ; env'' <- simplNonRecX env' b' arg
1767 ; bind_args env'' dead_bndr bs' args }
1770 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr the_args $$
1771 text "scrut:" <+> ppr scrut
1775 %************************************************************************
1777 \subsection{Duplicating continuations}
1779 %************************************************************************
1782 prepareCaseCont :: SimplEnv
1783 -> [InAlt] -> SimplCont
1784 -> SimplM (SimplEnv, SimplCont,SimplCont)
1785 -- Return a duplicatable continuation, a non-duplicable part
1786 -- plus some extra bindings (that scope over the entire
1789 -- No need to make it duplicatable if there's only one alternative
1790 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1791 prepareCaseCont env _ cont = mkDupableCont env cont
1795 mkDupableCont :: SimplEnv -> SimplCont
1796 -> SimplM (SimplEnv, SimplCont, SimplCont)
1798 mkDupableCont env cont
1799 | contIsDupable cont
1800 = return (env, cont, mkBoringStop)
1802 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1804 mkDupableCont env (CoerceIt ty cont)
1805 = do { (env', dup, nodup) <- mkDupableCont env cont
1806 ; return (env', CoerceIt ty dup, nodup) }
1808 mkDupableCont env cont@(StrictBind {})
1809 = return (env, mkBoringStop, cont)
1810 -- See Note [Duplicating strict continuations]
1812 mkDupableCont env cont@(StrictArg {})
1813 = return (env, mkBoringStop, cont)
1814 -- See Note [Duplicating strict continuations]
1816 mkDupableCont env (ApplyTo _ arg se cont)
1817 = -- e.g. [...hole...] (...arg...)
1819 -- let a = ...arg...
1820 -- in [...hole...] a
1821 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1822 ; arg' <- simplExpr (se `setInScope` env') arg
1823 ; (env'', arg'') <- makeTrivial env' arg'
1824 ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1825 ; return (env'', app_cont, nodup_cont) }
1827 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1828 -- See Note [Single-alternative case]
1829 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1830 -- | not (isDeadBinder case_bndr)
1831 | all isDeadBinder bs -- InIds
1832 && not (isUnLiftedType (idType case_bndr))
1833 -- Note [Single-alternative-unlifted]
1834 = return (env, mkBoringStop, cont)
1836 mkDupableCont env (Select _ case_bndr alts se cont)
1837 = -- e.g. (case [...hole...] of { pi -> ei })
1839 -- let ji = \xij -> ei
1840 -- in case [...hole...] of { pi -> ji xij }
1841 do { tick (CaseOfCase case_bndr)
1842 ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1843 -- NB: call mkDupableCont here, *not* prepareCaseCont
1844 -- We must make a duplicable continuation, whereas prepareCaseCont
1845 -- doesn't when there is a single case branch
1847 ; let alt_env = se `setInScope` env'
1848 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
1849 ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
1850 -- Safe to say that there are no handled-cons for the DEFAULT case
1851 -- NB: simplBinder does not zap deadness occ-info, so
1852 -- a dead case_bndr' will still advertise its deadness
1853 -- This is really important because in
1854 -- case e of b { (# p,q #) -> ... }
1855 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1856 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1857 -- In the new alts we build, we have the new case binder, so it must retain
1859 -- NB: we don't use alt_env further; it has the substEnv for
1860 -- the alternatives, and we don't want that
1862 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
1863 ; return (env'', -- Note [Duplicated env]
1864 Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
1868 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1869 -> SimplM (SimplEnv, [InAlt])
1870 -- Absorbs the continuation into the new alternatives
1872 mkDupableAlts env case_bndr' the_alts
1875 go env0 [] = return (env0, [])
1877 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
1878 ; (env2, alts') <- go env1 alts
1879 ; return (env2, alt' : alts' ) }
1881 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
1882 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
1883 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1884 | exprIsDupable rhs' -- Note [Small alternative rhs]
1885 = return (env, (con, bndrs', rhs'))
1887 = do { let rhs_ty' = exprType rhs'
1888 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1890 | isTyVar bndr = True -- Abstract over all type variables just in case
1891 | otherwise = not (isDeadBinder bndr)
1892 -- The deadness info on the new Ids is preserved by simplBinders
1894 ; (final_bndrs', final_args) -- Note [Join point abstraction]
1895 <- if (any isId used_bndrs')
1896 then return (used_bndrs', varsToCoreExprs used_bndrs')
1897 else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
1898 ; return ([rw_id], [Var realWorldPrimId]) }
1900 ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
1901 -- Note [Funky mkPiTypes]
1903 ; let -- We make the lambdas into one-shot-lambdas. The
1904 -- join point is sure to be applied at most once, and doing so
1905 -- prevents the body of the join point being floated out by
1906 -- the full laziness pass
1907 really_final_bndrs = map one_shot final_bndrs'
1908 one_shot v | isId v = setOneShotLambda v
1910 join_rhs = mkLams really_final_bndrs rhs'
1911 join_call = mkApps (Var join_bndr) final_args
1913 ; return (addPolyBind NotTopLevel env (NonRec join_bndr join_rhs), (con, bndrs', join_call)) }
1914 -- See Note [Duplicated env]
1917 Note [Duplicated env]
1918 ~~~~~~~~~~~~~~~~~~~~~
1919 Some of the alternatives are simplified, but have not been turned into a join point
1920 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
1921 bind the join point, because it might to do PostInlineUnconditionally, and
1922 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
1923 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1924 at worst delays the join-point inlining.
1926 Note [Small alterantive rhs]
1927 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1928 It is worth checking for a small RHS because otherwise we
1929 get extra let bindings that may cause an extra iteration of the simplifier to
1930 inline back in place. Quite often the rhs is just a variable or constructor.
1931 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1932 iterations because the version with the let bindings looked big, and so wasn't
1933 inlined, but after the join points had been inlined it looked smaller, and so
1936 NB: we have to check the size of rhs', not rhs.
1937 Duplicating a small InAlt might invalidate occurrence information
1938 However, if it *is* dupable, we return the *un* simplified alternative,
1939 because otherwise we'd need to pair it up with an empty subst-env....
1940 but we only have one env shared between all the alts.
1941 (Remember we must zap the subst-env before re-simplifying something).
1942 Rather than do this we simply agree to re-simplify the original (small) thing later.
1944 Note [Funky mkPiTypes]
1945 ~~~~~~~~~~~~~~~~~~~~~~
1946 Notice the funky mkPiTypes. If the contructor has existentials
1947 it's possible that the join point will be abstracted over
1948 type varaibles as well as term variables.
1949 Example: Suppose we have
1950 data T = forall t. C [t]
1952 case (case e of ...) of
1954 We get the join point
1955 let j :: forall t. [t] -> ...
1956 j = /\t \xs::[t] -> rhs
1958 case (case e of ...) of
1959 C t xs::[t] -> j t xs
1961 Note [Join point abstaction]
1962 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1963 If we try to lift a primitive-typed something out
1964 for let-binding-purposes, we will *caseify* it (!),
1965 with potentially-disastrous strictness results. So
1966 instead we turn it into a function: \v -> e
1967 where v::State# RealWorld#. The value passed to this function
1968 is realworld#, which generates (almost) no code.
1970 There's a slight infelicity here: we pass the overall
1971 case_bndr to all the join points if it's used in *any* RHS,
1972 because we don't know its usage in each RHS separately
1974 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1975 we make the join point into a function whenever used_bndrs'
1976 is empty. This makes the join-point more CPR friendly.
1977 Consider: let j = if .. then I# 3 else I# 4
1978 in case .. of { A -> j; B -> j; C -> ... }
1980 Now CPR doesn't w/w j because it's a thunk, so
1981 that means that the enclosing function can't w/w either,
1982 which is a lose. Here's the example that happened in practice:
1983 kgmod :: Int -> Int -> Int
1984 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1988 I have seen a case alternative like this:
1990 It's a bit silly to add the realWorld dummy arg in this case, making
1993 (the \v alone is enough to make CPR happy) but I think it's rare
1995 Note [Duplicating strict continuations]
1996 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1997 Do *not* duplicate StrictBind and StritArg continuations. We gain
1998 nothing by propagating them into the expressions, and we do lose a
1999 lot. Here's an example:
2000 && (case x of { T -> F; F -> T }) E
2001 Now, && is strict so we end up simplifying the case with
2002 an ArgOf continuation. If we let-bind it, we get
2004 let $j = \v -> && v E
2005 in simplExpr (case x of { T -> F; F -> T })
2007 And after simplifying more we get
2009 let $j = \v -> && v E
2010 in case x of { T -> $j F; F -> $j T }
2011 Which is a Very Bad Thing
2013 The desire not to duplicate is the entire reason that
2014 mkDupableCont returns a pair of continuations.
2016 The original plan had:
2017 e.g. (...strict-fn...) [...hole...]
2019 let $j = \a -> ...strict-fn...
2022 Note [Single-alternative cases]
2023 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2024 This case is just like the ArgOf case. Here's an example:
2028 case (case x of I# x' ->
2030 True -> I# (negate# x')
2031 False -> I# x') of y {
2033 Because the (case x) has only one alternative, we'll transform to
2035 case (case x' <# 0# of
2036 True -> I# (negate# x')
2037 False -> I# x') of y {
2039 But now we do *NOT* want to make a join point etc, giving
2041 let $j = \y -> MkT y
2043 True -> $j (I# (negate# x'))
2045 In this case the $j will inline again, but suppose there was a big
2046 strict computation enclosing the orginal call to MkT. Then, it won't
2047 "see" the MkT any more, because it's big and won't get duplicated.
2048 And, what is worse, nothing was gained by the case-of-case transform.
2050 When should use this case of mkDupableCont?
2051 However, matching on *any* single-alternative case is a *disaster*;
2052 e.g. case (case ....) of (a,b) -> (# a,b #)
2053 We must push the outer case into the inner one!
2056 * Match [(DEFAULT,_,_)], but in the common case of Int,
2057 the alternative-filling-in code turned the outer case into
2058 case (...) of y { I# _ -> MkT y }
2060 * Match on single alternative plus (not (isDeadBinder case_bndr))
2061 Rationale: pushing the case inwards won't eliminate the construction.
2062 But there's a risk of
2063 case (...) of y { (a,b) -> let z=(a,b) in ... }
2064 Now y looks dead, but it'll come alive again. Still, this
2065 seems like the best option at the moment.
2067 * Match on single alternative plus (all (isDeadBinder bndrs))
2068 Rationale: this is essentially seq.
2070 * Match when the rhs is *not* duplicable, and hence would lead to a
2071 join point. This catches the disaster-case above. We can test
2072 the *un-simplified* rhs, which is fine. It might get bigger or
2073 smaller after simplification; if it gets smaller, this case might
2074 fire next time round. NB also that we must test contIsDupable
2075 case_cont *btoo, because case_cont might be big!
2077 HOWEVER: I found that this version doesn't work well, because
2078 we can get let x = case (...) of { small } in ...case x...
2079 When x is inlined into its full context, we find that it was a bad
2080 idea to have pushed the outer case inside the (...) case.
2082 Note [Single-alternative-unlifted]
2083 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2084 Here's another single-alternative where we really want to do case-of-case:
2092 case y_s6X of tpl_s7m {
2093 M1.Mk1 ipv_s70 -> ipv_s70;
2094 M1.Mk2 ipv_s72 -> ipv_s72;
2100 case x_s74 of tpl_s7n {
2101 M1.Mk1 ipv_s77 -> ipv_s77;
2102 M1.Mk2 ipv_s79 -> ipv_s79;
2106 { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2110 So the outer case is doing *nothing at all*, other than serving as a
2111 join-point. In this case we really want to do case-of-case and decide
2112 whether to use a real join point or just duplicate the continuation.
2114 Hence: check whether the case binder's type is unlifted, because then
2115 the outer case is *not* a seq.