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, substTyVar )
16 import FamInstEnv ( FamInstEnv )
18 import MkId ( mkImpossibleExpr, seqId )
21 import Name ( mkSystemVarName, isExternalName )
23 import OptCoercion ( optCoercion )
24 import FamInstEnv ( topNormaliseType )
25 import DataCon ( DataCon, dataConWorkId, dataConRepStrictness )
26 import CoreMonad ( SimplifierSwitch(..), Tick(..) )
28 import Demand ( isStrictDmd, splitStrictSig )
29 import PprCore ( pprParendExpr, pprCoreExpr )
30 import CoreUnfold ( mkUnfolding, mkCoreUnfolding, mkInlineRule,
31 exprIsConApp_maybe, callSiteInline, CallCtxt(..) )
33 import qualified CoreSubst
34 import CoreArity ( exprArity )
35 import Rules ( lookupRule, getRules )
36 import BasicTypes ( isMarkedStrict, Arity )
37 import CostCentre ( currentCCS, pushCCisNop )
38 import TysPrim ( realWorldStatePrimTy )
39 import PrelInfo ( realWorldPrimId )
40 import BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) )
41 import MonadUtils ( foldlM, mapAccumLM )
42 import Maybes ( orElse )
43 import Data.List ( mapAccumL )
49 The guts of the simplifier is in this module, but the driver loop for
50 the simplifier is in SimplCore.lhs.
53 -----------------------------------------
54 *** IMPORTANT NOTE ***
55 -----------------------------------------
56 The simplifier used to guarantee that the output had no shadowing, but
57 it does not do so any more. (Actually, it never did!) The reason is
58 documented with simplifyArgs.
61 -----------------------------------------
62 *** IMPORTANT NOTE ***
63 -----------------------------------------
64 Many parts of the simplifier return a bunch of "floats" as well as an
65 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
67 All "floats" are let-binds, not case-binds, but some non-rec lets may
68 be unlifted (with RHS ok-for-speculation).
72 -----------------------------------------
73 ORGANISATION OF FUNCTIONS
74 -----------------------------------------
76 - simplify all top-level binders
77 - for NonRec, call simplRecOrTopPair
78 - for Rec, call simplRecBind
81 ------------------------------
82 simplExpr (applied lambda) ==> simplNonRecBind
83 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
84 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
86 ------------------------------
87 simplRecBind [binders already simplfied]
88 - use simplRecOrTopPair on each pair in turn
90 simplRecOrTopPair [binder already simplified]
91 Used for: recursive bindings (top level and nested)
92 top-level non-recursive bindings
94 - check for PreInlineUnconditionally
98 Used for: non-top-level non-recursive bindings
99 beta reductions (which amount to the same thing)
100 Because it can deal with strict arts, it takes a
101 "thing-inside" and returns an expression
103 - check for PreInlineUnconditionally
104 - simplify binder, including its IdInfo
113 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
114 Used for: binding case-binder and constr args in a known-constructor case
115 - check for PreInLineUnconditionally
119 ------------------------------
120 simplLazyBind: [binder already simplified, RHS not]
121 Used for: recursive bindings (top level and nested)
122 top-level non-recursive bindings
123 non-top-level, but *lazy* non-recursive bindings
124 [must not be strict or unboxed]
125 Returns floats + an augmented environment, not an expression
126 - substituteIdInfo and add result to in-scope
127 [so that rules are available in rec rhs]
130 - float if exposes constructor or PAP
134 completeNonRecX: [binder and rhs both simplified]
135 - if the the thing needs case binding (unlifted and not ok-for-spec)
141 completeBind: [given a simplified RHS]
142 [used for both rec and non-rec bindings, top level and not]
143 - try PostInlineUnconditionally
144 - add unfolding [this is the only place we add an unfolding]
149 Right hand sides and arguments
150 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
151 In many ways we want to treat
152 (a) the right hand side of a let(rec), and
153 (b) a function argument
154 in the same way. But not always! In particular, we would
155 like to leave these arguments exactly as they are, so they
156 will match a RULE more easily.
161 It's harder to make the rule match if we ANF-ise the constructor,
162 or eta-expand the PAP:
164 f (let { a = g x; b = h x } in (a,b))
167 On the other hand if we see the let-defns
172 then we *do* want to ANF-ise and eta-expand, so that p and q
173 can be safely inlined.
175 Even floating lets out is a bit dubious. For let RHS's we float lets
176 out if that exposes a value, so that the value can be inlined more vigorously.
179 r = let x = e in (x,x)
181 Here, if we float the let out we'll expose a nice constructor. We did experiments
182 that showed this to be a generally good thing. But it was a bad thing to float
183 lets out unconditionally, because that meant they got allocated more often.
185 For function arguments, there's less reason to expose a constructor (it won't
186 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
187 So for the moment we don't float lets out of function arguments either.
192 For eta expansion, we want to catch things like
194 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
196 If the \x was on the RHS of a let, we'd eta expand to bring the two
197 lambdas together. And in general that's a good thing to do. Perhaps
198 we should eta expand wherever we find a (value) lambda? Then the eta
199 expansion at a let RHS can concentrate solely on the PAP case.
202 %************************************************************************
204 \subsection{Bindings}
206 %************************************************************************
209 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
211 simplTopBinds env0 binds0
212 = do { -- Put all the top-level binders into scope at the start
213 -- so that if a transformation rule has unexpectedly brought
214 -- anything into scope, then we don't get a complaint about that.
215 -- It's rather as if the top-level binders were imported.
216 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
217 ; dflags <- getDOptsSmpl
218 ; let dump_flag = dopt Opt_D_verbose_core2core dflags
219 ; env2 <- simpl_binds dump_flag env1 binds0
220 ; freeTick SimplifierDone
223 -- We need to track the zapped top-level binders, because
224 -- they should have their fragile IdInfo zapped (notably occurrence info)
225 -- That's why we run down binds and bndrs' simultaneously.
227 -- The dump-flag emits a trace for each top-level binding, which
228 -- helps to locate the tracing for inlining and rule firing
229 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
230 simpl_binds _ env [] = return env
231 simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
233 ; simpl_binds dump env' binds }
235 trace_bind True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
236 trace_bind False _ = \x -> x
238 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
239 simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
241 (env', b') = addBndrRules env b (lookupRecBndr env b)
245 %************************************************************************
247 \subsection{Lazy bindings}
249 %************************************************************************
251 simplRecBind is used for
252 * recursive bindings only
255 simplRecBind :: SimplEnv -> TopLevelFlag
258 simplRecBind env0 top_lvl pairs0
259 = do { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
260 ; env1 <- go (zapFloats env_with_info) triples
261 ; return (env0 `addRecFloats` env1) }
262 -- addFloats adds the floats from env1,
263 -- _and_ updates env0 with the in-scope set from env1
265 add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
266 -- Add the (substituted) rules to the binder
267 add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
269 (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
271 go env [] = return env
273 go env ((old_bndr, new_bndr, rhs) : pairs)
274 = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
278 simplOrTopPair is used for
279 * recursive bindings (whether top level or not)
280 * top-level non-recursive bindings
282 It assumes the binder has already been simplified, but not its IdInfo.
285 simplRecOrTopPair :: SimplEnv
287 -> InId -> OutBndr -> InExpr -- Binder and rhs
288 -> SimplM SimplEnv -- Returns an env that includes the binding
290 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
291 | preInlineUnconditionally env top_lvl old_bndr rhs -- Check for unconditional inline
292 = do { tick (PreInlineUnconditionally old_bndr)
293 ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
296 = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
297 -- May not actually be recursive, but it doesn't matter
301 simplLazyBind is used for
302 * [simplRecOrTopPair] recursive bindings (whether top level or not)
303 * [simplRecOrTopPair] top-level non-recursive bindings
304 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
307 1. It assumes that the binder is *already* simplified,
308 and is in scope, and its IdInfo too, except unfolding
310 2. It assumes that the binder type is lifted.
312 3. It does not check for pre-inline-unconditionallly;
313 that should have been done already.
316 simplLazyBind :: SimplEnv
317 -> TopLevelFlag -> RecFlag
318 -> InId -> OutId -- Binder, both pre-and post simpl
319 -- The OutId has IdInfo, except arity, unfolding
320 -> InExpr -> SimplEnv -- The RHS and its environment
323 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
324 = do { let rhs_env = rhs_se `setInScope` env
325 (tvs, body) = case collectTyBinders rhs of
326 (tvs, body) | not_lam body -> (tvs,body)
327 | otherwise -> ([], rhs)
328 not_lam (Lam _ _) = False
330 -- Do not do the "abstract tyyvar" thing if there's
331 -- a lambda inside, becuase it defeats eta-reduction
332 -- f = /\a. \x. g a x
335 ; (body_env, tvs') <- simplBinders rhs_env tvs
336 -- See Note [Floating and type abstraction] in SimplUtils
339 ; (body_env1, body1) <- simplExprF body_env body mkRhsStop
340 -- ANF-ise a constructor or PAP rhs
341 ; (body_env2, body2) <- prepareRhs body_env1 bndr1 body1
344 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
345 then -- No floating, just wrap up!
346 do { rhs' <- mkLam env tvs' (wrapFloats body_env2 body2)
347 ; return (env, rhs') }
349 else if null tvs then -- Simple floating
350 do { tick LetFloatFromLet
351 ; return (addFloats env body_env2, body2) }
353 else -- Do type-abstraction first
354 do { tick LetFloatFromLet
355 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
356 ; rhs' <- mkLam env tvs' body3
357 ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
358 ; return (env', rhs') }
360 ; completeBind env' top_lvl bndr bndr1 rhs' }
363 A specialised variant of simplNonRec used when the RHS is already simplified,
364 notably in knownCon. It uses case-binding where necessary.
367 simplNonRecX :: SimplEnv
368 -> InId -- Old binder
369 -> OutExpr -- Simplified RHS
372 simplNonRecX env bndr new_rhs
373 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
374 = return env -- Here b is dead, and we avoid creating
375 | otherwise -- the binding b = (a,b)
376 = do { (env', bndr') <- simplBinder env bndr
377 ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
379 completeNonRecX :: SimplEnv
381 -> InId -- Old binder
382 -> OutId -- New binder
383 -> OutExpr -- Simplified RHS
386 completeNonRecX env is_strict old_bndr new_bndr new_rhs
387 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_bndr new_rhs
389 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
390 then do { tick LetFloatFromLet
391 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
392 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
393 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
396 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
397 Doing so risks exponential behaviour, because new_rhs has been simplified once already
398 In the cases described by the folowing commment, postInlineUnconditionally will
399 catch many of the relevant cases.
400 -- This happens; for example, the case_bndr during case of
401 -- known constructor: case (a,b) of x { (p,q) -> ... }
402 -- Here x isn't mentioned in the RHS, so we don't want to
403 -- create the (dead) let-binding let x = (a,b) in ...
405 -- Similarly, single occurrences can be inlined vigourously
406 -- e.g. case (f x, g y) of (a,b) -> ....
407 -- If a,b occur once we can avoid constructing the let binding for them.
409 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
410 -- Consider case I# (quotInt# x y) of
411 -- I# v -> let w = J# v in ...
412 -- If we gaily inline (quotInt# x y) for v, we end up building an
414 -- let w = J# (quotInt# x y) in ...
415 -- because quotInt# can fail.
417 | preInlineUnconditionally env NotTopLevel bndr new_rhs
418 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
421 ----------------------------------
422 prepareRhs takes a putative RHS, checks whether it's a PAP or
423 constructor application and, if so, converts it to ANF, so that the
424 resulting thing can be inlined more easily. Thus
431 We also want to deal well cases like this
432 v = (f e1 `cast` co) e2
433 Here we want to make e1,e2 trivial and get
434 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
435 That's what the 'go' loop in prepareRhs does
438 prepareRhs :: SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
439 -- Adds new floats to the env iff that allows us to return a good RHS
440 prepareRhs env id (Cast rhs co) -- Note [Float coercions]
441 | (ty1, _ty2) <- coercionKind co -- Do *not* do this if rhs has an unlifted type
442 , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
443 = do { (env', rhs') <- makeTrivialWithInfo env sanitised_info rhs
444 ; return (env', Cast rhs' co) }
446 sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
447 `setDemandInfo` demandInfo info
450 prepareRhs env0 _ rhs0
451 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
452 ; return (env1, rhs1) }
454 go n_val_args env (Cast rhs co)
455 = do { (is_exp, env', rhs') <- go n_val_args env rhs
456 ; return (is_exp, env', Cast rhs' co) }
457 go n_val_args env (App fun (Type ty))
458 = do { (is_exp, env', rhs') <- go n_val_args env fun
459 ; return (is_exp, env', App rhs' (Type ty)) }
460 go n_val_args env (App fun arg)
461 = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
463 True -> do { (env'', arg') <- makeTrivial env' arg
464 ; return (True, env'', App fun' arg') }
465 False -> return (False, env, App fun arg) }
466 go n_val_args env (Var fun)
467 = return (is_exp, env, Var fun)
469 is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
470 -- See Note [CONLIKE pragma] in BasicTypes
471 -- The definition of is_exp should match that in
472 -- OccurAnal.occAnalApp
475 = return (False, env, other)
479 Note [Float coercions]
480 ~~~~~~~~~~~~~~~~~~~~~~
481 When we find the binding
483 we'd like to transform it to
485 x = x `cast` co -- A trivial binding
486 There's a chance that e will be a constructor application or function, or something
487 like that, so moving the coerion to the usage site may well cancel the coersions
488 and lead to further optimisation. Example:
491 data instance T Int = T Int
493 foo :: Int -> Int -> Int
498 go n = case x of { T m -> go (n-m) }
499 -- This case should optimise
501 Note [Preserve strictness when floating coercions]
502 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
503 In the Note [Float coercions] transformation, keep the strictness info.
505 f = e `cast` co -- f has strictness SSL
507 f' = e -- f' also has strictness SSL
508 f = f' `cast` co -- f still has strictness SSL
510 Its not wrong to drop it on the floor, but better to keep it.
512 Note [Float coercions (unlifted)]
513 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
514 BUT don't do [Float coercions] if 'e' has an unlifted type.
517 foo :: Int = (error (# Int,Int #) "urk")
518 `cast` CoUnsafe (# Int,Int #) Int
520 If do the makeTrivial thing to the error call, we'll get
521 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
522 But 'v' isn't in scope!
524 These strange casts can happen as a result of case-of-case
525 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
530 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
531 -- Binds the expression to a variable, if it's not trivial, returning the variable
532 makeTrivial env expr = makeTrivialWithInfo env vanillaIdInfo expr
534 makeTrivialWithInfo :: SimplEnv -> IdInfo -> OutExpr -> SimplM (SimplEnv, OutExpr)
535 -- Propagate strictness and demand info to the new binder
536 -- Note [Preserve strictness when floating coercions]
537 -- Returned SimplEnv has same substitution as incoming one
538 makeTrivialWithInfo env info expr
541 | otherwise -- See Note [Take care] below
542 = do { uniq <- getUniqueM
543 ; let name = mkSystemVarName uniq (fsLit "a")
544 var = mkLocalIdWithInfo name (exprType expr) info
545 ; env' <- completeNonRecX env False var var expr
546 ; expr' <- simplVar env' var
547 ; return (env', expr') }
548 -- The simplVar is needed becase we're constructing a new binding
550 -- And if rhs is of form (rhs1 |> co), then we might get
553 -- and now a's RHS is trivial and can be substituted out, and that
554 -- is what completeNonRecX will do
555 -- To put it another way, it's as if we'd simplified
556 -- let var = e in var
560 %************************************************************************
562 \subsection{Completing a lazy binding}
564 %************************************************************************
567 * deals only with Ids, not TyVars
568 * takes an already-simplified binder and RHS
569 * is used for both recursive and non-recursive bindings
570 * is used for both top-level and non-top-level bindings
572 It does the following:
573 - tries discarding a dead binding
574 - tries PostInlineUnconditionally
575 - add unfolding [this is the only place we add an unfolding]
578 It does *not* attempt to do let-to-case. Why? Because it is used for
579 - top-level bindings (when let-to-case is impossible)
580 - many situations where the "rhs" is known to be a WHNF
581 (so let-to-case is inappropriate).
583 Nor does it do the atomic-argument thing
586 completeBind :: SimplEnv
587 -> TopLevelFlag -- Flag stuck into unfolding
588 -> InId -- Old binder
589 -> OutId -> OutExpr -- New binder and RHS
591 -- completeBind may choose to do its work
592 -- * by extending the substitution (e.g. let x = y in ...)
593 -- * or by adding to the floats in the envt
595 completeBind env top_lvl old_bndr new_bndr new_rhs
596 = do { let old_info = idInfo old_bndr
597 old_unf = unfoldingInfo old_info
598 occ_info = occInfo old_info
600 ; new_unfolding <- simplUnfolding env top_lvl old_bndr occ_info new_rhs old_unf
602 ; if postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs new_unfolding
603 -- Inline and discard the binding
604 then do { tick (PostInlineUnconditionally old_bndr)
605 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> equals <+> ppr new_rhs) $
606 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
607 -- Use the substitution to make quite, quite sure that the
608 -- substitution will happen, since we are going to discard the binding
610 else return (addNonRecWithUnf env new_bndr new_rhs new_unfolding) }
612 ------------------------------
613 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
614 -- Add a new binding to the environment, complete with its unfolding
615 -- but *do not* do postInlineUnconditionally, because we have already
616 -- processed some of the scope of the binding
617 -- We still want the unfolding though. Consider
619 -- x = /\a. let y = ... in Just y
621 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
622 -- but 'x' may well then be inlined in 'body' in which case we'd like the
623 -- opportunity to inline 'y' too.
625 addPolyBind top_lvl env (NonRec poly_id rhs)
626 = do { unfolding <- simplUnfolding env top_lvl poly_id NoOccInfo rhs noUnfolding
627 -- Assumes that poly_id did not have an INLINE prag
628 -- which is perhaps wrong. ToDo: think about this
629 ; return (addNonRecWithUnf env poly_id rhs unfolding) }
631 addPolyBind _ env bind@(Rec _) = return (extendFloats env bind)
632 -- Hack: letrecs are more awkward, so we extend "by steam"
633 -- without adding unfoldings etc. At worst this leads to
634 -- more simplifier iterations
636 ------------------------------
637 addNonRecWithUnf :: SimplEnv
638 -> OutId -> OutExpr -- New binder and RHS
639 -> Unfolding -- New unfolding
641 addNonRecWithUnf env new_bndr new_rhs new_unfolding
642 = let new_arity = exprArity new_rhs
643 old_arity = idArity new_bndr
644 info1 = idInfo new_bndr `setArityInfo` new_arity
646 -- Unfolding info: Note [Setting the new unfolding]
647 info2 = info1 `setUnfoldingInfo` new_unfolding
649 -- Demand info: Note [Setting the demand info]
650 info3 | isEvaldUnfolding new_unfolding = zapDemandInfo info2 `orElse` info2
653 final_id = new_bndr `setIdInfo` info3
654 dmd_arity = length $ fst $ splitStrictSig $ idStrictness new_bndr
656 ASSERT( isId new_bndr )
657 WARN( new_arity < old_arity || new_arity < dmd_arity,
658 (ptext (sLit "Arity decrease:") <+> (ppr final_id <+> ppr old_arity
659 <+> ppr new_arity <+> ppr dmd_arity) $$ ppr new_rhs) )
660 -- Note [Arity decrease]
662 final_id `seq` -- This seq forces the Id, and hence its IdInfo,
663 -- and hence any inner substitutions
664 -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
665 addNonRec env final_id new_rhs
666 -- The addNonRec adds it to the in-scope set too
668 ------------------------------
669 simplUnfolding :: SimplEnv-> TopLevelFlag
671 -> OccInfo -> OutExpr
672 -> Unfolding -> SimplM Unfolding
673 -- Note [Setting the new unfolding]
674 simplUnfolding env _ _ _ _ (DFunUnfolding con ops)
675 = return (DFunUnfolding con ops')
677 ops' = map (substExpr (text "simplUnfolding") env) ops
679 simplUnfolding env top_lvl id _ _
680 (CoreUnfolding { uf_tmpl = expr, uf_arity = arity
681 , uf_src = src, uf_guidance = guide })
682 | isInlineRuleSource src
683 = do { expr' <- simplExpr rule_env expr
684 ; let src' = CoreSubst.substUnfoldingSource (mkCoreSubst (text "inline-unf") env) src
685 ; return (mkCoreUnfolding (isTopLevel top_lvl) src' expr' arity guide) }
686 -- See Note [Top-level flag on inline rules] in CoreUnfold
688 act = idInlineActivation id
689 rule_env = updMode (updModeForInlineRules act) env
690 -- See Note [Simplifying gently inside InlineRules] in SimplUtils
692 simplUnfolding _ top_lvl id _occ_info new_rhs _
693 = return (mkUnfolding (isTopLevel top_lvl) (isBottomingId id) new_rhs)
694 -- We make an unfolding *even for loop-breakers*.
695 -- Reason: (a) It might be useful to know that they are WHNF
696 -- (b) In TidyPgm we currently assume that, if we want to
697 -- expose the unfolding then indeed we *have* an unfolding
698 -- to expose. (We could instead use the RHS, but currently
699 -- we don't.) The simple thing is always to have one.
702 Note [Arity decrease]
703 ~~~~~~~~~~~~~~~~~~~~~
704 Generally speaking the arity of a binding should not decrease. But it *can*
705 legitimately happen becuase of RULES. Eg
707 where g has arity 2, will have arity 2. But if there's a rewrite rule
709 where h has arity 1, then f's arity will decrease. Here's a real-life example,
710 which is in the output of Specialise:
713 $dm {Arity 2} = \d.\x. op d
714 {-# RULES forall d. $dm Int d = $s$dm #-}
716 dInt = MkD .... opInt ...
717 opInt {Arity 1} = $dm dInt
719 $s$dm {Arity 0} = \x. op dInt }
721 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
722 That's why Specialise goes to a little trouble to pin the right arity
723 on specialised functions too.
725 Note [Setting the new unfolding]
726 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
727 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
728 should do nothing at all, but simplifying gently might get rid of
731 * If not, we make an unfolding from the new RHS. But *only* for
732 non-loop-breakers. Making loop breakers not have an unfolding at all
733 means that we can avoid tests in exprIsConApp, for example. This is
734 important: if exprIsConApp says 'yes' for a recursive thing, then we
735 can get into an infinite loop
737 If there's an InlineRule on a loop breaker, we hang on to the inlining.
738 It's pretty dodgy, but the user did say 'INLINE'. May need to revisit
741 Note [Setting the demand info]
742 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
743 If the unfolding is a value, the demand info may
744 go pear-shaped, so we nuke it. Example:
746 case x of (p,q) -> h p q x
747 Here x is certainly demanded. But after we've nuked
748 the case, we'll get just
749 let x = (a,b) in h a b x
750 and now x is not demanded (I'm assuming h is lazy)
751 This really happens. Similarly
752 let f = \x -> e in ...f..f...
753 After inlining f at some of its call sites the original binding may
754 (for example) be no longer strictly demanded.
755 The solution here is a bit ad hoc...
758 %************************************************************************
760 \subsection[Simplify-simplExpr]{The main function: simplExpr}
762 %************************************************************************
764 The reason for this OutExprStuff stuff is that we want to float *after*
765 simplifying a RHS, not before. If we do so naively we get quadratic
766 behaviour as things float out.
768 To see why it's important to do it after, consider this (real) example:
782 a -- Can't inline a this round, cos it appears twice
786 Each of the ==> steps is a round of simplification. We'd save a
787 whole round if we float first. This can cascade. Consider
792 let f = let d1 = ..d.. in \y -> e
796 in \x -> ...(\y ->e)...
798 Only in this second round can the \y be applied, and it
799 might do the same again.
803 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
804 simplExpr env expr = simplExprC env expr mkBoringStop
806 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
807 -- Simplify an expression, given a continuation
808 simplExprC env expr cont
809 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
810 do { (env', expr') <- simplExprF (zapFloats env) expr cont
811 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
812 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
813 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
814 return (wrapFloats env' expr') }
816 --------------------------------------------------
817 simplExprF :: SimplEnv -> InExpr -> SimplCont
818 -> SimplM (SimplEnv, OutExpr)
820 simplExprF env e cont
821 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
822 simplExprF' env e cont
824 simplExprF' :: SimplEnv -> InExpr -> SimplCont
825 -> SimplM (SimplEnv, OutExpr)
826 simplExprF' env (Var v) cont = simplVarF env v cont
827 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
828 simplExprF' env (Note n expr) cont = simplNote env n expr cont
829 simplExprF' env (Cast body co) cont = simplCast env body co cont
830 simplExprF' env (App fun arg) cont = simplExprF env fun $
831 ApplyTo NoDup arg env cont
833 simplExprF' env expr@(Lam _ _) cont
834 = simplLam env (map zap bndrs) body cont
835 -- The main issue here is under-saturated lambdas
836 -- (\x1. \x2. e) arg1
837 -- Here x1 might have "occurs-once" occ-info, because occ-info
838 -- is computed assuming that a group of lambdas is applied
839 -- all at once. If there are too few args, we must zap the
842 n_args = countArgs cont
843 n_params = length bndrs
844 (bndrs, body) = collectBinders expr
845 zap | n_args >= n_params = \b -> b
846 | otherwise = \b -> if isTyVar b then b
848 -- NB: we count all the args incl type args
849 -- so we must count all the binders (incl type lambdas)
851 simplExprF' env (Type ty) cont
852 = ASSERT( contIsRhsOrArg cont )
853 do { ty' <- simplCoercion env ty
854 ; rebuild env (Type ty') cont }
856 simplExprF' env (Case scrut bndr _ alts) cont
857 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
858 = -- Simplify the scrutinee with a Select continuation
859 simplExprF env scrut (Select NoDup bndr alts env cont)
862 = -- If case-of-case is off, simply simplify the case expression
863 -- in a vanilla Stop context, and rebuild the result around it
864 do { case_expr' <- simplExprC env scrut case_cont
865 ; rebuild env case_expr' cont }
867 case_cont = Select NoDup bndr alts env mkBoringStop
869 simplExprF' env (Let (Rec pairs) body) cont
870 = do { env' <- simplRecBndrs env (map fst pairs)
871 -- NB: bndrs' don't have unfoldings or rules
872 -- We add them as we go down
874 ; env'' <- simplRecBind env' NotTopLevel pairs
875 ; simplExprF env'' body cont }
877 simplExprF' env (Let (NonRec bndr rhs) body) cont
878 = simplNonRecE env bndr (rhs, env) ([], body) cont
880 ---------------------------------
881 simplType :: SimplEnv -> InType -> SimplM OutType
882 -- Kept monadic just so we can do the seqType
884 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
885 seqType new_ty `seq` return new_ty
887 new_ty = substTy env ty
889 ---------------------------------
890 simplCoercion :: SimplEnv -> InType -> SimplM OutType
891 -- The InType isn't *necessarily* a coercion, but it might be
892 -- (in a type application, say) and optCoercion is a no-op on types
894 = seqType new_co `seq` return new_co
896 new_co = optCoercion (getTvSubst env) co
900 %************************************************************************
902 \subsection{The main rebuilder}
904 %************************************************************************
907 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
908 -- At this point the substitution in the SimplEnv should be irrelevant
909 -- only the in-scope set and floats should matter
910 rebuild env expr cont0
911 = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
913 Stop {} -> return (env, expr)
914 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
915 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
916 StrictArg info _ cont -> rebuildCall env (info `addArgTo` expr) cont
917 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
918 ; simplLam env' bs body cont }
919 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
920 ; rebuild env (App expr arg') cont }
924 %************************************************************************
928 %************************************************************************
931 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
932 -> SimplM (SimplEnv, OutExpr)
933 simplCast env body co0 cont0
934 = do { co1 <- simplCoercion env co0
935 ; simplExprF env body (addCoerce co1 cont0) }
937 addCoerce co cont = add_coerce co (coercionKind co) cont
939 add_coerce _co (s1, k1) cont -- co :: ty~ty
940 | s1 `coreEqType` k1 = cont -- is a no-op
942 add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
943 | (_l1, t1) <- coercionKind co2
944 -- e |> (g1 :: S1~L) |> (g2 :: L~T1)
947 -- e |> (g1 . g2 :: S1~T1) otherwise
949 -- For example, in the initial form of a worker
950 -- we may find (coerce T (coerce S (\x.e))) y
951 -- and we'd like it to simplify to e[y/x] in one round
953 , s1 `coreEqType` t1 = cont -- The coerces cancel out
954 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
956 add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
957 -- (f |> g) ty ---> (f ty) |> (g @ ty)
958 -- This implements the PushT and PushC rules from the paper
959 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
961 (new_arg_ty, new_cast)
962 | isCoVar tyvar = (new_arg_co, mkCselRCoercion co) -- PushC rule
963 | otherwise = (ty', mkInstCoercion co ty') -- PushT rule
965 ApplyTo dup (Type new_arg_ty) (zapSubstEnv arg_se) (addCoerce new_cast cont)
967 ty' = substTy (arg_se `setInScope` env) arg_ty
968 new_arg_co = mkCsel1Coercion co `mkTransCoercion`
969 ty' `mkTransCoercion`
970 mkSymCoercion (mkCsel2Coercion co)
972 add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
973 | not (isTypeArg arg) -- This implements the Push rule from the paper
974 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
975 -- (e |> (g :: s1s2 ~ t1->t2)) f
977 -- (e (f |> (arg g :: t1~s1))
978 -- |> (res g :: s2->t2)
980 -- t1t2 must be a function type, t1->t2, because it's applied
981 -- to something but s1s2 might conceivably not be
983 -- When we build the ApplyTo we can't mix the out-types
984 -- with the InExpr in the argument, so we simply substitute
985 -- to make it all consistent. It's a bit messy.
986 -- But it isn't a common case.
988 -- Example of use: Trac #995
989 = ApplyTo dup new_arg (zapSubstEnv arg_se) (addCoerce co2 cont)
991 -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
992 -- t2 ~ s2 with left and right on the curried form:
993 -- (->) t1 t2 ~ (->) s1 s2
994 [co1, co2] = decomposeCo 2 co
995 new_arg = mkCoerce (mkSymCoercion co1) arg'
996 arg' = substExpr (text "move-cast") (arg_se `setInScope` env) arg
998 add_coerce co _ cont = CoerceIt co cont
1002 %************************************************************************
1004 \subsection{Lambdas}
1006 %************************************************************************
1009 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1010 -> SimplM (SimplEnv, OutExpr)
1012 simplLam env [] body cont = simplExprF env body cont
1015 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
1016 = do { tick (BetaReduction bndr)
1017 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
1019 -- Not enough args, so there are real lambdas left to put in the result
1020 simplLam env bndrs body cont
1021 = do { (env', bndrs') <- simplLamBndrs env bndrs
1022 ; body' <- simplExpr env' body
1023 ; new_lam <- mkLam env' bndrs' body'
1024 ; rebuild env' new_lam cont }
1027 simplNonRecE :: SimplEnv
1028 -> InBndr -- The binder
1029 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1030 -> ([InBndr], InExpr) -- Body of the let/lambda
1033 -> SimplM (SimplEnv, OutExpr)
1035 -- simplNonRecE is used for
1036 -- * non-top-level non-recursive lets in expressions
1039 -- It deals with strict bindings, via the StrictBind continuation,
1040 -- which may abort the whole process
1042 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1043 -- representing a lambda; so we recurse back to simplLam
1044 -- Why? Because of the binder-occ-info-zapping done before
1045 -- the call to simplLam in simplExprF (Lam ...)
1047 -- First deal with type applications and type lets
1048 -- (/\a. e) (Type ty) and (let a = Type ty in e)
1049 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1050 = ASSERT( isTyVar bndr )
1051 do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1052 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1054 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1055 | preInlineUnconditionally env NotTopLevel bndr rhs
1056 = do { tick (PreInlineUnconditionally bndr)
1057 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1060 = do { simplExprF (rhs_se `setFloats` env) rhs
1061 (StrictBind bndr bndrs body env cont) }
1064 = ASSERT( not (isTyVar bndr) )
1065 do { (env1, bndr1) <- simplNonRecBndr env bndr
1066 ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
1067 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1068 ; simplLam env3 bndrs body cont }
1072 %************************************************************************
1076 %************************************************************************
1079 -- Hack alert: we only distinguish subsumed cost centre stacks for the
1080 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
1081 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
1082 -> SimplM (SimplEnv, OutExpr)
1083 simplNote env (SCC cc) e cont
1084 | pushCCisNop cc (getEnclosingCC env) -- scc "f" (...(scc "f" e)...)
1085 = simplExprF env e cont -- ==> scc "f" (...e...)
1087 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
1088 ; rebuild env (mkSCC cc e') cont }
1090 simplNote env (CoreNote s) e cont
1091 = do { e' <- simplExpr env e
1092 ; rebuild env (Note (CoreNote s) e') cont }
1096 %************************************************************************
1100 %************************************************************************
1103 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1104 -- Look up an InVar in the environment
1107 = return (Type (substTyVar env var))
1109 = case substId env var of
1110 DoneId var1 -> return (Var var1)
1111 DoneEx e -> return e
1112 ContEx tvs ids e -> simplExpr (setSubstEnv env tvs ids) e
1114 simplVarF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1115 simplVarF env var cont
1116 = case substId env var of
1117 DoneEx e -> simplExprF (zapSubstEnv env) e cont
1118 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1119 DoneId var1 -> completeCall env var1 cont
1120 -- Note [zapSubstEnv]
1121 -- The template is already simplified, so don't re-substitute.
1122 -- This is VITAL. Consider
1124 -- let y = \z -> ...x... in
1126 -- We'll clone the inner \x, adding x->x' in the id_subst
1127 -- Then when we inline y, we must *not* replace x by x' in
1128 -- the inlined copy!!
1130 ---------------------------------------------------------
1131 -- Dealing with a call site
1133 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1134 completeCall env var cont
1135 = do { ------------- Try inlining ----------------
1136 dflags <- getDOptsSmpl
1137 ; let (lone_variable, arg_infos, call_cont) = contArgs cont
1138 -- The args are OutExprs, obtained by *lazily* substituting
1139 -- in the args found in cont. These args are only examined
1140 -- to limited depth (unless a rule fires). But we must do
1141 -- the substitution; rule matching on un-simplified args would
1144 n_val_args = length arg_infos
1145 interesting_cont = interestingCallContext call_cont
1146 unfolding = activeUnfolding env var
1147 maybe_inline = callSiteInline dflags var unfolding
1148 lone_variable arg_infos interesting_cont
1149 ; case maybe_inline of {
1150 Just expr -- There is an inlining!
1151 -> do { tick (UnfoldingDone var)
1152 ; trace_inline dflags expr cont $
1153 simplExprF (zapSubstEnv env) expr cont }
1155 ; Nothing -> do -- No inlining!
1157 { rule_base <- getSimplRules
1158 ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
1159 ; rebuildCall env info cont
1162 trace_inline dflags unfolding cont stuff
1163 | not (dopt Opt_D_dump_inlinings dflags) = stuff
1164 | not (dopt Opt_D_verbose_core2core dflags)
1165 = if isExternalName (idName var) then
1166 pprTrace "Inlining done:" (ppr var) stuff
1169 = pprTrace ("Inlining done: " ++ showSDoc (ppr var))
1170 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1171 text "Cont: " <+> ppr cont])
1174 rebuildCall :: SimplEnv
1177 -> SimplM (SimplEnv, OutExpr)
1178 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1179 -- When we run out of strictness args, it means
1180 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1181 -- Then we want to discard the entire strict continuation. E.g.
1182 -- * case (error "hello") of { ... }
1183 -- * (error "Hello") arg
1184 -- * f (error "Hello") where f is strict
1186 -- Then, especially in the first of these cases, we'd like to discard
1187 -- the continuation, leaving just the bottoming expression. But the
1188 -- type might not be right, so we may have to add a coerce.
1189 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1190 = return (env, mk_coerce res) -- contination to discard, else we do it
1191 where -- again and again!
1192 res = mkApps (Var fun) (reverse rev_args)
1193 res_ty = exprType res
1194 cont_ty = contResultType env res_ty cont
1195 co = mkUnsafeCoercion res_ty cont_ty
1196 mk_coerce expr | cont_ty `coreEqType` res_ty = expr
1197 | otherwise = mkCoerce co expr
1199 rebuildCall env info (ApplyTo _ (Type arg_ty) se cont)
1200 = do { ty' <- simplCoercion (se `setInScope` env) arg_ty
1201 ; rebuildCall env (info `addArgTo` Type ty') cont }
1203 rebuildCall env info@(ArgInfo { ai_encl = encl_rules
1204 , ai_strs = str:strs, ai_discs = disc:discs })
1205 (ApplyTo _ arg arg_se cont)
1206 | str -- Strict argument
1207 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1208 simplExprF (arg_se `setFloats` env) arg
1209 (StrictArg info' cci cont)
1212 | otherwise -- Lazy argument
1213 -- DO NOT float anything outside, hence simplExprC
1214 -- There is no benefit (unlike in a let-binding), and we'd
1215 -- have to be very careful about bogus strictness through
1216 -- floating a demanded let.
1217 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1219 ; rebuildCall env (addArgTo info' arg') cont }
1221 info' = info { ai_strs = strs, ai_discs = discs }
1222 cci | encl_rules || disc > 0 = ArgCtxt encl_rules -- Be keener here
1223 | otherwise = BoringCtxt -- Nothing interesting
1225 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
1226 = do { -- We've accumulated a simplified call in <fun,rev_args>
1227 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1228 -- See also Note [Rules for recursive functions]
1229 ; let args = reverse rev_args
1230 env' = zapSubstEnv env
1231 ; mb_rule <- tryRules env rules fun args cont
1233 Just (n_args, rule_rhs) -> simplExprF env' rule_rhs $
1234 pushArgs env' (drop n_args args) cont ;
1235 -- n_args says how many args the rule consumed
1236 ; Nothing -> rebuild env (mkApps (Var fun) args) cont -- No rules
1240 Note [RULES apply to simplified arguments]
1241 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1242 It's very desirable to try RULES once the arguments have been simplified, because
1243 doing so ensures that rule cascades work in one pass. Consider
1244 {-# RULES g (h x) = k x
1247 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1248 we match f's rules against the un-simplified RHS, it won't match. This
1249 makes a particularly big difference when superclass selectors are involved:
1250 op ($p1 ($p2 (df d)))
1251 We want all this to unravel in one sweeep.
1255 This part of the simplifier may break the no-shadowing invariant
1257 f (...(\a -> e)...) (case y of (a,b) -> e')
1258 where f is strict in its second arg
1259 If we simplify the innermost one first we get (...(\a -> e)...)
1260 Simplifying the second arg makes us float the case out, so we end up with
1261 case y of (a,b) -> f (...(\a -> e)...) e'
1262 So the output does not have the no-shadowing invariant. However, there is
1263 no danger of getting name-capture, because when the first arg was simplified
1264 we used an in-scope set that at least mentioned all the variables free in its
1265 static environment, and that is enough.
1267 We can't just do innermost first, or we'd end up with a dual problem:
1268 case x of (a,b) -> f e (...(\a -> e')...)
1270 I spent hours trying to recover the no-shadowing invariant, but I just could
1271 not think of an elegant way to do it. The simplifier is already knee-deep in
1272 continuations. We have to keep the right in-scope set around; AND we have
1273 to get the effect that finding (error "foo") in a strict arg position will
1274 discard the entire application and replace it with (error "foo"). Getting
1275 all this at once is TOO HARD!
1278 %************************************************************************
1282 %************************************************************************
1285 tryRules :: SimplEnv -> [CoreRule]
1286 -> Id -> [OutExpr] -> SimplCont
1287 -> SimplM (Maybe (Arity, CoreExpr)) -- The arity is the number of
1288 -- args consumed by the rule
1289 tryRules env rules fn args call_cont
1293 = do { dflags <- getDOptsSmpl
1294 ; case activeRule dflags env of {
1295 Nothing -> return Nothing ; -- No rules apply
1297 case lookupRule act_fn (activeUnfInRule env) (getInScope env) fn args rules of {
1298 Nothing -> return Nothing ; -- No rule matches
1299 Just (rule, rule_rhs) ->
1301 do { tick (RuleFired (ru_name rule))
1302 ; trace_dump dflags rule rule_rhs $
1303 return (Just (ruleArity rule, rule_rhs)) }}}}
1305 trace_dump dflags rule rule_rhs stuff
1306 | not (dopt Opt_D_dump_rule_firings dflags) = stuff
1307 | not (dopt Opt_D_verbose_core2core dflags)
1309 = pprTrace "Rule fired:" (ftext (ru_name rule)) stuff
1311 = pprTrace "Rule fired"
1312 (vcat [text "Rule:" <+> ftext (ru_name rule),
1313 text "Before:" <+> ppr fn <+> sep (map pprParendExpr args),
1314 text "After: " <+> pprCoreExpr rule_rhs,
1315 text "Cont: " <+> ppr call_cont])
1319 Note [Rules for recursive functions]
1320 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1321 You might think that we shouldn't apply rules for a loop breaker:
1322 doing so might give rise to an infinite loop, because a RULE is
1323 rather like an extra equation for the function:
1324 RULE: f (g x) y = x+y
1327 But it's too drastic to disable rules for loop breakers.
1328 Even the foldr/build rule would be disabled, because foldr
1329 is recursive, and hence a loop breaker:
1330 foldr k z (build g) = g k z
1331 So it's up to the programmer: rules can cause divergence
1334 %************************************************************************
1336 Rebuilding a cse expression
1338 %************************************************************************
1340 Note [Case elimination]
1341 ~~~~~~~~~~~~~~~~~~~~~~~
1342 The case-elimination transformation discards redundant case expressions.
1343 Start with a simple situation:
1345 case x# of ===> e[x#/y#]
1348 (when x#, y# are of primitive type, of course). We can't (in general)
1349 do this for algebraic cases, because we might turn bottom into
1352 The code in SimplUtils.prepareAlts has the effect of generalise this
1353 idea to look for a case where we're scrutinising a variable, and we
1354 know that only the default case can match. For example:
1358 DEFAULT -> ...(case x of
1362 Here the inner case is first trimmed to have only one alternative, the
1363 DEFAULT, after which it's an instance of the previous case. This
1364 really only shows up in eliminating error-checking code.
1366 We also make sure that we deal with this very common case:
1371 Here we are using the case as a strict let; if x is used only once
1372 then we want to inline it. We have to be careful that this doesn't
1373 make the program terminate when it would have diverged before, so we
1375 - e is already evaluated (it may so if e is a variable)
1376 - x is used strictly, or
1378 Lastly, the code in SimplUtils.mkCase combines identical RHSs. So
1380 case e of ===> case e of DEFAULT -> r
1384 Now again the case may be elminated by the CaseElim transformation.
1387 Further notes about case elimination
1388 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1389 Consider: test :: Integer -> IO ()
1392 Turns out that this compiles to:
1395 eta1 :: State# RealWorld ->
1396 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1398 (PrelNum.jtos eta ($w[] @ Char))
1400 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1402 Notice the strange '<' which has no effect at all. This is a funny one.
1403 It started like this:
1405 f x y = if x < 0 then jtos x
1406 else if y==0 then "" else jtos x
1408 At a particular call site we have (f v 1). So we inline to get
1410 if v < 0 then jtos x
1411 else if 1==0 then "" else jtos x
1413 Now simplify the 1==0 conditional:
1415 if v<0 then jtos v else jtos v
1417 Now common-up the two branches of the case:
1419 case (v<0) of DEFAULT -> jtos v
1421 Why don't we drop the case? Because it's strict in v. It's technically
1422 wrong to drop even unnecessary evaluations, and in practice they
1423 may be a result of 'seq' so we *definitely* don't want to drop those.
1424 I don't really know how to improve this situation.
1427 ---------------------------------------------------------
1428 -- Eliminate the case if possible
1430 rebuildCase, reallyRebuildCase
1432 -> OutExpr -- Scrutinee
1433 -> InId -- Case binder
1434 -> [InAlt] -- Alternatives (inceasing order)
1436 -> SimplM (SimplEnv, OutExpr)
1438 --------------------------------------------------
1439 -- 1. Eliminate the case if there's a known constructor
1440 --------------------------------------------------
1442 rebuildCase env scrut case_bndr alts cont
1443 | Lit lit <- scrut -- No need for same treatment as constructors
1444 -- because literals are inlined more vigorously
1445 = do { tick (KnownBranch case_bndr)
1446 ; case findAlt (LitAlt lit) alts of
1447 Nothing -> missingAlt env case_bndr alts cont
1448 Just (_, bs, rhs) -> simple_rhs bs rhs }
1450 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (activeUnfInRule env) scrut
1451 -- Works when the scrutinee is a variable with a known unfolding
1452 -- as well as when it's an explicit constructor application
1453 = do { tick (KnownBranch case_bndr)
1454 ; case findAlt (DataAlt con) alts of
1455 Nothing -> missingAlt env case_bndr alts cont
1456 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1457 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
1458 case_bndr bs rhs cont
1461 simple_rhs bs rhs = ASSERT( null bs )
1462 do { env' <- simplNonRecX env case_bndr scrut
1463 ; simplExprF env' rhs cont }
1466 --------------------------------------------------
1467 -- 2. Eliminate the case if scrutinee is evaluated
1468 --------------------------------------------------
1470 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1471 -- See if we can get rid of the case altogether
1472 -- See Note [Case eliminiation]
1473 -- mkCase made sure that if all the alternatives are equal,
1474 -- then there is now only one (DEFAULT) rhs
1475 | all isDeadBinder bndrs -- bndrs are [InId]
1477 -- Check that the scrutinee can be let-bound instead of case-bound
1478 , exprOkForSpeculation scrut
1479 -- OK not to evaluate it
1480 -- This includes things like (==# a# b#)::Bool
1481 -- so that we simplify
1482 -- case ==# a# b# of { True -> x; False -> x }
1485 -- This particular example shows up in default methods for
1486 -- comparision operations (e.g. in (>=) for Int.Int32)
1487 || exprIsHNF scrut -- It's already evaluated
1488 || var_demanded_later scrut -- It'll be demanded later
1490 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1491 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1492 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1493 -- its argument: case x of { y -> dataToTag# y }
1494 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1495 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1497 -- Also we don't want to discard 'seq's
1498 = do { tick (CaseElim case_bndr)
1499 ; env' <- simplNonRecX env case_bndr scrut
1500 ; simplExprF env' rhs cont }
1502 -- The case binder is going to be evaluated later,
1503 -- and the scrutinee is a simple variable
1504 var_demanded_later (Var v) = isStrictDmd (idDemandInfo case_bndr)
1505 && not (isTickBoxOp v)
1506 -- ugly hack; covering this case is what
1507 -- exprOkForSpeculation was intended for.
1508 var_demanded_later _ = False
1510 --------------------------------------------------
1511 -- 3. Try seq rules; see Note [User-defined RULES for seq] in MkId
1512 --------------------------------------------------
1514 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1515 | all isDeadBinder (case_bndr : bndrs) -- So this is just 'seq'
1516 = do { let rhs' = substExpr (text "rebuild-case") env rhs
1517 out_args = [Type (substTy env (idType case_bndr)),
1518 Type (exprType rhs'), scrut, rhs']
1519 -- Lazily evaluated, so we don't do most of this
1521 ; rule_base <- getSimplRules
1522 ; mb_rule <- tryRules env (getRules rule_base seqId) seqId out_args cont
1524 Just (n_args, res) -> simplExprF (zapSubstEnv env)
1525 (mkApps res (drop n_args out_args))
1527 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1529 rebuildCase env scrut case_bndr alts cont
1530 = reallyRebuildCase env scrut case_bndr alts cont
1532 --------------------------------------------------
1533 -- 3. Catch-all case
1534 --------------------------------------------------
1536 reallyRebuildCase env scrut case_bndr alts cont
1537 = do { -- Prepare the continuation;
1538 -- The new subst_env is in place
1539 (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1541 -- Simplify the alternatives
1542 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1544 -- Check for empty alternatives
1545 ; if null alts' then missingAlt env case_bndr alts cont
1547 { dflags <- getDOptsSmpl
1548 ; case_expr <- mkCase dflags scrut' case_bndr' alts'
1550 -- Notice that rebuild gets the in-scope set from env', not alt_env
1551 -- (which in any case is only build in simplAlts)
1552 -- The case binder *not* scope over the whole returned case-expression
1553 ; rebuild env' case_expr nodup_cont } }
1556 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1557 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1558 way, there's a chance that v will now only be used once, and hence
1561 Historical note: we use to do the "case binder swap" in the Simplifier
1562 so there were additional complications if the scrutinee was a variable.
1563 Now the binder-swap stuff is done in the occurrence analyer; see
1564 OccurAnal Note [Binder swap].
1568 If the case binder is not dead, then neither are the pattern bound
1570 case <any> of x { (a,b) ->
1571 case x of { (p,q) -> p } }
1572 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1573 The point is that we bring into the envt a binding
1575 after the outer case, and that makes (a,b) alive. At least we do unless
1576 the case binder is guaranteed dead.
1578 In practice, the scrutinee is almost always a variable, so we pretty
1579 much always zap the OccInfo of the binders. It doesn't matter much though.
1584 Consider case (v `cast` co) of x { I# y ->
1585 ... (case (v `cast` co) of {...}) ...
1586 We'd like to eliminate the inner case. We can get this neatly by
1587 arranging that inside the outer case we add the unfolding
1588 v |-> x `cast` (sym co)
1589 to v. Then we should inline v at the inner case, cancel the casts, and away we go
1591 Note [Improving seq]
1594 type family F :: * -> *
1595 type instance F Int = Int
1597 ... case e of x { DEFAULT -> rhs } ...
1599 where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
1601 case e `cast` co of x'::Int
1602 I# x# -> let x = x' `cast` sym co
1605 so that 'rhs' can take advantage of the form of x'.
1607 Notice that Note [Case of cast] may then apply to the result.
1609 Nota Bene: We only do the [Improving seq] transformation if the
1610 case binder 'x' is actually used in the rhs; that is, if the case
1611 is *not* a *pure* seq.
1612 a) There is no point in adding the cast to a pure seq.
1613 b) There is a good reason not to: doing so would interfere
1614 with seq rules (Note [Built-in RULES for seq] in MkId).
1615 In particular, this [Improving seq] thing *adds* a cast
1616 while [Built-in RULES for seq] *removes* one, so they
1619 You might worry about
1620 case v of x { __DEFAULT ->
1621 ... case (v `cast` co) of y { I# -> ... }}
1622 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1623 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1624 case v of x { __DEFAULT ->
1625 ... case (x `cast` co) of y { I# -> ... }}
1626 Now the outer case is not a pure seq, so [Improving seq] will happen,
1627 and then the inner case will disappear.
1629 The need for [Improving seq] showed up in Roman's experiments. Example:
1630 foo :: F Int -> Int -> Int
1631 foo t n = t `seq` bar n
1634 bar n = bar (n - case t of TI i -> i)
1635 Here we'd like to avoid repeated evaluating t inside the loop, by
1636 taking advantage of the `seq`.
1638 At one point I did transformation in LiberateCase, but it's more
1639 robust here. (Otherwise, there's a danger that we'll simply drop the
1640 'seq' altogether, before LiberateCase gets to see it.)
1643 simplAlts :: SimplEnv
1645 -> InId -- Case binder
1646 -> [InAlt] -- Non-empty
1648 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
1649 -- Like simplExpr, this just returns the simplified alternatives;
1650 -- it does not return an environment
1652 simplAlts env scrut case_bndr alts cont'
1653 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seTvSubst env)) $
1654 do { let env0 = zapFloats env
1656 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1658 ; fam_envs <- getFamEnvs
1659 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
1660 case_bndr case_bndr1 alts
1662 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
1664 ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1665 ; return (scrut', case_bndr', alts') }
1668 ------------------------------------
1669 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1670 -> OutExpr -> InId -> OutId -> [InAlt]
1671 -> SimplM (SimplEnv, OutExpr, OutId)
1672 -- Note [Improving seq]
1673 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1674 | not (isDeadBinder case_bndr) -- Not a pure seq! See the Note!
1675 , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1676 = do { case_bndr2 <- newId (fsLit "nt") ty2
1677 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1678 env2 = extendIdSubst env case_bndr rhs
1679 ; return (env2, scrut `Cast` co, case_bndr2) }
1681 improveSeq _ env scrut _ case_bndr1 _
1682 = return (env, scrut, case_bndr1)
1685 ------------------------------------
1686 simplAlt :: SimplEnv
1687 -> [AltCon] -- These constructors can't be present when
1688 -- matching the DEFAULT alternative
1689 -> OutId -- The case binder
1694 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1695 = ASSERT( null bndrs )
1696 do { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1697 -- Record the constructors that the case-binder *can't* be.
1698 ; rhs' <- simplExprC env' rhs cont'
1699 ; return (DEFAULT, [], rhs') }
1701 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1702 = ASSERT( null bndrs )
1703 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1704 ; rhs' <- simplExprC env' rhs cont'
1705 ; return (LitAlt lit, [], rhs') }
1707 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1708 = do { -- Deal with the pattern-bound variables
1709 -- Mark the ones that are in ! positions in the
1710 -- data constructor as certainly-evaluated.
1711 -- NB: simplLamBinders preserves this eval info
1712 let vs_with_evals = add_evals (dataConRepStrictness con)
1713 ; (env', vs') <- simplLamBndrs env vs_with_evals
1715 -- Bind the case-binder to (con args)
1716 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1717 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1718 env'' = addBinderUnfolding env' case_bndr'
1719 (mkConApp con con_args)
1721 ; rhs' <- simplExprC env'' rhs cont'
1722 ; return (DataAlt con, vs', rhs') }
1724 -- add_evals records the evaluated-ness of the bound variables of
1725 -- a case pattern. This is *important*. Consider
1726 -- data T = T !Int !Int
1728 -- case x of { T a b -> T (a+1) b }
1730 -- We really must record that b is already evaluated so that we don't
1731 -- go and re-evaluate it when constructing the result.
1732 -- See Note [Data-con worker strictness] in MkId.lhs
1737 go (v:vs') strs | isTyVar v = v : go vs' strs
1738 go (v:vs') (str:strs)
1739 | isMarkedStrict str = evald_v : go vs' strs
1740 | otherwise = zapped_v : go vs' strs
1742 zapped_v = zap_occ_info v
1743 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1744 go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1746 -- See Note [zapOccInfo]
1747 -- zap_occ_info: if the case binder is alive, then we add the unfolding
1749 -- to the envt; so vs are now very much alive
1750 -- Note [Aug06] I can't see why this actually matters, but it's neater
1751 -- case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1752 -- ==> case e of t { (a,b) -> ...(a)... }
1753 -- Look, Ma, a is alive now.
1754 zap_occ_info = zapCasePatIdOcc case_bndr'
1756 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1757 addBinderUnfolding env bndr rhs
1758 = modifyInScope env (bndr `setIdUnfolding` mkUnfolding False False rhs)
1760 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1761 addBinderOtherCon env bndr cons
1762 = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1764 zapCasePatIdOcc :: Id -> Id -> Id
1765 -- Consider case e of b { (a,b) -> ... }
1766 -- Then if we bind b to (a,b) in "...", and b is not dead,
1767 -- then we must zap the deadness info on a,b
1768 zapCasePatIdOcc case_bndr
1769 | isDeadBinder case_bndr = \ pat_id -> pat_id
1770 | otherwise = \ pat_id -> zapIdOccInfo pat_id
1774 %************************************************************************
1776 \subsection{Known constructor}
1778 %************************************************************************
1780 We are a bit careful with occurrence info. Here's an example
1782 (\x* -> case x of (a*, b) -> f a) (h v, e)
1784 where the * means "occurs once". This effectively becomes
1785 case (h v, e) of (a*, b) -> f a)
1787 let a* = h v; b = e in f a
1791 All this should happen in one sweep.
1794 knownCon :: SimplEnv
1795 -> OutExpr -- The scrutinee
1796 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
1797 -> InId -> [InBndr] -> InExpr -- The alternative
1799 -> SimplM (SimplEnv, OutExpr)
1801 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1802 = do { env' <- bind_args env bs dc_args
1803 ; env'' <- bind_case_bndr env'
1804 ; simplExprF env'' rhs cont }
1806 zap_occ = zapCasePatIdOcc bndr -- bndr is an InId
1809 bind_args env' [] _ = return env'
1811 bind_args env' (b:bs') (Type ty : args)
1812 = ASSERT( isTyVar b )
1813 bind_args (extendTvSubst env' b ty) bs' args
1815 bind_args env' (b:bs') (arg : args)
1817 do { let b' = zap_occ b
1818 -- Note that the binder might be "dead", because it doesn't
1819 -- occur in the RHS; and simplNonRecX may therefore discard
1820 -- it via postInlineUnconditionally.
1821 -- Nevertheless we must keep it if the case-binder is alive,
1822 -- because it may be used in the con_app. See Note [zapOccInfo]
1823 ; env'' <- simplNonRecX env' b' arg
1824 ; bind_args env'' bs' args }
1827 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1828 text "scrut:" <+> ppr scrut
1830 -- It's useful to bind bndr to scrut, rather than to a fresh
1831 -- binding x = Con arg1 .. argn
1832 -- because very often the scrut is a variable, so we avoid
1833 -- creating, and then subsequently eliminating, a let-binding
1834 -- BUT, if scrut is a not a variable, we must be careful
1835 -- about duplicating the arg redexes; in that case, make
1836 -- a new con-app from the args
1838 | isDeadBinder bndr = return env
1839 | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
1840 | otherwise = do { dc_args <- mapM (simplVar env) bs
1841 -- dc_ty_args are aready OutTypes,
1842 -- but bs are InBndrs
1843 ; let con_app = Var (dataConWorkId dc)
1844 `mkTyApps` dc_ty_args
1846 ; simplNonRecX env bndr con_app }
1849 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1850 -- This isn't strictly an error, although it is unusual.
1851 -- It's possible that the simplifer might "see" that
1852 -- an inner case has no accessible alternatives before
1853 -- it "sees" that the entire branch of an outer case is
1854 -- inaccessible. So we simply put an error case here instead.
1855 missingAlt env case_bndr alts cont
1856 = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1857 return (env, mkImpossibleExpr res_ty)
1859 res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1863 %************************************************************************
1865 \subsection{Duplicating continuations}
1867 %************************************************************************
1870 prepareCaseCont :: SimplEnv
1871 -> [InAlt] -> SimplCont
1872 -> SimplM (SimplEnv, SimplCont,SimplCont)
1873 -- Return a duplicatable continuation, a non-duplicable part
1874 -- plus some extra bindings (that scope over the entire
1877 -- No need to make it duplicatable if there's only one alternative
1878 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1879 prepareCaseCont env _ cont = mkDupableCont env cont
1883 mkDupableCont :: SimplEnv -> SimplCont
1884 -> SimplM (SimplEnv, SimplCont, SimplCont)
1886 mkDupableCont env cont
1887 | contIsDupable cont
1888 = return (env, cont, mkBoringStop)
1890 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1892 mkDupableCont env (CoerceIt ty cont)
1893 = do { (env', dup, nodup) <- mkDupableCont env cont
1894 ; return (env', CoerceIt ty dup, nodup) }
1896 mkDupableCont env cont@(StrictBind {})
1897 = return (env, mkBoringStop, cont)
1898 -- See Note [Duplicating StrictBind]
1900 mkDupableCont env (StrictArg info cci cont)
1901 -- See Note [Duplicating StrictArg]
1902 = do { (env', dup, nodup) <- mkDupableCont env cont
1903 ; (env'', args') <- mapAccumLM makeTrivial env' (ai_args info)
1904 ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
1906 mkDupableCont env (ApplyTo _ arg se cont)
1907 = -- e.g. [...hole...] (...arg...)
1909 -- let a = ...arg...
1910 -- in [...hole...] a
1911 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1912 ; arg' <- simplExpr (se `setInScope` env') arg
1913 ; (env'', arg'') <- makeTrivial env' arg'
1914 ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1915 ; return (env'', app_cont, nodup_cont) }
1917 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1918 -- See Note [Single-alternative case]
1919 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1920 -- | not (isDeadBinder case_bndr)
1921 | all isDeadBinder bs -- InIds
1922 && not (isUnLiftedType (idType case_bndr))
1923 -- Note [Single-alternative-unlifted]
1924 = return (env, mkBoringStop, cont)
1926 mkDupableCont env (Select _ case_bndr alts se cont)
1927 = -- e.g. (case [...hole...] of { pi -> ei })
1929 -- let ji = \xij -> ei
1930 -- in case [...hole...] of { pi -> ji xij }
1931 do { tick (CaseOfCase case_bndr)
1932 ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1933 -- NB: call mkDupableCont here, *not* prepareCaseCont
1934 -- We must make a duplicable continuation, whereas prepareCaseCont
1935 -- doesn't when there is a single case branch
1937 ; let alt_env = se `setInScope` env'
1938 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
1939 ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
1940 -- Safe to say that there are no handled-cons for the DEFAULT case
1941 -- NB: simplBinder does not zap deadness occ-info, so
1942 -- a dead case_bndr' will still advertise its deadness
1943 -- This is really important because in
1944 -- case e of b { (# p,q #) -> ... }
1945 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1946 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1947 -- In the new alts we build, we have the new case binder, so it must retain
1949 -- NB: we don't use alt_env further; it has the substEnv for
1950 -- the alternatives, and we don't want that
1952 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
1953 ; return (env'', -- Note [Duplicated env]
1954 Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
1958 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1959 -> SimplM (SimplEnv, [InAlt])
1960 -- Absorbs the continuation into the new alternatives
1962 mkDupableAlts env case_bndr' the_alts
1965 go env0 [] = return (env0, [])
1967 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
1968 ; (env2, alts') <- go env1 alts
1969 ; return (env2, alt' : alts' ) }
1971 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
1972 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
1973 mkDupableAlt env case_bndr (con, bndrs', rhs')
1974 | exprIsDupable rhs' -- Note [Small alternative rhs]
1975 = return (env, (con, bndrs', rhs'))
1977 = do { let rhs_ty' = exprType rhs'
1978 scrut_ty = idType case_bndr
1981 DEFAULT -> case_bndr
1982 DataAlt dc -> setIdUnfolding case_bndr unf
1984 -- See Note [Case binders and join points]
1985 unf = mkInlineRule rhs Nothing
1986 rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
1987 ++ varsToCoreExprs bndrs')
1989 LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
1990 <+> ppr case_bndr <+> ppr con )
1992 -- The case binder is alive but trivial, so why has
1993 -- it not been substituted away?
1995 used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
1996 | otherwise = bndrs' ++ [case_bndr_w_unf]
1999 | isTyVar bndr = True -- Abstract over all type variables just in case
2000 | otherwise = not (isDeadBinder bndr)
2001 -- The deadness info on the new Ids is preserved by simplBinders
2003 ; (final_bndrs', final_args) -- Note [Join point abstraction]
2004 <- if (any isId used_bndrs')
2005 then return (used_bndrs', varsToCoreExprs used_bndrs')
2006 else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
2007 ; return ([rw_id], [Var realWorldPrimId]) }
2009 ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2010 -- Note [Funky mkPiTypes]
2012 ; let -- We make the lambdas into one-shot-lambdas. The
2013 -- join point is sure to be applied at most once, and doing so
2014 -- prevents the body of the join point being floated out by
2015 -- the full laziness pass
2016 really_final_bndrs = map one_shot final_bndrs'
2017 one_shot v | isId v = setOneShotLambda v
2019 join_rhs = mkLams really_final_bndrs rhs'
2020 join_call = mkApps (Var join_bndr) final_args
2022 ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2023 ; return (env', (con, bndrs', join_call)) }
2024 -- See Note [Duplicated env]
2027 Note [Case binders and join points]
2028 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2030 case (case .. ) of c {
2033 If we make a join point with c but not c# we get
2034 $j = \c -> ....c....
2036 But if later inlining scrutines the c, thus
2038 $j = \c -> ... case c of { I# y -> ... } ...
2040 we won't see that 'c' has already been scrutinised. This actually
2041 happens in the 'tabulate' function in wave4main, and makes a significant
2042 difference to allocation.
2044 An alternative plan is this:
2046 $j = \c# -> let c = I# c# in ...c....
2048 but that is bad if 'c' is *not* later scrutinised.
2050 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2051 that it's really I# c#, thus
2053 $j = \c# -> \c[=I# c#] -> ...c....
2055 Absence analysis may later discard 'c'.
2058 Note [Duplicated env]
2059 ~~~~~~~~~~~~~~~~~~~~~
2060 Some of the alternatives are simplified, but have not been turned into a join point
2061 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
2062 bind the join point, because it might to do PostInlineUnconditionally, and
2063 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
2064 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2065 at worst delays the join-point inlining.
2067 Note [Small alternative rhs]
2068 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2069 It is worth checking for a small RHS because otherwise we
2070 get extra let bindings that may cause an extra iteration of the simplifier to
2071 inline back in place. Quite often the rhs is just a variable or constructor.
2072 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2073 iterations because the version with the let bindings looked big, and so wasn't
2074 inlined, but after the join points had been inlined it looked smaller, and so
2077 NB: we have to check the size of rhs', not rhs.
2078 Duplicating a small InAlt might invalidate occurrence information
2079 However, if it *is* dupable, we return the *un* simplified alternative,
2080 because otherwise we'd need to pair it up with an empty subst-env....
2081 but we only have one env shared between all the alts.
2082 (Remember we must zap the subst-env before re-simplifying something).
2083 Rather than do this we simply agree to re-simplify the original (small) thing later.
2085 Note [Funky mkPiTypes]
2086 ~~~~~~~~~~~~~~~~~~~~~~
2087 Notice the funky mkPiTypes. If the contructor has existentials
2088 it's possible that the join point will be abstracted over
2089 type varaibles as well as term variables.
2090 Example: Suppose we have
2091 data T = forall t. C [t]
2093 case (case e of ...) of
2095 We get the join point
2096 let j :: forall t. [t] -> ...
2097 j = /\t \xs::[t] -> rhs
2099 case (case e of ...) of
2100 C t xs::[t] -> j t xs
2102 Note [Join point abstaction]
2103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2104 If we try to lift a primitive-typed something out
2105 for let-binding-purposes, we will *caseify* it (!),
2106 with potentially-disastrous strictness results. So
2107 instead we turn it into a function: \v -> e
2108 where v::State# RealWorld#. The value passed to this function
2109 is realworld#, which generates (almost) no code.
2111 There's a slight infelicity here: we pass the overall
2112 case_bndr to all the join points if it's used in *any* RHS,
2113 because we don't know its usage in each RHS separately
2115 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2116 we make the join point into a function whenever used_bndrs'
2117 is empty. This makes the join-point more CPR friendly.
2118 Consider: let j = if .. then I# 3 else I# 4
2119 in case .. of { A -> j; B -> j; C -> ... }
2121 Now CPR doesn't w/w j because it's a thunk, so
2122 that means that the enclosing function can't w/w either,
2123 which is a lose. Here's the example that happened in practice:
2124 kgmod :: Int -> Int -> Int
2125 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2129 I have seen a case alternative like this:
2131 It's a bit silly to add the realWorld dummy arg in this case, making
2134 (the \v alone is enough to make CPR happy) but I think it's rare
2136 Note [Duplicating StrictArg]
2137 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2138 The original plan had (where E is a big argument)
2140 ==> let $j = \a -> f E a
2143 But this is terrible! Here's an example:
2144 && E (case x of { T -> F; F -> T })
2145 Now, && is strict so we end up simplifying the case with
2146 an ArgOf continuation. If we let-bind it, we get
2147 let $j = \v -> && E v
2148 in simplExpr (case x of { T -> F; F -> T })
2150 And after simplifying more we get
2151 let $j = \v -> && E v
2152 in case x of { T -> $j F; F -> $j T }
2153 Which is a Very Bad Thing
2155 What we do now is this
2159 Now if the thing in the hole is a case expression (which is when
2160 we'll call mkDupableCont), we'll push the function call into the
2161 branches, which is what we want. Now RULES for f may fire, and
2162 call-pattern specialisation. Here's an example from Trac #3116
2165 _ -> Chunk p fpc (o+1) (l-1) bs')
2166 If we can push the call for 'go' inside the case, we get
2167 call-pattern specialisation for 'go', which is *crucial* for
2170 Here is the (&&) example:
2171 && E (case x of { T -> F; F -> T })
2173 case x of { T -> && a F; F -> && a T }
2177 * Arguments to f *after* the strict one are handled by
2178 the ApplyTo case of mkDupableCont. Eg
2181 * We can only do the let-binding of E because the function
2182 part of a StrictArg continuation is an explicit syntax
2183 tree. In earlier versions we represented it as a function
2184 (CoreExpr -> CoreEpxr) which we couldn't take apart.
2186 Do *not* duplicate StrictBind and StritArg continuations. We gain
2187 nothing by propagating them into the expressions, and we do lose a
2190 The desire not to duplicate is the entire reason that
2191 mkDupableCont returns a pair of continuations.
2193 Note [Duplicating StrictBind]
2194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2195 Unlike StrictArg, there doesn't seem anything to gain from
2196 duplicating a StrictBind continuation, so we don't.
2198 The desire not to duplicate is the entire reason that
2199 mkDupableCont returns a pair of continuations.
2202 Note [Single-alternative cases]
2203 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2204 This case is just like the ArgOf case. Here's an example:
2208 case (case x of I# x' ->
2210 True -> I# (negate# x')
2211 False -> I# x') of y {
2213 Because the (case x) has only one alternative, we'll transform to
2215 case (case x' <# 0# of
2216 True -> I# (negate# x')
2217 False -> I# x') of y {
2219 But now we do *NOT* want to make a join point etc, giving
2221 let $j = \y -> MkT y
2223 True -> $j (I# (negate# x'))
2225 In this case the $j will inline again, but suppose there was a big
2226 strict computation enclosing the orginal call to MkT. Then, it won't
2227 "see" the MkT any more, because it's big and won't get duplicated.
2228 And, what is worse, nothing was gained by the case-of-case transform.
2230 When should use this case of mkDupableCont?
2231 However, matching on *any* single-alternative case is a *disaster*;
2232 e.g. case (case ....) of (a,b) -> (# a,b #)
2233 We must push the outer case into the inner one!
2236 * Match [(DEFAULT,_,_)], but in the common case of Int,
2237 the alternative-filling-in code turned the outer case into
2238 case (...) of y { I# _ -> MkT y }
2240 * Match on single alternative plus (not (isDeadBinder case_bndr))
2241 Rationale: pushing the case inwards won't eliminate the construction.
2242 But there's a risk of
2243 case (...) of y { (a,b) -> let z=(a,b) in ... }
2244 Now y looks dead, but it'll come alive again. Still, this
2245 seems like the best option at the moment.
2247 * Match on single alternative plus (all (isDeadBinder bndrs))
2248 Rationale: this is essentially seq.
2250 * Match when the rhs is *not* duplicable, and hence would lead to a
2251 join point. This catches the disaster-case above. We can test
2252 the *un-simplified* rhs, which is fine. It might get bigger or
2253 smaller after simplification; if it gets smaller, this case might
2254 fire next time round. NB also that we must test contIsDupable
2255 case_cont *btoo, because case_cont might be big!
2257 HOWEVER: I found that this version doesn't work well, because
2258 we can get let x = case (...) of { small } in ...case x...
2259 When x is inlined into its full context, we find that it was a bad
2260 idea to have pushed the outer case inside the (...) case.
2262 Note [Single-alternative-unlifted]
2263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2264 Here's another single-alternative where we really want to do case-of-case:
2272 case y_s6X of tpl_s7m {
2273 M1.Mk1 ipv_s70 -> ipv_s70;
2274 M1.Mk2 ipv_s72 -> ipv_s72;
2280 case x_s74 of tpl_s7n {
2281 M1.Mk1 ipv_s77 -> ipv_s77;
2282 M1.Mk2 ipv_s79 -> ipv_s79;
2286 { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2290 So the outer case is doing *nothing at all*, other than serving as a
2291 join-point. In this case we really want to do case-of-case and decide
2292 whether to use a real join point or just duplicate the continuation.
2294 Hence: check whether the case binder's type is unlifted, because then
2295 the outer case is *not* a seq.