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 )
20 import DataCon ( dataConRepStrictness, dataConUnivTyVars )
22 import NewDemand ( isStrictDmd )
23 import PprCore ( pprParendExpr, pprCoreExpr )
24 import CoreUnfold ( mkUnfolding, callSiteInline )
26 import Rules ( lookupRule )
27 import BasicTypes ( isMarkedStrict )
28 import CostCentre ( currentCCS )
29 import TysPrim ( realWorldStatePrimTy )
30 import PrelInfo ( realWorldPrimId )
31 import BasicTypes ( TopLevelFlag(..), isTopLevel,
32 RecFlag(..), isNonRuleLoopBreaker )
33 import Maybes ( orElse )
39 The guts of the simplifier is in this module, but the driver loop for
40 the simplifier is in SimplCore.lhs.
43 -----------------------------------------
44 *** IMPORTANT NOTE ***
45 -----------------------------------------
46 The simplifier used to guarantee that the output had no shadowing, but
47 it does not do so any more. (Actually, it never did!) The reason is
48 documented with simplifyArgs.
51 -----------------------------------------
52 *** IMPORTANT NOTE ***
53 -----------------------------------------
54 Many parts of the simplifier return a bunch of "floats" as well as an
55 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
57 All "floats" are let-binds, not case-binds, but some non-rec lets may
58 be unlifted (with RHS ok-for-speculation).
62 -----------------------------------------
63 ORGANISATION OF FUNCTIONS
64 -----------------------------------------
66 - simplify all top-level binders
67 - for NonRec, call simplRecOrTopPair
68 - for Rec, call simplRecBind
71 ------------------------------
72 simplExpr (applied lambda) ==> simplNonRecBind
73 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
74 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
76 ------------------------------
77 simplRecBind [binders already simplfied]
78 - use simplRecOrTopPair on each pair in turn
80 simplRecOrTopPair [binder already simplified]
81 Used for: recursive bindings (top level and nested)
82 top-level non-recursive bindings
84 - check for PreInlineUnconditionally
88 Used for: non-top-level non-recursive bindings
89 beta reductions (which amount to the same thing)
90 Because it can deal with strict arts, it takes a
91 "thing-inside" and returns an expression
93 - check for PreInlineUnconditionally
94 - simplify binder, including its IdInfo
103 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
104 Used for: binding case-binder and constr args in a known-constructor case
105 - check for PreInLineUnconditionally
109 ------------------------------
110 simplLazyBind: [binder already simplified, RHS not]
111 Used for: recursive bindings (top level and nested)
112 top-level non-recursive bindings
113 non-top-level, but *lazy* non-recursive bindings
114 [must not be strict or unboxed]
115 Returns floats + an augmented environment, not an expression
116 - substituteIdInfo and add result to in-scope
117 [so that rules are available in rec rhs]
120 - float if exposes constructor or PAP
124 completeNonRecX: [binder and rhs both simplified]
125 - if the the thing needs case binding (unlifted and not ok-for-spec)
131 completeBind: [given a simplified RHS]
132 [used for both rec and non-rec bindings, top level and not]
133 - try PostInlineUnconditionally
134 - add unfolding [this is the only place we add an unfolding]
139 Right hand sides and arguments
140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141 In many ways we want to treat
142 (a) the right hand side of a let(rec), and
143 (b) a function argument
144 in the same way. But not always! In particular, we would
145 like to leave these arguments exactly as they are, so they
146 will match a RULE more easily.
151 It's harder to make the rule match if we ANF-ise the constructor,
152 or eta-expand the PAP:
154 f (let { a = g x; b = h x } in (a,b))
157 On the other hand if we see the let-defns
162 then we *do* want to ANF-ise and eta-expand, so that p and q
163 can be safely inlined.
165 Even floating lets out is a bit dubious. For let RHS's we float lets
166 out if that exposes a value, so that the value can be inlined more vigorously.
169 r = let x = e in (x,x)
171 Here, if we float the let out we'll expose a nice constructor. We did experiments
172 that showed this to be a generally good thing. But it was a bad thing to float
173 lets out unconditionally, because that meant they got allocated more often.
175 For function arguments, there's less reason to expose a constructor (it won't
176 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
177 So for the moment we don't float lets out of function arguments either.
182 For eta expansion, we want to catch things like
184 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
186 If the \x was on the RHS of a let, we'd eta expand to bring the two
187 lambdas together. And in general that's a good thing to do. Perhaps
188 we should eta expand wherever we find a (value) lambda? Then the eta
189 expansion at a let RHS can concentrate solely on the PAP case.
192 %************************************************************************
194 \subsection{Bindings}
196 %************************************************************************
199 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
201 simplTopBinds env binds
202 = do { -- Put all the top-level binders into scope at the start
203 -- so that if a transformation rule has unexpectedly brought
204 -- anything into scope, then we don't get a complaint about that.
205 -- It's rather as if the top-level binders were imported.
206 ; env <- simplRecBndrs env (bindersOfBinds binds)
207 ; dflags <- getDOptsSmpl
208 ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
209 dopt Opt_D_dump_rule_firings dflags
210 ; env' <- simpl_binds dump_flag env binds
211 ; freeTick SimplifierDone
212 ; return (getFloats env') }
214 -- We need to track the zapped top-level binders, because
215 -- they should have their fragile IdInfo zapped (notably occurrence info)
216 -- That's why we run down binds and bndrs' simultaneously.
218 -- The dump-flag emits a trace for each top-level binding, which
219 -- helps to locate the tracing for inlining and rule firing
220 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
221 simpl_binds dump env [] = return env
222 simpl_binds dump env (bind:binds) = do { env' <- trace dump bind $
224 ; simpl_binds dump env' binds }
226 trace True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
227 trace False bind = \x -> x
229 simpl_bind env (NonRec b r) = simplRecOrTopPair env TopLevel b r
230 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
234 %************************************************************************
236 \subsection{Lazy bindings}
238 %************************************************************************
240 simplRecBind is used for
241 * recursive bindings only
244 simplRecBind :: SimplEnv -> TopLevelFlag
247 simplRecBind env top_lvl pairs
248 = do { env' <- go (zapFloats env) pairs
249 ; return (env `addRecFloats` env') }
250 -- addFloats adds the floats from env',
251 -- *and* updates env with the in-scope set from env'
253 go env [] = return env
255 go env ((bndr, rhs) : pairs)
256 = do { env <- simplRecOrTopPair env top_lvl bndr rhs
260 simplOrTopPair is used for
261 * recursive bindings (whether top level or not)
262 * top-level non-recursive bindings
264 It assumes the binder has already been simplified, but not its IdInfo.
267 simplRecOrTopPair :: SimplEnv
269 -> InId -> InExpr -- Binder and rhs
270 -> SimplM SimplEnv -- Returns an env that includes the binding
272 simplRecOrTopPair env top_lvl bndr rhs
273 | preInlineUnconditionally env top_lvl bndr rhs -- Check for unconditional inline
274 = do { tick (PreInlineUnconditionally bndr)
275 ; return (extendIdSubst env bndr (mkContEx env rhs)) }
278 = do { let bndr' = lookupRecBndr env bndr
279 (env', bndr'') = addLetIdInfo env bndr bndr'
280 ; simplLazyBind env' top_lvl Recursive bndr bndr'' rhs env' }
281 -- May not actually be recursive, but it doesn't matter
285 simplLazyBind is used for
286 * [simplRecOrTopPair] recursive bindings (whether top level or not)
287 * [simplRecOrTopPair] top-level non-recursive bindings
288 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
291 1. It assumes that the binder is *already* simplified,
292 and is in scope, and its IdInfo too, except unfolding
294 2. It assumes that the binder type is lifted.
296 3. It does not check for pre-inline-unconditionallly;
297 that should have been done already.
300 simplLazyBind :: SimplEnv
301 -> TopLevelFlag -> RecFlag
302 -> InId -> OutId -- Binder, both pre-and post simpl
303 -- The OutId has IdInfo, except arity, unfolding
304 -> InExpr -> SimplEnv -- The RHS and its environment
307 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
308 = do { let rhs_env = rhs_se `setInScope` env
309 (tvs, body) = collectTyBinders rhs
310 ; (body_env, tvs') <- simplBinders rhs_env tvs
311 -- See Note [Floating and type abstraction]
314 -- Simplify the RHS; note the mkRhsStop, which tells
315 -- the simplifier that this is the RHS of a let.
316 ; let rhs_cont = mkRhsStop (applyTys (idType bndr1) (mkTyVarTys tvs'))
317 ; (body_env1, body1) <- simplExprF body_env body rhs_cont
319 -- ANF-ise a constructor or PAP rhs
320 ; (body_env2, body2) <- prepareRhs body_env1 body1
323 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
324 then -- No floating, just wrap up!
325 do { rhs' <- mkLam tvs' (wrapFloats body_env2 body2)
326 ; return (env, rhs') }
328 else if null tvs then -- Simple floating
329 do { tick LetFloatFromLet
330 ; return (addFloats env body_env2, body2) }
332 else -- Do type-abstraction first
333 do { tick LetFloatFromLet
334 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
335 ; rhs' <- mkLam tvs' body3
336 ; return (extendFloats env poly_binds, rhs') }
338 ; completeBind env' top_lvl bndr bndr1 rhs' }
341 A specialised variant of simplNonRec used when the RHS is already simplified,
342 notably in knownCon. It uses case-binding where necessary.
345 simplNonRecX :: SimplEnv
346 -> InId -- Old binder
347 -> OutExpr -- Simplified RHS
350 simplNonRecX env bndr new_rhs
351 = do { (env, bndr') <- simplBinder env bndr
352 ; completeNonRecX env NotTopLevel NonRecursive
353 (isStrictId bndr) bndr bndr' new_rhs }
355 completeNonRecX :: SimplEnv
356 -> TopLevelFlag -> RecFlag -> Bool
357 -> InId -- Old binder
358 -> OutId -- New binder
359 -> OutExpr -- Simplified RHS
362 completeNonRecX env top_lvl is_rec is_strict old_bndr new_bndr new_rhs
363 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
365 if doFloatFromRhs top_lvl is_rec is_strict rhs1 env1
366 then do { tick LetFloatFromLet
367 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
368 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
369 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
372 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
373 Doing so risks exponential behaviour, because new_rhs has been simplified once already
374 In the cases described by the folowing commment, postInlineUnconditionally will
375 catch many of the relevant cases.
376 -- This happens; for example, the case_bndr during case of
377 -- known constructor: case (a,b) of x { (p,q) -> ... }
378 -- Here x isn't mentioned in the RHS, so we don't want to
379 -- create the (dead) let-binding let x = (a,b) in ...
381 -- Similarly, single occurrences can be inlined vigourously
382 -- e.g. case (f x, g y) of (a,b) -> ....
383 -- If a,b occur once we can avoid constructing the let binding for them.
385 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
386 -- Consider case I# (quotInt# x y) of
387 -- I# v -> let w = J# v in ...
388 -- If we gaily inline (quotInt# x y) for v, we end up building an
390 -- let w = J# (quotInt# x y) in ...
391 -- because quotInt# can fail.
393 | preInlineUnconditionally env NotTopLevel bndr new_rhs
394 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
397 ----------------------------------
398 prepareRhs takes a putative RHS, checks whether it's a PAP or
399 constructor application and, if so, converts it to ANF, so that the
400 resulting thing can be inlined more easily. Thus
407 We also want to deal well cases like this
408 v = (f e1 `cast` co) e2
409 Here we want to make e1,e2 trivial and get
410 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
411 That's what the 'go' loop in prepareRhs does
414 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
415 -- Adds new floats to the env iff that allows us to return a good RHS
416 prepareRhs env (Cast rhs co) -- Note [Float coercions]
417 = do { (env', rhs') <- makeTrivial env rhs
418 ; return (env', Cast rhs' co) }
421 = do { (is_val, env', rhs') <- go 0 env rhs
422 ; return (env', rhs') }
424 go n_val_args env (Cast rhs co)
425 = do { (is_val, env', rhs') <- go n_val_args env rhs
426 ; return (is_val, env', Cast rhs' co) }
427 go n_val_args env (App fun (Type ty))
428 = do { (is_val, env', rhs') <- go n_val_args env fun
429 ; return (is_val, env', App rhs' (Type ty)) }
430 go n_val_args env (App fun arg)
431 = do { (is_val, env', fun') <- go (n_val_args+1) env fun
433 True -> do { (env'', arg') <- makeTrivial env' arg
434 ; return (True, env'', App fun' arg') }
435 False -> return (False, env, App fun arg) }
436 go n_val_args env (Var fun)
437 = return (is_val, env, Var fun)
439 is_val = n_val_args > 0 -- There is at least one arg
440 -- ...and the fun a constructor or PAP
441 && (isDataConWorkId fun || n_val_args < idArity fun)
442 go n_val_args env other
443 = return (False, env, other)
447 Note [Float coercions]
448 ~~~~~~~~~~~~~~~~~~~~~~
449 When we find the binding
451 we'd like to transform it to
453 x = x `cast` co -- A trivial binding
454 There's a chance that e will be a constructor application or function, or something
455 like that, so moving the coerion to the usage site may well cancel the coersions
456 and lead to further optimisation. Example:
459 data instance T Int = T Int
461 foo :: Int -> Int -> Int
466 go n = case x of { T m -> go (n-m) }
467 -- This case should optimise
471 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
472 -- Binds the expression to a variable, if it's not trivial, returning the variable
476 | otherwise -- See Note [Take care] below
477 = do { var <- newId FSLIT("a") (exprType expr)
478 ; env <- completeNonRecX env NotTopLevel NonRecursive
480 ; return (env, substExpr env (Var var)) }
484 %************************************************************************
486 \subsection{Completing a lazy binding}
488 %************************************************************************
491 * deals only with Ids, not TyVars
492 * takes an already-simplified binder and RHS
493 * is used for both recursive and non-recursive bindings
494 * is used for both top-level and non-top-level bindings
496 It does the following:
497 - tries discarding a dead binding
498 - tries PostInlineUnconditionally
499 - add unfolding [this is the only place we add an unfolding]
502 It does *not* attempt to do let-to-case. Why? Because it is used for
503 - top-level bindings (when let-to-case is impossible)
504 - many situations where the "rhs" is known to be a WHNF
505 (so let-to-case is inappropriate).
507 Nor does it do the atomic-argument thing
510 completeBind :: SimplEnv
511 -> TopLevelFlag -- Flag stuck into unfolding
512 -> InId -- Old binder
513 -> OutId -> OutExpr -- New binder and RHS
515 -- completeBind may choose to do its work
516 -- * by extending the substitution (e.g. let x = y in ...)
517 -- * or by adding to the floats in the envt
519 completeBind env top_lvl old_bndr new_bndr new_rhs
520 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
521 -- Inline and discard the binding
522 = do { tick (PostInlineUnconditionally old_bndr)
523 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
524 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
525 -- Use the substitution to make quite, quite sure that the
526 -- substitution will happen, since we are going to discard the binding
531 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
534 -- Add the unfolding *only* for non-loop-breakers
535 -- Making loop breakers not have an unfolding at all
536 -- means that we can avoid tests in exprIsConApp, for example.
537 -- This is important: if exprIsConApp says 'yes' for a recursive
538 -- thing, then we can get into an infinite loop
541 -- If the unfolding is a value, the demand info may
542 -- go pear-shaped, so we nuke it. Example:
544 -- case x of (p,q) -> h p q x
545 -- Here x is certainly demanded. But after we've nuked
546 -- the case, we'll get just
547 -- let x = (a,b) in h a b x
548 -- and now x is not demanded (I'm assuming h is lazy)
549 -- This really happens. Similarly
550 -- let f = \x -> e in ...f..f...
551 -- After inlining f at some of its call sites the original binding may
552 -- (for example) be no longer strictly demanded.
553 -- The solution here is a bit ad hoc...
554 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
555 final_info | loop_breaker = new_bndr_info
556 | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
557 | otherwise = info_w_unf
559 final_id = new_bndr `setIdInfo` final_info
561 -- These seqs forces the Id, and hence its IdInfo,
562 -- and hence any inner substitutions
564 -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
565 return (addNonRec env final_id new_rhs)
567 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
568 loop_breaker = isNonRuleLoopBreaker occ_info
569 old_info = idInfo old_bndr
570 occ_info = occInfo old_info
575 %************************************************************************
577 \subsection[Simplify-simplExpr]{The main function: simplExpr}
579 %************************************************************************
581 The reason for this OutExprStuff stuff is that we want to float *after*
582 simplifying a RHS, not before. If we do so naively we get quadratic
583 behaviour as things float out.
585 To see why it's important to do it after, consider this (real) example:
599 a -- Can't inline a this round, cos it appears twice
603 Each of the ==> steps is a round of simplification. We'd save a
604 whole round if we float first. This can cascade. Consider
609 let f = let d1 = ..d.. in \y -> e
613 in \x -> ...(\y ->e)...
615 Only in this second round can the \y be applied, and it
616 might do the same again.
620 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
621 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
623 expr_ty' = substTy env (exprType expr)
624 -- The type in the Stop continuation, expr_ty', is usually not used
625 -- It's only needed when discarding continuations after finding
626 -- a function that returns bottom.
627 -- Hence the lazy substitution
630 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
631 -- Simplify an expression, given a continuation
632 simplExprC env expr cont
633 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
634 do { (env', expr') <- simplExprF (zapFloats env) expr cont
635 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
636 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
637 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
638 return (wrapFloats env' expr') }
640 --------------------------------------------------
641 simplExprF :: SimplEnv -> InExpr -> SimplCont
642 -> SimplM (SimplEnv, OutExpr)
644 simplExprF env e cont
645 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
646 simplExprF' env e cont
648 simplExprF' env (Var v) cont = simplVar env v cont
649 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
650 simplExprF' env (Note n expr) cont = simplNote env n expr cont
651 simplExprF' env (Cast body co) cont = simplCast env body co cont
652 simplExprF' env (App fun arg) cont = simplExprF env fun $
653 ApplyTo NoDup arg env cont
655 simplExprF' env expr@(Lam _ _) cont
656 = simplLam env (map zap bndrs) body cont
657 -- The main issue here is under-saturated lambdas
658 -- (\x1. \x2. e) arg1
659 -- Here x1 might have "occurs-once" occ-info, because occ-info
660 -- is computed assuming that a group of lambdas is applied
661 -- all at once. If there are too few args, we must zap the
664 n_args = countArgs cont
665 n_params = length bndrs
666 (bndrs, body) = collectBinders expr
667 zap | n_args >= n_params = \b -> b
668 | otherwise = \b -> if isTyVar b then b
670 -- NB: we count all the args incl type args
671 -- so we must count all the binders (incl type lambdas)
673 simplExprF' env (Type ty) cont
674 = ASSERT( contIsRhsOrArg cont )
675 do { ty' <- simplType env ty
676 ; rebuild env (Type ty') cont }
678 simplExprF' env (Case scrut bndr case_ty alts) cont
679 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
680 = -- Simplify the scrutinee with a Select continuation
681 simplExprF env scrut (Select NoDup bndr alts env cont)
684 = -- If case-of-case is off, simply simplify the case expression
685 -- in a vanilla Stop context, and rebuild the result around it
686 do { case_expr' <- simplExprC env scrut case_cont
687 ; rebuild env case_expr' cont }
689 case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
690 case_ty' = substTy env case_ty -- c.f. defn of simplExpr
692 simplExprF' env (Let (Rec pairs) body) cont
693 = do { env <- simplRecBndrs env (map fst pairs)
694 -- NB: bndrs' don't have unfoldings or rules
695 -- We add them as we go down
697 ; env <- simplRecBind env NotTopLevel pairs
698 ; simplExprF env body cont }
700 simplExprF' env (Let (NonRec bndr rhs) body) cont
701 = simplNonRecE env bndr (rhs, env) ([], body) cont
703 ---------------------------------
704 simplType :: SimplEnv -> InType -> SimplM OutType
705 -- Kept monadic just so we can do the seqType
707 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
708 seqType new_ty `seq` returnSmpl new_ty
710 new_ty = substTy env ty
714 %************************************************************************
716 \subsection{The main rebuilder}
718 %************************************************************************
721 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
722 -- At this point the substitution in the SimplEnv should be irrelevant
723 -- only the in-scope set and floats should matter
724 rebuild env expr cont
725 = -- pprTrace "rebuild" (ppr expr $$ ppr cont $$ ppr (seFloats env)) $
727 Stop {} -> return (env, expr)
728 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
729 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
730 StrictArg fun ty info cont -> rebuildCall env (fun `App` expr) (funResultTy ty) info cont
731 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
732 ; simplLam env' bs body cont }
733 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
734 ; rebuild env (App expr arg') cont }
738 %************************************************************************
742 %************************************************************************
745 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
746 -> SimplM (SimplEnv, OutExpr)
747 simplCast env body co cont
748 = do { co' <- simplType env co
749 ; simplExprF env body (addCoerce co' cont) }
751 addCoerce co cont = add_coerce co (coercionKind co) cont
753 add_coerce co (s1, k1) cont -- co :: ty~ty
754 | s1 `coreEqType` k1 = cont -- is a no-op
756 add_coerce co1 (s1, k2) (CoerceIt co2 cont)
757 | (l1, t1) <- coercionKind co2
758 -- coerce T1 S1 (coerce S1 K1 e)
761 -- coerce T1 K1 e, otherwise
763 -- For example, in the initial form of a worker
764 -- we may find (coerce T (coerce S (\x.e))) y
765 -- and we'd like it to simplify to e[y/x] in one round
767 , s1 `coreEqType` t1 = cont -- The coerces cancel out
768 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
770 add_coerce co (s1s2, t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
771 -- (f `cast` g) ty ---> (f ty) `cast` (g @ ty)
772 -- This implements the PushT rule from the paper
773 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
774 , not (isCoVar tyvar)
775 = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
777 ty' = substTy arg_se arg_ty
779 -- ToDo: the PushC rule is not implemented at all
781 add_coerce co (s1s2, t1t2) (ApplyTo dup arg arg_se cont)
782 | not (isTypeArg arg) -- This implements the Push rule from the paper
783 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
784 -- co : s1s2 :=: t1t2
785 -- (coerce (T1->T2) (S1->S2) F) E
787 -- coerce T2 S2 (F (coerce S1 T1 E))
789 -- t1t2 must be a function type, T1->T2, because it's applied
790 -- to something but s1s2 might conceivably not be
792 -- When we build the ApplyTo we can't mix the out-types
793 -- with the InExpr in the argument, so we simply substitute
794 -- to make it all consistent. It's a bit messy.
795 -- But it isn't a common case.
797 -- Example of use: Trac #995
798 = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
800 -- we split coercion t1->t2 :=: s1->s2 into t1 :=: s1 and
801 -- t2 :=: s2 with left and right on the curried form:
802 -- (->) t1 t2 :=: (->) s1 s2
803 [co1, co2] = decomposeCo 2 co
804 new_arg = mkCoerce (mkSymCoercion co1) arg'
805 arg' = substExpr arg_se arg
807 add_coerce co _ cont = CoerceIt co cont
811 %************************************************************************
815 %************************************************************************
818 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
819 -> SimplM (SimplEnv, OutExpr)
821 simplLam env [] body cont = simplExprF env body cont
823 -- Type-beta reduction
824 simplLam env (bndr:bndrs) body (ApplyTo _ (Type ty_arg) arg_se cont)
825 = ASSERT( isTyVar bndr )
826 do { tick (BetaReduction bndr)
827 ; ty_arg' <- simplType (arg_se `setInScope` env) ty_arg
828 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
830 -- Ordinary beta reduction
831 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
832 = do { tick (BetaReduction bndr)
833 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
835 -- Not enough args, so there are real lambdas left to put in the result
836 simplLam env bndrs body cont
837 = do { (env, bndrs') <- simplLamBndrs env bndrs
838 ; body' <- simplExpr env body
839 ; new_lam <- mkLam bndrs' body'
840 ; rebuild env new_lam cont }
843 simplNonRecE :: SimplEnv
844 -> InId -- The binder
845 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
846 -> ([InId], InExpr) -- Body of the let/lambda
849 -> SimplM (SimplEnv, OutExpr)
851 -- simplNonRecE is used for
852 -- * non-top-level non-recursive lets in expressions
855 -- It deals with strict bindings, via the StrictBind continuation,
856 -- which may abort the whole process
858 -- The "body" of the binding comes as a pair of ([InId],InExpr)
859 -- representing a lambda; so we recurse back to simplLam
860 -- Why? Because of the binder-occ-info-zapping done before
861 -- the call to simplLam in simplExprF (Lam ...)
863 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
864 | preInlineUnconditionally env NotTopLevel bndr rhs
865 = do { tick (PreInlineUnconditionally bndr)
866 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
869 = do { simplExprF (rhs_se `setFloats` env) rhs
870 (StrictBind bndr bndrs body env cont) }
873 = do { (env, bndr') <- simplBinder env bndr
874 ; env <- simplLazyBind env NotTopLevel NonRecursive bndr bndr' rhs rhs_se
875 ; simplLam env bndrs body cont }
879 %************************************************************************
883 %************************************************************************
886 -- Hack alert: we only distinguish subsumed cost centre stacks for the
887 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
888 simplNote env (SCC cc) e cont
889 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
890 ; rebuild env (mkSCC cc e') cont }
892 -- See notes with SimplMonad.inlineMode
893 simplNote env InlineMe e cont
894 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
895 = do { -- Don't inline inside an INLINE expression
896 e' <- simplExpr (setMode inlineMode env) e
897 ; rebuild env (mkInlineMe e') cont }
899 | otherwise -- Dissolve the InlineMe note if there's
900 -- an interesting context of any kind to combine with
901 -- (even a type application -- anything except Stop)
902 = simplExprF env e cont
904 simplNote env (CoreNote s) e cont
905 = simplExpr env e `thenSmpl` \ e' ->
906 rebuild env (Note (CoreNote s) e') cont
910 %************************************************************************
912 \subsection{Dealing with calls}
914 %************************************************************************
917 simplVar env var cont
918 = case substId env var of
919 DoneEx e -> simplExprF (zapSubstEnv env) e cont
920 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
921 DoneId var1 -> completeCall (zapSubstEnv env) var1 cont
922 -- Note [zapSubstEnv]
923 -- The template is already simplified, so don't re-substitute.
924 -- This is VITAL. Consider
926 -- let y = \z -> ...x... in
928 -- We'll clone the inner \x, adding x->x' in the id_subst
929 -- Then when we inline y, we must *not* replace x by x' in
930 -- the inlined copy!!
932 ---------------------------------------------------------
933 -- Dealing with a call site
935 completeCall env var cont
936 = do { dflags <- getDOptsSmpl
937 ; let (args,call_cont) = contArgs cont
938 -- The args are OutExprs, obtained by *lazily* substituting
939 -- in the args found in cont. These args are only examined
940 -- to limited depth (unless a rule fires). But we must do
941 -- the substitution; rule matching on un-simplified args would
944 ------------- First try rules ----------------
945 -- Do this before trying inlining. Some functions have
946 -- rules *and* are strict; in this case, we don't want to
947 -- inline the wrapper of the non-specialised thing; better
948 -- to call the specialised thing instead.
950 -- We used to use the black-listing mechanism to ensure that inlining of
951 -- the wrapper didn't occur for things that have specialisations till a
952 -- later phase, so but now we just try RULES first
954 -- You might think that we shouldn't apply rules for a loop breaker:
955 -- doing so might give rise to an infinite loop, because a RULE is
956 -- rather like an extra equation for the function:
957 -- RULE: f (g x) y = x+y
960 -- But it's too drastic to disable rules for loop breakers.
961 -- Even the foldr/build rule would be disabled, because foldr
962 -- is recursive, and hence a loop breaker:
963 -- foldr k z (build g) = g k z
964 -- So it's up to the programmer: rules can cause divergence
965 ; let in_scope = getInScope env
967 maybe_rule = case activeRule dflags env of
968 Nothing -> Nothing -- No rules apply
969 Just act_fn -> lookupRule act_fn in_scope
971 ; case maybe_rule of {
972 Just (rule, rule_rhs) ->
973 tick (RuleFired (ru_name rule)) `thenSmpl_`
974 (if dopt Opt_D_dump_rule_firings dflags then
975 pprTrace "Rule fired" (vcat [
976 text "Rule:" <+> ftext (ru_name rule),
977 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
978 text "After: " <+> pprCoreExpr rule_rhs,
979 text "Cont: " <+> ppr call_cont])
982 simplExprF env rule_rhs (dropArgs (ruleArity rule) cont)
983 -- The ruleArity says how many args the rule consumed
985 ; Nothing -> do -- No rules
987 ------------- Next try inlining ----------------
988 { let arg_infos = [interestingArg arg | arg <- args, isValArg arg]
989 n_val_args = length arg_infos
990 interesting_cont = interestingCallContext (notNull args)
993 active_inline = activeInline env var
994 maybe_inline = callSiteInline dflags active_inline
995 var arg_infos interesting_cont
996 ; case maybe_inline of {
997 Just unfolding -- There is an inlining!
998 -> do { tick (UnfoldingDone var)
999 ; (if dopt Opt_D_dump_inlinings dflags then
1000 pprTrace "Inlining done" (vcat [
1001 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1002 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1003 text "Cont: " <+> ppr call_cont])
1006 simplExprF env unfolding cont }
1008 ; Nothing -> -- No inlining!
1010 ------------- No inlining! ----------------
1011 -- Next, look for rules or specialisations that match
1013 rebuildCall env (Var var) (idType var)
1014 (mkArgInfo var n_val_args call_cont) cont
1017 rebuildCall :: SimplEnv
1018 -> OutExpr -> OutType -- Function and its type
1019 -> (Bool, [Bool]) -- See SimplUtils.mkArgInfo
1021 -> SimplM (SimplEnv, OutExpr)
1022 rebuildCall env fun fun_ty (has_rules, []) cont
1023 -- When we run out of strictness args, it means
1024 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1025 -- Then we want to discard the entire strict continuation. E.g.
1026 -- * case (error "hello") of { ... }
1027 -- * (error "Hello") arg
1028 -- * f (error "Hello") where f is strict
1030 -- Then, especially in the first of these cases, we'd like to discard
1031 -- the continuation, leaving just the bottoming expression. But the
1032 -- type might not be right, so we may have to add a coerce.
1033 | not (contIsTrivial cont) -- Only do thia if there is a non-trivial
1034 = return (env, mk_coerce fun) -- contination to discard, else we do it
1035 where -- again and again!
1036 cont_ty = contResultType cont
1037 co = mkUnsafeCoercion fun_ty cont_ty
1038 mk_coerce expr | cont_ty `coreEqType` fun_ty = fun
1039 | otherwise = mkCoerce co fun
1041 rebuildCall env fun fun_ty info (ApplyTo _ (Type arg_ty) se cont)
1042 = do { ty' <- simplType (se `setInScope` env) arg_ty
1043 ; rebuildCall env (fun `App` Type ty') (applyTy fun_ty ty') info cont }
1045 rebuildCall env fun fun_ty (has_rules, str:strs) (ApplyTo _ arg arg_se cont)
1046 | str || isStrictType arg_ty -- Strict argument
1047 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1048 simplExprF (arg_se `setFloats` env) arg
1049 (StrictArg fun fun_ty (has_rules, strs) cont)
1052 | otherwise -- Lazy argument
1053 -- DO NOT float anything outside, hence simplExprC
1054 -- There is no benefit (unlike in a let-binding), and we'd
1055 -- have to be very careful about bogus strictness through
1056 -- floating a demanded let.
1057 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1058 (mkLazyArgStop arg_ty has_rules)
1059 ; rebuildCall env (fun `App` arg') res_ty (has_rules, strs) cont }
1061 (arg_ty, res_ty) = splitFunTy fun_ty
1063 rebuildCall env fun fun_ty info cont
1064 = rebuild env fun cont
1069 This part of the simplifier may break the no-shadowing invariant
1071 f (...(\a -> e)...) (case y of (a,b) -> e')
1072 where f is strict in its second arg
1073 If we simplify the innermost one first we get (...(\a -> e)...)
1074 Simplifying the second arg makes us float the case out, so we end up with
1075 case y of (a,b) -> f (...(\a -> e)...) e'
1076 So the output does not have the no-shadowing invariant. However, there is
1077 no danger of getting name-capture, because when the first arg was simplified
1078 we used an in-scope set that at least mentioned all the variables free in its
1079 static environment, and that is enough.
1081 We can't just do innermost first, or we'd end up with a dual problem:
1082 case x of (a,b) -> f e (...(\a -> e')...)
1084 I spent hours trying to recover the no-shadowing invariant, but I just could
1085 not think of an elegant way to do it. The simplifier is already knee-deep in
1086 continuations. We have to keep the right in-scope set around; AND we have
1087 to get the effect that finding (error "foo") in a strict arg position will
1088 discard the entire application and replace it with (error "foo"). Getting
1089 all this at once is TOO HARD!
1091 %************************************************************************
1093 Rebuilding a cse expression
1095 %************************************************************************
1097 Blob of helper functions for the "case-of-something-else" situation.
1100 ---------------------------------------------------------
1101 -- Eliminate the case if possible
1103 rebuildCase :: SimplEnv
1104 -> OutExpr -- Scrutinee
1105 -> InId -- Case binder
1106 -> [InAlt] -- Alternatives (inceasing order)
1108 -> SimplM (SimplEnv, OutExpr)
1110 --------------------------------------------------
1111 -- 1. Eliminate the case if there's a known constructor
1112 --------------------------------------------------
1114 rebuildCase env scrut case_bndr alts cont
1115 | Just (con,args) <- exprIsConApp_maybe scrut
1116 -- Works when the scrutinee is a variable with a known unfolding
1117 -- as well as when it's an explicit constructor application
1118 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1120 | Lit lit <- scrut -- No need for same treatment as constructors
1121 -- because literals are inlined more vigorously
1122 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1125 --------------------------------------------------
1126 -- 2. Eliminate the case if scrutinee is evaluated
1127 --------------------------------------------------
1129 rebuildCase env scrut case_bndr [(con,bndrs,rhs)] cont
1130 -- See if we can get rid of the case altogether
1131 -- See the extensive notes on case-elimination above
1132 -- mkCase made sure that if all the alternatives are equal,
1133 -- then there is now only one (DEFAULT) rhs
1134 | all isDeadBinder bndrs -- bndrs are [InId]
1136 -- Check that the scrutinee can be let-bound instead of case-bound
1137 , exprOkForSpeculation scrut
1138 -- OK not to evaluate it
1139 -- This includes things like (==# a# b#)::Bool
1140 -- so that we simplify
1141 -- case ==# a# b# of { True -> x; False -> x }
1144 -- This particular example shows up in default methods for
1145 -- comparision operations (e.g. in (>=) for Int.Int32)
1146 || exprIsHNF scrut -- It's already evaluated
1147 || var_demanded_later scrut -- It'll be demanded later
1149 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1150 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1151 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1152 -- its argument: case x of { y -> dataToTag# y }
1153 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1154 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1156 -- Also we don't want to discard 'seq's
1157 = do { tick (CaseElim case_bndr)
1158 ; env <- simplNonRecX env case_bndr scrut
1159 ; simplExprF env rhs cont }
1161 -- The case binder is going to be evaluated later,
1162 -- and the scrutinee is a simple variable
1163 var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1164 && not (isTickBoxOp v)
1165 -- ugly hack; covering this case is what
1166 -- exprOkForSpeculation was intended for.
1167 var_demanded_later other = False
1170 --------------------------------------------------
1171 -- 3. Catch-all case
1172 --------------------------------------------------
1174 rebuildCase env scrut case_bndr alts cont
1175 = do { -- Prepare the continuation;
1176 -- The new subst_env is in place
1177 (env, dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1179 -- Simplify the alternatives
1180 ; (case_bndr', alts') <- simplAlts env scrut case_bndr alts dup_cont
1181 ; let res_ty' = contResultType dup_cont
1182 ; case_expr <- mkCase scrut case_bndr' res_ty' alts'
1184 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1185 -- The case binder *not* scope over the whole returned case-expression
1186 ; rebuild env case_expr nodup_cont }
1189 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1190 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1191 way, there's a chance that v will now only be used once, and hence
1194 Note [no-case-of-case]
1195 ~~~~~~~~~~~~~~~~~~~~~~
1196 There is a time we *don't* want to do that, namely when
1197 -fno-case-of-case is on. This happens in the first simplifier pass,
1198 and enhances full laziness. Here's the bad case:
1199 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1200 If we eliminate the inner case, we trap it inside the I# v -> arm,
1201 which might prevent some full laziness happening. I've seen this
1202 in action in spectral/cichelli/Prog.hs:
1203 [(m,n) | m <- [1..max], n <- [1..max]]
1204 Hence the check for NoCaseOfCase.
1206 Note [Suppressing the case binder-swap]
1207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1208 There is another situation when it might make sense to suppress the
1209 case-expression binde-swap. If we have
1211 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1212 ...other cases .... }
1214 We'll perform the binder-swap for the outer case, giving
1216 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1217 ...other cases .... }
1219 But there is no point in doing it for the inner case, because w1 can't
1220 be inlined anyway. Furthermore, doing the case-swapping involves
1221 zapping w2's occurrence info (see paragraphs that follow), and that
1222 forces us to bind w2 when doing case merging. So we get
1224 case x of w1 { A -> let w2 = w1 in e1
1225 B -> let w2 = w1 in e2
1226 ...other cases .... }
1228 This is plain silly in the common case where w2 is dead.
1230 Even so, I can't see a good way to implement this idea. I tried
1231 not doing the binder-swap if the scrutinee was already evaluated
1232 but that failed big-time:
1236 case v of w { MkT x ->
1237 case x of x1 { I# y1 ->
1238 case x of x2 { I# y2 -> ...
1240 Notice that because MkT is strict, x is marked "evaluated". But to
1241 eliminate the last case, we must either make sure that x (as well as
1242 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1243 the binder-swap. So this whole note is a no-op.
1247 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1248 any occurrence info (eg IAmDead) in the case binder, because the
1249 case-binder now effectively occurs whenever v does. AND we have to do
1250 the same for the pattern-bound variables! Example:
1252 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1254 Here, b and p are dead. But when we move the argment inside the first
1255 case RHS, and eliminate the second case, we get
1257 case x of { (a,b) -> a b }
1259 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1262 Indeed, this can happen anytime the case binder isn't dead:
1263 case <any> of x { (a,b) ->
1264 case x of { (p,q) -> p } }
1265 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1266 The point is that we bring into the envt a binding
1268 after the outer case, and that makes (a,b) alive. At least we do unless
1269 the case binder is guaranteed dead.
1273 Consider case (v `cast` co) of x { I# ->
1274 ... (case (v `cast` co) of {...}) ...
1275 We'd like to eliminate the inner case. We can get this neatly by
1276 arranging that inside the outer case we add the unfolding
1277 v |-> x `cast` (sym co)
1278 to v. Then we should inline v at the inner case, cancel the casts, and away we go
1281 Note [Case elimination]
1282 ~~~~~~~~~~~~~~~~~~~~~~~
1283 The case-elimination transformation discards redundant case expressions.
1284 Start with a simple situation:
1286 case x# of ===> e[x#/y#]
1289 (when x#, y# are of primitive type, of course). We can't (in general)
1290 do this for algebraic cases, because we might turn bottom into
1293 The code in SimplUtils.prepareAlts has the effect of generalise this
1294 idea to look for a case where we're scrutinising a variable, and we
1295 know that only the default case can match. For example:
1299 DEFAULT -> ...(case x of
1303 Here the inner case is first trimmed to have only one alternative, the
1304 DEFAULT, after which it's an instance of the previous case. This
1305 really only shows up in eliminating error-checking code.
1307 We also make sure that we deal with this very common case:
1312 Here we are using the case as a strict let; if x is used only once
1313 then we want to inline it. We have to be careful that this doesn't
1314 make the program terminate when it would have diverged before, so we
1316 - e is already evaluated (it may so if e is a variable)
1317 - x is used strictly, or
1319 Lastly, the code in SimplUtils.mkCase combines identical RHSs. So
1321 case e of ===> case e of DEFAULT -> r
1325 Now again the case may be elminated by the CaseElim transformation.
1328 Further notes about case elimination
1329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1330 Consider: test :: Integer -> IO ()
1333 Turns out that this compiles to:
1336 eta1 :: State# RealWorld ->
1337 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1339 (PrelNum.jtos eta ($w[] @ Char))
1341 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1343 Notice the strange '<' which has no effect at all. This is a funny one.
1344 It started like this:
1346 f x y = if x < 0 then jtos x
1347 else if y==0 then "" else jtos x
1349 At a particular call site we have (f v 1). So we inline to get
1351 if v < 0 then jtos x
1352 else if 1==0 then "" else jtos x
1354 Now simplify the 1==0 conditional:
1356 if v<0 then jtos v else jtos v
1358 Now common-up the two branches of the case:
1360 case (v<0) of DEFAULT -> jtos v
1362 Why don't we drop the case? Because it's strict in v. It's technically
1363 wrong to drop even unnecessary evaluations, and in practice they
1364 may be a result of 'seq' so we *definitely* don't want to drop those.
1365 I don't really know how to improve this situation.
1369 simplCaseBinder :: SimplEnv -> OutExpr -> InId -> SimplM (SimplEnv, OutId)
1370 simplCaseBinder env scrut case_bndr
1371 | switchIsOn (getSwitchChecker env) NoCaseOfCase
1372 -- See Note [no-case-of-case]
1373 = do { (env, case_bndr') <- simplBinder env case_bndr
1374 ; return (env, case_bndr') }
1376 simplCaseBinder env (Var v) case_bndr
1377 -- Failed try [see Note 2 above]
1378 -- not (isEvaldUnfolding (idUnfolding v))
1379 = do { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1380 ; return (modifyInScope env v case_bndr', case_bndr') }
1381 -- We could extend the substitution instead, but it would be
1382 -- a hack because then the substitution wouldn't be idempotent
1383 -- any more (v is an OutId). And this does just as well.
1385 simplCaseBinder env (Cast (Var v) co) case_bndr -- Note [Case of cast]
1386 = do { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1387 ; let rhs = Cast (Var case_bndr') (mkSymCoercion co)
1388 ; return (addBinderUnfolding env v rhs, case_bndr') }
1390 simplCaseBinder env other_scrut case_bndr
1391 = do { (env, case_bndr') <- simplBinder env case_bndr
1392 ; return (env, case_bndr') }
1394 zapOccInfo :: InId -> InId -- See Note [zapOccInfo]
1395 zapOccInfo b = b `setIdOccInfo` NoOccInfo
1399 simplAlts does two things:
1401 1. Eliminate alternatives that cannot match, including the
1402 DEFAULT alternative.
1404 2. If the DEFAULT alternative can match only one possible constructor,
1405 then make that constructor explicit.
1407 case e of x { DEFAULT -> rhs }
1409 case e of x { (a,b) -> rhs }
1410 where the type is a single constructor type. This gives better code
1411 when rhs also scrutinises x or e.
1413 Here "cannot match" includes knowledge from GADTs
1415 It's a good idea do do this stuff before simplifying the alternatives, to
1416 avoid simplifying alternatives we know can't happen, and to come up with
1417 the list of constructors that are handled, to put into the IdInfo of the
1418 case binder, for use when simplifying the alternatives.
1420 Eliminating the default alternative in (1) isn't so obvious, but it can
1423 data Colour = Red | Green | Blue
1432 DEFAULT -> [ case y of ... ]
1434 If we inline h into f, the default case of the inlined h can't happen.
1435 If we don't notice this, we may end up filtering out *all* the cases
1436 of the inner case y, which give us nowhere to go!
1440 simplAlts :: SimplEnv
1442 -> InId -- Case binder
1443 -> [InAlt] -> SimplCont
1444 -> SimplM (OutId, [OutAlt]) -- Includes the continuation
1445 -- Like simplExpr, this just returns the simplified alternatives;
1446 -- it not return an environment
1448 simplAlts env scrut case_bndr alts cont'
1449 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1450 do { let alt_env = zapFloats env
1451 ; (alt_env, case_bndr') <- simplCaseBinder alt_env scrut case_bndr
1453 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut case_bndr' alts
1455 ; alts' <- mapM (simplAlt alt_env imposs_deflt_cons case_bndr' cont') in_alts
1456 ; return (case_bndr', alts') }
1458 ------------------------------------
1459 simplAlt :: SimplEnv
1460 -> [AltCon] -- These constructors can't be present when
1461 -- matching the DEFAULT alternative
1462 -> OutId -- The case binder
1467 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1468 = ASSERT( null bndrs )
1469 do { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1470 -- Record the constructors that the case-binder *can't* be.
1471 ; rhs' <- simplExprC env' rhs cont'
1472 ; return (DEFAULT, [], rhs') }
1474 simplAlt env imposs_deflt_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1475 = ASSERT( null bndrs )
1476 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1477 ; rhs' <- simplExprC env' rhs cont'
1478 ; return (LitAlt lit, [], rhs') }
1480 simplAlt env imposs_deflt_cons case_bndr' cont' (DataAlt con, vs, rhs)
1481 = do { -- Deal with the pattern-bound variables
1482 (env, vs') <- simplBinders env (add_evals con vs)
1484 -- Mark the ones that are in ! positions in the
1485 -- data constructor as certainly-evaluated.
1486 ; let vs'' = add_evals con vs'
1488 -- Bind the case-binder to (con args)
1489 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1490 con_args = map Type inst_tys' ++ varsToCoreExprs vs''
1491 env' = addBinderUnfolding env case_bndr' (mkConApp con con_args)
1493 ; rhs' <- simplExprC env' rhs cont'
1494 ; return (DataAlt con, vs'', rhs') }
1496 -- add_evals records the evaluated-ness of the bound variables of
1497 -- a case pattern. This is *important*. Consider
1498 -- data T = T !Int !Int
1500 -- case x of { T a b -> T (a+1) b }
1502 -- We really must record that b is already evaluated so that we don't
1503 -- go and re-evaluate it when constructing the result.
1504 -- See Note [Data-con worker strictness] in MkId.lhs
1505 add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1507 cat_evals dc vs strs
1511 go (v:vs) strs | isTyVar v = v : go vs strs
1512 go (v:vs) (str:strs)
1513 | isMarkedStrict str = evald_v : go vs strs
1514 | otherwise = zapped_v : go vs strs
1516 zapped_v = zap_occ_info v
1517 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1518 go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1520 -- If the case binder is alive, then we add the unfolding
1522 -- to the envt; so vs are now very much alive
1523 -- Note [Aug06] I can't see why this actually matters
1524 zap_occ_info | isDeadBinder case_bndr' = \id -> id
1525 | otherwise = zapOccInfo
1527 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1528 addBinderUnfolding env bndr rhs
1529 = modifyInScope env bndr (bndr `setIdUnfolding` mkUnfolding False rhs)
1531 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1532 addBinderOtherCon env bndr cons
1533 = modifyInScope env bndr (bndr `setIdUnfolding` mkOtherCon cons)
1537 %************************************************************************
1539 \subsection{Known constructor}
1541 %************************************************************************
1543 We are a bit careful with occurrence info. Here's an example
1545 (\x* -> case x of (a*, b) -> f a) (h v, e)
1547 where the * means "occurs once". This effectively becomes
1548 case (h v, e) of (a*, b) -> f a)
1550 let a* = h v; b = e in f a
1554 All this should happen in one sweep.
1557 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1558 -> InId -> [InAlt] -> SimplCont
1559 -> SimplM (SimplEnv, OutExpr)
1561 knownCon env scrut con args bndr alts cont
1562 = do { tick (KnownBranch bndr)
1563 ; knownAlt env scrut args bndr (findAlt con alts) cont }
1565 knownAlt env scrut args bndr (DEFAULT, bs, rhs) cont
1567 do { env <- simplNonRecX env bndr scrut
1568 -- This might give rise to a binding with non-atomic args
1569 -- like x = Node (f x) (g x)
1570 -- but simplNonRecX will atomic-ify it
1571 ; simplExprF env rhs cont }
1573 knownAlt env scrut args bndr (LitAlt lit, bs, rhs) cont
1575 do { env <- simplNonRecX env bndr scrut
1576 ; simplExprF env rhs cont }
1578 knownAlt env scrut args bndr (DataAlt dc, bs, rhs) cont
1579 = do { let dead_bndr = isDeadBinder bndr -- bndr is an InId
1580 n_drop_tys = length (dataConUnivTyVars dc)
1581 ; env <- bind_args env dead_bndr bs (drop n_drop_tys args)
1583 -- It's useful to bind bndr to scrut, rather than to a fresh
1584 -- binding x = Con arg1 .. argn
1585 -- because very often the scrut is a variable, so we avoid
1586 -- creating, and then subsequently eliminating, a let-binding
1587 -- BUT, if scrut is a not a variable, we must be careful
1588 -- about duplicating the arg redexes; in that case, make
1589 -- a new con-app from the args
1590 bndr_rhs = case scrut of
1593 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1594 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1595 -- args are aready OutExprs, but bs are InIds
1597 ; env <- simplNonRecX env bndr bndr_rhs
1598 ; -- pprTrace "knownCon2" (ppr bs $$ ppr rhs $$ ppr (seIdSubst env)) $
1599 simplExprF env rhs cont }
1602 bind_args env dead_bndr [] _ = return env
1604 bind_args env dead_bndr (b:bs) (Type ty : args)
1605 = ASSERT( isTyVar b )
1606 bind_args (extendTvSubst env b ty) dead_bndr bs args
1608 bind_args env dead_bndr (b:bs) (arg : args)
1610 do { let b' = if dead_bndr then b else zapOccInfo b
1611 -- Note that the binder might be "dead", because it doesn't occur
1612 -- in the RHS; and simplNonRecX may therefore discard it via postInlineUnconditionally
1613 -- Nevertheless we must keep it if the case-binder is alive, because it may
1614 -- be used in the con_app. See Note [zapOccInfo]
1615 ; env <- simplNonRecX env b' arg
1616 ; bind_args env dead_bndr bs args }
1618 bind_args _ _ _ _ = panic "bind_args"
1622 %************************************************************************
1624 \subsection{Duplicating continuations}
1626 %************************************************************************
1629 prepareCaseCont :: SimplEnv
1630 -> [InAlt] -> SimplCont
1631 -> SimplM (SimplEnv, SimplCont,SimplCont)
1632 -- Return a duplicatable continuation, a non-duplicable part
1633 -- plus some extra bindings (that scope over the entire
1636 -- No need to make it duplicatable if there's only one alternative
1637 prepareCaseCont env [alt] cont = return (env, cont, mkBoringStop (contResultType cont))
1638 prepareCaseCont env alts cont = mkDupableCont env cont
1642 mkDupableCont :: SimplEnv -> SimplCont
1643 -> SimplM (SimplEnv, SimplCont, SimplCont)
1645 mkDupableCont env cont
1646 | contIsDupable cont
1647 = returnSmpl (env, cont, mkBoringStop (contResultType cont))
1649 mkDupableCont env (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1651 mkDupableCont env (CoerceIt ty cont)
1652 = do { (env, dup, nodup) <- mkDupableCont env cont
1653 ; return (env, CoerceIt ty dup, nodup) }
1655 mkDupableCont env cont@(StrictBind bndr _ _ se _)
1656 = return (env, mkBoringStop (substTy se (idType bndr)), cont)
1657 -- See Note [Duplicating strict continuations]
1659 mkDupableCont env cont@(StrictArg _ fun_ty _ _)
1660 = return (env, mkBoringStop (funArgTy fun_ty), cont)
1661 -- See Note [Duplicating strict continuations]
1663 mkDupableCont env (ApplyTo _ arg se cont)
1664 = -- e.g. [...hole...] (...arg...)
1666 -- let a = ...arg...
1667 -- in [...hole...] a
1668 do { (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1669 ; arg <- simplExpr (se `setInScope` env) arg
1670 ; (env, arg) <- makeTrivial env arg
1671 ; let app_cont = ApplyTo OkToDup arg (zapSubstEnv env) dup_cont
1672 ; return (env, app_cont, nodup_cont) }
1674 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1675 -- See Note [Single-alternative case]
1676 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1677 -- | not (isDeadBinder case_bndr)
1678 | all isDeadBinder bs -- InIds
1679 = return (env, mkBoringStop scrut_ty, cont)
1681 scrut_ty = substTy se (idType case_bndr)
1683 mkDupableCont env (Select _ case_bndr alts se cont)
1684 = -- e.g. (case [...hole...] of { pi -> ei })
1686 -- let ji = \xij -> ei
1687 -- in case [...hole...] of { pi -> ji xij }
1688 do { tick (CaseOfCase case_bndr)
1689 ; (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1690 -- NB: call mkDupableCont here, *not* prepareCaseCont
1691 -- We must make a duplicable continuation, whereas prepareCaseCont
1692 -- doesn't when there is a single case branch
1694 ; let alt_env = se `setInScope` env
1695 ; (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1696 ; alts' <- mapM (simplAlt alt_env [] case_bndr' dup_cont) alts
1697 -- Safe to say that there are no handled-cons for the DEFAULT case
1698 -- NB: simplBinder does not zap deadness occ-info, so
1699 -- a dead case_bndr' will still advertise its deadness
1700 -- This is really important because in
1701 -- case e of b { (# p,q #) -> ... }
1702 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1703 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1704 -- In the new alts we build, we have the new case binder, so it must retain
1706 -- NB: we don't use alt_env further; it has the substEnv for
1707 -- the alternatives, and we don't want that
1709 ; (env, alts') <- mkDupableAlts env case_bndr' alts'
1710 ; return (env, -- Note [Duplicated env]
1711 Select OkToDup case_bndr' alts' (zapSubstEnv env)
1712 (mkBoringStop (contResultType dup_cont)),
1716 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1717 -> SimplM (SimplEnv, [InAlt])
1718 -- Absorbs the continuation into the new alternatives
1720 mkDupableAlts env case_bndr' alts
1723 go env [] = return (env, [])
1725 = do { (env, alt') <- mkDupableAlt env case_bndr' alt
1726 ; (env, alts') <- go env alts
1727 ; return (env, alt' : alts' ) }
1729 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1730 | exprIsDupable rhs' -- Note [Small alternative rhs]
1731 = return (env, (con, bndrs', rhs'))
1733 = do { let rhs_ty' = exprType rhs'
1734 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1736 | isTyVar bndr = True -- Abstract over all type variables just in case
1737 | otherwise = not (isDeadBinder bndr)
1738 -- The deadness info on the new Ids is preserved by simplBinders
1740 ; (final_bndrs', final_args) -- Note [Join point abstraction]
1741 <- if (any isId used_bndrs')
1742 then return (used_bndrs', varsToCoreExprs used_bndrs')
1743 else do { rw_id <- newId FSLIT("w") realWorldStatePrimTy
1744 ; return ([rw_id], [Var realWorldPrimId]) }
1746 ; join_bndr <- newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty')
1747 -- Note [Funky mkPiTypes]
1749 ; let -- We make the lambdas into one-shot-lambdas. The
1750 -- join point is sure to be applied at most once, and doing so
1751 -- prevents the body of the join point being floated out by
1752 -- the full laziness pass
1753 really_final_bndrs = map one_shot final_bndrs'
1754 one_shot v | isId v = setOneShotLambda v
1756 join_rhs = mkLams really_final_bndrs rhs'
1757 join_call = mkApps (Var join_bndr) final_args
1759 ; return (addNonRec env join_bndr join_rhs, (con, bndrs', join_call)) }
1760 -- See Note [Duplicated env]
1763 Note [Duplicated env]
1764 ~~~~~~~~~~~~~~~~~~~~~
1765 Some of the alternatives are simplified, but have not been turned into a join point
1766 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
1767 bind the join point, because it might to do PostInlineUnconditionally, and
1768 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
1769 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1770 at worst delays the join-point inlining.
1772 Note [Small alterantive rhs]
1773 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1774 It is worth checking for a small RHS because otherwise we
1775 get extra let bindings that may cause an extra iteration of the simplifier to
1776 inline back in place. Quite often the rhs is just a variable or constructor.
1777 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1778 iterations because the version with the let bindings looked big, and so wasn't
1779 inlined, but after the join points had been inlined it looked smaller, and so
1782 NB: we have to check the size of rhs', not rhs.
1783 Duplicating a small InAlt might invalidate occurrence information
1784 However, if it *is* dupable, we return the *un* simplified alternative,
1785 because otherwise we'd need to pair it up with an empty subst-env....
1786 but we only have one env shared between all the alts.
1787 (Remember we must zap the subst-env before re-simplifying something).
1788 Rather than do this we simply agree to re-simplify the original (small) thing later.
1790 Note [Funky mkPiTypes]
1791 ~~~~~~~~~~~~~~~~~~~~~~
1792 Notice the funky mkPiTypes. If the contructor has existentials
1793 it's possible that the join point will be abstracted over
1794 type varaibles as well as term variables.
1795 Example: Suppose we have
1796 data T = forall t. C [t]
1798 case (case e of ...) of
1800 We get the join point
1801 let j :: forall t. [t] -> ...
1802 j = /\t \xs::[t] -> rhs
1804 case (case e of ...) of
1805 C t xs::[t] -> j t xs
1807 Note [Join point abstaction]
1808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1809 If we try to lift a primitive-typed something out
1810 for let-binding-purposes, we will *caseify* it (!),
1811 with potentially-disastrous strictness results. So
1812 instead we turn it into a function: \v -> e
1813 where v::State# RealWorld#. The value passed to this function
1814 is realworld#, which generates (almost) no code.
1816 There's a slight infelicity here: we pass the overall
1817 case_bndr to all the join points if it's used in *any* RHS,
1818 because we don't know its usage in each RHS separately
1820 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1821 we make the join point into a function whenever used_bndrs'
1822 is empty. This makes the join-point more CPR friendly.
1823 Consider: let j = if .. then I# 3 else I# 4
1824 in case .. of { A -> j; B -> j; C -> ... }
1826 Now CPR doesn't w/w j because it's a thunk, so
1827 that means that the enclosing function can't w/w either,
1828 which is a lose. Here's the example that happened in practice:
1829 kgmod :: Int -> Int -> Int
1830 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1834 I have seen a case alternative like this:
1836 It's a bit silly to add the realWorld dummy arg in this case, making
1839 (the \v alone is enough to make CPR happy) but I think it's rare
1841 Note [Duplicating strict continuations]
1842 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1843 Do *not* duplicate StrictBind and StritArg continuations. We gain
1844 nothing by propagating them into the expressions, and we do lose a
1845 lot. Here's an example:
1846 && (case x of { T -> F; F -> T }) E
1847 Now, && is strict so we end up simplifying the case with
1848 an ArgOf continuation. If we let-bind it, we get
1850 let $j = \v -> && v E
1851 in simplExpr (case x of { T -> F; F -> T })
1853 And after simplifying more we get
1855 let $j = \v -> && v E
1856 in case x of { T -> $j F; F -> $j T }
1857 Which is a Very Bad Thing
1859 The desire not to duplicate is the entire reason that
1860 mkDupableCont returns a pair of continuations.
1862 The original plan had:
1863 e.g. (...strict-fn...) [...hole...]
1865 let $j = \a -> ...strict-fn...
1868 Note [Single-alternative cases]
1869 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1870 This case is just like the ArgOf case. Here's an example:
1874 case (case x of I# x' ->
1876 True -> I# (negate# x')
1877 False -> I# x') of y {
1879 Because the (case x) has only one alternative, we'll transform to
1881 case (case x' <# 0# of
1882 True -> I# (negate# x')
1883 False -> I# x') of y {
1885 But now we do *NOT* want to make a join point etc, giving
1887 let $j = \y -> MkT y
1889 True -> $j (I# (negate# x'))
1891 In this case the $j will inline again, but suppose there was a big
1892 strict computation enclosing the orginal call to MkT. Then, it won't
1893 "see" the MkT any more, because it's big and won't get duplicated.
1894 And, what is worse, nothing was gained by the case-of-case transform.
1896 When should use this case of mkDupableCont?
1897 However, matching on *any* single-alternative case is a *disaster*;
1898 e.g. case (case ....) of (a,b) -> (# a,b #)
1899 We must push the outer case into the inner one!
1902 * Match [(DEFAULT,_,_)], but in the common case of Int,
1903 the alternative-filling-in code turned the outer case into
1904 case (...) of y { I# _ -> MkT y }
1906 * Match on single alternative plus (not (isDeadBinder case_bndr))
1907 Rationale: pushing the case inwards won't eliminate the construction.
1908 But there's a risk of
1909 case (...) of y { (a,b) -> let z=(a,b) in ... }
1910 Now y looks dead, but it'll come alive again. Still, this
1911 seems like the best option at the moment.
1913 * Match on single alternative plus (all (isDeadBinder bndrs))
1914 Rationale: this is essentially seq.
1916 * Match when the rhs is *not* duplicable, and hence would lead to a
1917 join point. This catches the disaster-case above. We can test
1918 the *un-simplified* rhs, which is fine. It might get bigger or
1919 smaller after simplification; if it gets smaller, this case might
1920 fire next time round. NB also that we must test contIsDupable
1921 case_cont *btoo, because case_cont might be big!
1923 HOWEVER: I found that this version doesn't work well, because
1924 we can get let x = case (...) of { small } in ...case x...
1925 When x is inlined into its full context, we find that it was a bad
1926 idea to have pushed the outer case inside the (...) case.