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 TcGadt ( dataConCanMatch )
21 import DataCon ( dataConTyCon, dataConRepStrictness )
22 import TyCon ( tyConArity, isAlgTyCon, isNewTyCon, tyConDataCons_maybe )
24 import PprCore ( pprParendExpr, pprCoreExpr )
25 import CoreUnfold ( mkUnfolding, callSiteInline )
27 import Rules ( lookupRule )
28 import BasicTypes ( isMarkedStrict )
29 import CostCentre ( currentCCS )
30 import TysPrim ( realWorldStatePrimTy )
31 import PrelInfo ( realWorldPrimId )
32 import BasicTypes ( TopLevelFlag(..), isTopLevel,
33 RecFlag(..), isNonRuleLoopBreaker )
35 import Maybes ( orElse )
41 The guts of the simplifier is in this module, but the driver loop for
42 the simplifier is in SimplCore.lhs.
45 -----------------------------------------
46 *** IMPORTANT NOTE ***
47 -----------------------------------------
48 The simplifier used to guarantee that the output had no shadowing, but
49 it does not do so any more. (Actually, it never did!) The reason is
50 documented with simplifyArgs.
53 -----------------------------------------
54 *** IMPORTANT NOTE ***
55 -----------------------------------------
56 Many parts of the simplifier return a bunch of "floats" as well as an
57 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
59 All "floats" are let-binds, not case-binds, but some non-rec lets may
60 be unlifted (with RHS ok-for-speculation).
64 -----------------------------------------
65 ORGANISATION OF FUNCTIONS
66 -----------------------------------------
68 - simplify all top-level binders
69 - for NonRec, call simplRecOrTopPair
70 - for Rec, call simplRecBind
73 ------------------------------
74 simplExpr (applied lambda) ==> simplNonRecBind
75 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
76 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
78 ------------------------------
79 simplRecBind [binders already simplfied]
80 - use simplRecOrTopPair on each pair in turn
82 simplRecOrTopPair [binder already simplified]
83 Used for: recursive bindings (top level and nested)
84 top-level non-recursive bindings
86 - check for PreInlineUnconditionally
90 Used for: non-top-level non-recursive bindings
91 beta reductions (which amount to the same thing)
92 Because it can deal with strict arts, it takes a
93 "thing-inside" and returns an expression
95 - check for PreInlineUnconditionally
96 - simplify binder, including its IdInfo
105 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
106 Used for: binding case-binder and constr args in a known-constructor case
107 - check for PreInLineUnconditionally
111 ------------------------------
112 simplLazyBind: [binder already simplified, RHS not]
113 Used for: recursive bindings (top level and nested)
114 top-level non-recursive bindings
115 non-top-level, but *lazy* non-recursive bindings
116 [must not be strict or unboxed]
117 Returns floats + an augmented environment, not an expression
118 - substituteIdInfo and add result to in-scope
119 [so that rules are available in rec rhs]
122 - float if exposes constructor or PAP
126 completeNonRecX: [binder and rhs both simplified]
127 - if the the thing needs case binding (unlifted and not ok-for-spec)
133 completeBind: [given a simplified RHS]
134 [used for both rec and non-rec bindings, top level and not]
135 - try PostInlineUnconditionally
136 - add unfolding [this is the only place we add an unfolding]
141 Right hand sides and arguments
142 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
143 In many ways we want to treat
144 (a) the right hand side of a let(rec), and
145 (b) a function argument
146 in the same way. But not always! In particular, we would
147 like to leave these arguments exactly as they are, so they
148 will match a RULE more easily.
153 It's harder to make the rule match if we ANF-ise the constructor,
154 or eta-expand the PAP:
156 f (let { a = g x; b = h x } in (a,b))
159 On the other hand if we see the let-defns
164 then we *do* want to ANF-ise and eta-expand, so that p and q
165 can be safely inlined.
167 Even floating lets out is a bit dubious. For let RHS's we float lets
168 out if that exposes a value, so that the value can be inlined more vigorously.
171 r = let x = e in (x,x)
173 Here, if we float the let out we'll expose a nice constructor. We did experiments
174 that showed this to be a generally good thing. But it was a bad thing to float
175 lets out unconditionally, because that meant they got allocated more often.
177 For function arguments, there's less reason to expose a constructor (it won't
178 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
179 So for the moment we don't float lets out of function arguments either.
184 For eta expansion, we want to catch things like
186 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
188 If the \x was on the RHS of a let, we'd eta expand to bring the two
189 lambdas together. And in general that's a good thing to do. Perhaps
190 we should eta expand wherever we find a (value) lambda? Then the eta
191 expansion at a let RHS can concentrate solely on the PAP case.
194 %************************************************************************
196 \subsection{Bindings}
198 %************************************************************************
201 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
203 simplTopBinds env binds
204 = do { -- Put all the top-level binders into scope at the start
205 -- so that if a transformation rule has unexpectedly brought
206 -- anything into scope, then we don't get a complaint about that.
207 -- It's rather as if the top-level binders were imported.
208 ; env <- simplRecBndrs env (bindersOfBinds binds)
209 ; dflags <- getDOptsSmpl
210 ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
211 dopt Opt_D_dump_rule_firings dflags
212 ; env' <- simpl_binds dump_flag env binds
213 ; freeTick SimplifierDone
214 ; return (getFloats env') }
216 -- We need to track the zapped top-level binders, because
217 -- they should have their fragile IdInfo zapped (notably occurrence info)
218 -- That's why we run down binds and bndrs' simultaneously.
220 -- The dump-flag emits a trace for each top-level binding, which
221 -- helps to locate the tracing for inlining and rule firing
222 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
223 simpl_binds dump env [] = return env
224 simpl_binds dump env (bind:binds) = do { env' <- trace dump bind $
226 ; simpl_binds dump env' binds }
228 trace True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
229 trace False bind = \x -> x
231 simpl_bind env (NonRec b r) = simplRecOrTopPair env TopLevel b r
232 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
236 %************************************************************************
238 \subsection{Lazy bindings}
240 %************************************************************************
242 simplRecBind is used for
243 * recursive bindings only
246 simplRecBind :: SimplEnv -> TopLevelFlag
249 simplRecBind env top_lvl pairs
250 = do { env' <- go (zapFloats env) pairs
251 ; return (env `addRecFloats` env') }
252 -- addFloats adds the floats from env',
253 -- *and* updates env with the in-scope set from env'
255 go env [] = return env
257 go env ((bndr, rhs) : pairs)
258 = do { env <- simplRecOrTopPair env top_lvl bndr rhs
262 simplOrTopPair is used for
263 * recursive bindings (whether top level or not)
264 * top-level non-recursive bindings
266 It assumes the binder has already been simplified, but not its IdInfo.
269 simplRecOrTopPair :: SimplEnv
271 -> InId -> InExpr -- Binder and rhs
272 -> SimplM SimplEnv -- Returns an env that includes the binding
274 simplRecOrTopPair env top_lvl bndr rhs
275 | preInlineUnconditionally env top_lvl bndr rhs -- Check for unconditional inline
276 = do { tick (PreInlineUnconditionally bndr)
277 ; return (extendIdSubst env bndr (mkContEx env rhs)) }
280 = do { let bndr' = lookupRecBndr env bndr
281 (env', bndr'') = addLetIdInfo env bndr bndr'
282 ; simplLazyBind env' top_lvl Recursive bndr bndr'' rhs env' }
283 -- May not actually be recursive, but it doesn't matter
287 simplLazyBind is used for
288 * [simplRecOrTopPair] recursive bindings (whether top level or not)
289 * [simplRecOrTopPair] top-level non-recursive bindings
290 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
293 1. It assumes that the binder is *already* simplified,
294 and is in scope, and its IdInfo too, except unfolding
296 2. It assumes that the binder type is lifted.
298 3. It does not check for pre-inline-unconditionallly;
299 that should have been done already.
302 simplLazyBind :: SimplEnv
303 -> TopLevelFlag -> RecFlag
304 -> InId -> OutId -- Binder, both pre-and post simpl
305 -- The OutId has IdInfo, except arity, unfolding
306 -> InExpr -> SimplEnv -- The RHS and its environment
309 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
310 = do { let rhs_env = rhs_se `setInScope` env
311 rhs_cont = mkRhsStop (idType bndr1)
313 -- Simplify the RHS; note the mkRhsStop, which tells
314 -- the simplifier that this is the RHS of a let.
315 ; (rhs_env1, rhs1) <- simplExprF rhs_env rhs rhs_cont
317 -- If any of the floats can't be floated, give up now
318 -- (The canFloat predicate says True for empty floats.)
319 ; if (not (canFloat top_lvl is_rec False rhs_env1))
320 then completeBind env top_lvl bndr bndr1
321 (wrapFloats rhs_env1 rhs1)
323 -- ANF-ise a constructor or PAP rhs
324 { (rhs_env2, rhs2) <- prepareRhs rhs_env1 rhs1
325 ; (env', rhs3) <- chooseRhsFloats top_lvl is_rec False env rhs_env2 rhs2
326 ; completeBind env' top_lvl bndr bndr1 rhs3 } }
328 chooseRhsFloats :: TopLevelFlag -> RecFlag -> Bool
329 -> SimplEnv -- Env for the let
330 -> SimplEnv -- Env for the RHS, with RHS floats in it
331 -> OutExpr -- ..and the RHS itself
332 -> SimplM (SimplEnv, OutExpr) -- New env for let, and RHS
334 chooseRhsFloats top_lvl is_rec is_strict env rhs_env rhs
335 | not (isEmptyFloats rhs_env) -- Something to float
336 , canFloat top_lvl is_rec is_strict rhs_env -- ...that can float
337 , (isTopLevel top_lvl || exprIsCheap rhs) -- ...and we want to float
338 = do { tick LetFloatFromLet -- Float
339 ; return (addFloats env rhs_env, rhs) } -- Add the floats to the main env
340 | otherwise -- Don't float
341 = return (env, wrapFloats rhs_env rhs) -- Wrap the floats around the RHS
345 %************************************************************************
347 \subsection{simplNonRec}
349 %************************************************************************
351 A specialised variant of simplNonRec used when the RHS is already simplified,
352 notably in knownCon. It uses case-binding where necessary.
355 simplNonRecX :: SimplEnv
356 -> InId -- Old binder
357 -> OutExpr -- Simplified RHS
360 simplNonRecX env bndr new_rhs
361 = do { (env, bndr') <- simplBinder env bndr
362 ; completeNonRecX env NotTopLevel NonRecursive
363 (isStrictId bndr) bndr bndr' new_rhs }
365 completeNonRecX :: SimplEnv
366 -> TopLevelFlag -> RecFlag -> Bool
367 -> InId -- Old binder
368 -> OutId -- New binder
369 -> OutExpr -- Simplified RHS
372 completeNonRecX env top_lvl is_rec is_strict old_bndr new_bndr new_rhs
373 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
374 ; (env2, rhs2) <- chooseRhsFloats top_lvl is_rec is_strict env env1 rhs1
375 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
378 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
379 Doing so risks exponential behaviour, because new_rhs has been simplified once already
380 In the cases described by the folowing commment, postInlineUnconditionally will
381 catch many of the relevant cases.
382 -- This happens; for example, the case_bndr during case of
383 -- known constructor: case (a,b) of x { (p,q) -> ... }
384 -- Here x isn't mentioned in the RHS, so we don't want to
385 -- create the (dead) let-binding let x = (a,b) in ...
387 -- Similarly, single occurrences can be inlined vigourously
388 -- e.g. case (f x, g y) of (a,b) -> ....
389 -- If a,b occur once we can avoid constructing the let binding for them.
391 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
392 -- Consider case I# (quotInt# x y) of
393 -- I# v -> let w = J# v in ...
394 -- If we gaily inline (quotInt# x y) for v, we end up building an
396 -- let w = J# (quotInt# x y) in ...
397 -- because quotInt# can fail.
399 | preInlineUnconditionally env NotTopLevel bndr new_rhs
400 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
403 ----------------------------------
404 prepareRhs takes a putative RHS, checks whether it's a PAP or
405 constructor application and, if so, converts it to ANF, so that the
406 resulting thing can be inlined more easily. Thus
413 We also want to deal well cases like this
414 v = (f e1 `cast` co) e2
415 Here we want to make e1,e2 trivial and get
416 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
417 That's what the 'go' loop in prepareRhs does
420 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
421 -- Adds new floats to the env iff that allows us to return a good RHS
422 prepareRhs env (Cast rhs co) -- Note [Float coercions]
423 = do { (env', rhs') <- makeTrivial env rhs
424 ; return (env', Cast rhs' co) }
427 = do { (is_val, env', rhs') <- go 0 env rhs
428 ; return (env', rhs') }
430 go n_val_args env (Cast rhs co)
431 = do { (is_val, env', rhs') <- go n_val_args env rhs
432 ; return (is_val, env', Cast rhs' co) }
433 go n_val_args env (App fun (Type ty))
434 = do { (is_val, env', rhs') <- go n_val_args env fun
435 ; return (is_val, env', App rhs' (Type ty)) }
436 go n_val_args env (App fun arg)
437 = do { (is_val, env', fun') <- go (n_val_args+1) env fun
439 True -> do { (env'', arg') <- makeTrivial env' arg
440 ; return (True, env'', App fun' arg') }
441 False -> return (False, env, App fun arg) }
442 go n_val_args env (Var fun)
443 = return (is_val, env, Var fun)
445 is_val = n_val_args > 0 -- There is at least one arg
446 -- ...and the fun a constructor or PAP
447 && (isDataConWorkId fun || n_val_args < idArity fun)
448 go n_val_args env other
449 = return (False, env, other)
452 Note [Float coercions]
453 ~~~~~~~~~~~~~~~~~~~~~~
454 When we find the binding
456 we'd like to transform it to
458 x = x `cast` co -- A trivial binding
459 There's a chance that e will be a constructor application or function, or something
460 like that, so moving the coerion to the usage site may well cancel the coersions
461 and lead to further optimisation. Example:
464 data instance T Int = T Int
466 foo :: Int -> Int -> Int
471 go n = case x of { T m -> go (n-m) }
472 -- This case should optimise
476 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
477 -- Binds the expression to a variable, if it's not trivial, returning the variable
481 | otherwise -- See Note [Take care] below
482 = do { var <- newId FSLIT("a") (exprType expr)
483 ; env <- completeNonRecX env NotTopLevel NonRecursive
485 ; return (env, substExpr env (Var var)) }
489 %************************************************************************
491 \subsection{Completing a lazy binding}
493 %************************************************************************
496 * deals only with Ids, not TyVars
497 * takes an already-simplified binder and RHS
498 * is used for both recursive and non-recursive bindings
499 * is used for both top-level and non-top-level bindings
501 It does the following:
502 - tries discarding a dead binding
503 - tries PostInlineUnconditionally
504 - add unfolding [this is the only place we add an unfolding]
507 It does *not* attempt to do let-to-case. Why? Because it is used for
508 - top-level bindings (when let-to-case is impossible)
509 - many situations where the "rhs" is known to be a WHNF
510 (so let-to-case is inappropriate).
512 Nor does it do the atomic-argument thing
515 completeBind :: SimplEnv
516 -> TopLevelFlag -- Flag stuck into unfolding
517 -> InId -- Old binder
518 -> OutId -> OutExpr -- New binder and RHS
520 -- completeBind may choose to do its work
521 -- * by extending the substitution (e.g. let x = y in ...)
522 -- * or by adding to the floats in the envt
524 completeBind env top_lvl old_bndr new_bndr new_rhs
525 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
526 -- Inline and discard the binding
527 = do { tick (PostInlineUnconditionally old_bndr)
528 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
529 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
530 -- Use the substitution to make quite, quite sure that the
531 -- substitution will happen, since we are going to discard the binding
536 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
539 -- Add the unfolding *only* for non-loop-breakers
540 -- Making loop breakers not have an unfolding at all
541 -- means that we can avoid tests in exprIsConApp, for example.
542 -- This is important: if exprIsConApp says 'yes' for a recursive
543 -- thing, then we can get into an infinite loop
546 -- If the unfolding is a value, the demand info may
547 -- go pear-shaped, so we nuke it. Example:
549 -- case x of (p,q) -> h p q x
550 -- Here x is certainly demanded. But after we've nuked
551 -- the case, we'll get just
552 -- let x = (a,b) in h a b x
553 -- and now x is not demanded (I'm assuming h is lazy)
554 -- This really happens. Similarly
555 -- let f = \x -> e in ...f..f...
556 -- After inlining f at some of its call sites the original binding may
557 -- (for example) be no longer strictly demanded.
558 -- The solution here is a bit ad hoc...
559 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
560 final_info | loop_breaker = new_bndr_info
561 | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
562 | otherwise = info_w_unf
564 final_id = new_bndr `setIdInfo` final_info
566 -- These seqs forces the Id, and hence its IdInfo,
567 -- and hence any inner substitutions
569 -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
570 return (addNonRec env final_id new_rhs)
572 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
573 loop_breaker = isNonRuleLoopBreaker occ_info
574 old_info = idInfo old_bndr
575 occ_info = occInfo old_info
580 %************************************************************************
582 \subsection[Simplify-simplExpr]{The main function: simplExpr}
584 %************************************************************************
586 The reason for this OutExprStuff stuff is that we want to float *after*
587 simplifying a RHS, not before. If we do so naively we get quadratic
588 behaviour as things float out.
590 To see why it's important to do it after, consider this (real) example:
604 a -- Can't inline a this round, cos it appears twice
608 Each of the ==> steps is a round of simplification. We'd save a
609 whole round if we float first. This can cascade. Consider
614 let f = let d1 = ..d.. in \y -> e
618 in \x -> ...(\y ->e)...
620 Only in this second round can the \y be applied, and it
621 might do the same again.
625 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
626 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
628 expr_ty' = substTy env (exprType expr)
629 -- The type in the Stop continuation, expr_ty', is usually not used
630 -- It's only needed when discarding continuations after finding
631 -- a function that returns bottom.
632 -- Hence the lazy substitution
635 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
636 -- Simplify an expression, given a continuation
637 simplExprC env expr cont
638 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
639 do { (env', expr') <- simplExprF (zapFloats env) expr cont
640 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
641 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
642 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
643 return (wrapFloats env' expr') }
645 --------------------------------------------------
646 simplExprF :: SimplEnv -> InExpr -> SimplCont
647 -> SimplM (SimplEnv, OutExpr)
649 simplExprF env e cont
650 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
651 simplExprF' env e cont
653 simplExprF' env (Var v) cont = simplVar env v cont
654 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
655 simplExprF' env (Note n expr) cont = simplNote env n expr cont
656 simplExprF' env (Cast body co) cont = simplCast env body co cont
657 simplExprF' env (App fun arg) cont = simplExprF env fun $
658 ApplyTo NoDup arg env cont
660 simplExprF' env expr@(Lam _ _) cont
661 = simplLam env (map zap bndrs) body cont
662 -- The main issue here is under-saturated lambdas
663 -- (\x1. \x2. e) arg1
664 -- Here x1 might have "occurs-once" occ-info, because occ-info
665 -- is computed assuming that a group of lambdas is applied
666 -- all at once. If there are too few args, we must zap the
669 n_args = countArgs cont
670 n_params = length bndrs
671 (bndrs, body) = collectBinders expr
672 zap | n_args >= n_params = \b -> b
673 | otherwise = \b -> if isTyVar b then b
675 -- NB: we count all the args incl type args
676 -- so we must count all the binders (incl type lambdas)
678 simplExprF' env (Type ty) cont
679 = ASSERT( contIsRhsOrArg cont )
680 do { ty' <- simplType env ty
681 ; rebuild env (Type ty') cont }
683 simplExprF' env (Case scrut bndr case_ty alts) cont
684 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
685 = -- Simplify the scrutinee with a Select continuation
686 simplExprF env scrut (Select NoDup bndr alts env cont)
689 = -- If case-of-case is off, simply simplify the case expression
690 -- in a vanilla Stop context, and rebuild the result around it
691 do { case_expr' <- simplExprC env scrut case_cont
692 ; rebuild env case_expr' cont }
694 case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
695 case_ty' = substTy env case_ty -- c.f. defn of simplExpr
697 simplExprF' env (Let (Rec pairs) body) cont
698 = do { env <- simplRecBndrs env (map fst pairs)
699 -- NB: bndrs' don't have unfoldings or rules
700 -- We add them as we go down
702 ; env <- simplRecBind env NotTopLevel pairs
703 ; simplExprF env body cont }
705 simplExprF' env (Let (NonRec bndr rhs) body) cont
706 = simplNonRecE env bndr (rhs, env) ([], body) cont
708 ---------------------------------
709 simplType :: SimplEnv -> InType -> SimplM OutType
710 -- Kept monadic just so we can do the seqType
712 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
713 seqType new_ty `seq` returnSmpl new_ty
715 new_ty = substTy env ty
719 %************************************************************************
721 \subsection{The main rebuilder}
723 %************************************************************************
726 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
727 -- At this point the substitution in the SimplEnv should be irrelevant
728 -- only the in-scope set and floats should matter
729 rebuild env expr cont
730 = -- pprTrace "rebuild" (ppr expr $$ ppr cont $$ ppr (seFloats env)) $
732 Stop {} -> return (env, expr)
733 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
734 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
735 StrictArg fun ty info cont -> rebuildCall env (fun `App` expr) (funResultTy ty) info cont
736 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
737 ; simplLam env' bs body cont }
738 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
739 ; rebuild env (App expr arg') cont }
743 %************************************************************************
747 %************************************************************************
750 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
751 -> SimplM (SimplEnv, OutExpr)
752 simplCast env body co cont
753 = do { co' <- simplType env co
754 ; simplExprF env body (addCoerce co' cont) }
756 addCoerce co cont = add_coerce co (coercionKind co) cont
758 add_coerce co (s1, k1) cont -- co :: ty~ty
759 | s1 `coreEqType` k1 = cont -- is a no-op
761 add_coerce co1 (s1, k2) (CoerceIt co2 cont)
762 | (l1, t1) <- coercionKind co2
763 -- coerce T1 S1 (coerce S1 K1 e)
766 -- coerce T1 K1 e, otherwise
768 -- For example, in the initial form of a worker
769 -- we may find (coerce T (coerce S (\x.e))) y
770 -- and we'd like it to simplify to e[y/x] in one round
772 , s1 `coreEqType` t1 = cont -- The coerces cancel out
773 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
775 add_coerce co (s1s2, t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
776 -- (f `cast` g) ty ---> (f ty) `cast` (g @ ty)
777 -- This implements the PushT rule from the paper
778 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
779 , not (isCoVar tyvar)
780 = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
782 ty' = substTy arg_se arg_ty
784 -- ToDo: the PushC rule is not implemented at all
786 add_coerce co (s1s2, t1t2) (ApplyTo dup arg arg_se cont)
787 | not (isTypeArg arg) -- This implements the Push rule from the paper
788 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
789 -- co : s1s2 :=: t1t2
790 -- (coerce (T1->T2) (S1->S2) F) E
792 -- coerce T2 S2 (F (coerce S1 T1 E))
794 -- t1t2 must be a function type, T1->T2, because it's applied
795 -- to something but s1s2 might conceivably not be
797 -- When we build the ApplyTo we can't mix the out-types
798 -- with the InExpr in the argument, so we simply substitute
799 -- to make it all consistent. It's a bit messy.
800 -- But it isn't a common case.
802 -- Example of use: Trac #995
803 = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
805 -- we split coercion t1->t2 :=: s1->s2 into t1 :=: s1 and
806 -- t2 :=: s2 with left and right on the curried form:
807 -- (->) t1 t2 :=: (->) s1 s2
808 [co1, co2] = decomposeCo 2 co
809 new_arg = mkCoerce (mkSymCoercion co1) arg'
810 arg' = substExpr arg_se arg
812 add_coerce co _ cont = CoerceIt co cont
816 %************************************************************************
820 %************************************************************************
823 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
824 -> SimplM (SimplEnv, OutExpr)
826 simplLam env [] body cont = simplExprF env body cont
828 -- Type-beta reduction
829 simplLam env (bndr:bndrs) body (ApplyTo _ (Type ty_arg) arg_se cont)
830 = ASSERT( isTyVar bndr )
831 do { tick (BetaReduction bndr)
832 ; ty_arg' <- simplType (arg_se `setInScope` env) ty_arg
833 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
835 -- Ordinary beta reduction
836 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
837 = do { tick (BetaReduction bndr)
838 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
840 -- Not enough args, so there are real lambdas left to put in the result
841 simplLam env bndrs body cont
842 = do { (env, bndrs') <- simplLamBndrs env bndrs
843 ; body' <- simplExpr env body
844 ; new_lam <- mkLam bndrs' body'
845 ; rebuild env new_lam cont }
848 simplNonRecE :: SimplEnv
849 -> InId -- The binder
850 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
851 -> ([InId], InExpr) -- Body of the let/lambda
854 -> SimplM (SimplEnv, OutExpr)
856 -- simplNonRecE is used for
857 -- * non-top-level non-recursive lets in expressions
860 -- It deals with strict bindings, via the StrictBind continuation,
861 -- which may abort the whole process
863 -- The "body" of the binding comes as a pair of ([InId],InExpr)
864 -- representing a lambda; so we recurse back to simplLam
865 -- Why? Because of the binder-occ-info-zapping done before
866 -- the call to simplLam in simplExprF (Lam ...)
868 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
869 | preInlineUnconditionally env NotTopLevel bndr rhs
870 = do { tick (PreInlineUnconditionally bndr)
871 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
874 = do { simplExprF (rhs_se `setFloats` env) rhs
875 (StrictBind bndr bndrs body env cont) }
878 = do { (env, bndr') <- simplBinder env bndr
879 ; env <- simplLazyBind env NotTopLevel NonRecursive bndr bndr' rhs rhs_se
880 ; simplLam env bndrs body cont }
884 %************************************************************************
888 %************************************************************************
891 -- Hack alert: we only distinguish subsumed cost centre stacks for the
892 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
893 simplNote env (SCC cc) e cont
894 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
895 ; rebuild env (mkSCC cc e') cont }
897 -- See notes with SimplMonad.inlineMode
898 simplNote env InlineMe e cont
899 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
900 = do { -- Don't inline inside an INLINE expression
901 e' <- simplExpr (setMode inlineMode env) e
902 ; rebuild env (mkInlineMe e') cont }
904 | otherwise -- Dissolve the InlineMe note if there's
905 -- an interesting context of any kind to combine with
906 -- (even a type application -- anything except Stop)
907 = simplExprF env e cont
909 simplNote env (CoreNote s) e cont
910 = simplExpr env e `thenSmpl` \ e' ->
911 rebuild env (Note (CoreNote s) e') cont
915 %************************************************************************
917 \subsection{Dealing with calls}
919 %************************************************************************
922 simplVar env var cont
923 = case substId env var of
924 DoneEx e -> simplExprF (zapSubstEnv env) e cont
925 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
926 DoneId var1 -> completeCall (zapSubstEnv env) var1 cont
927 -- Note [zapSubstEnv]
928 -- The template is already simplified, so don't re-substitute.
929 -- This is VITAL. Consider
931 -- let y = \z -> ...x... in
933 -- We'll clone the inner \x, adding x->x' in the id_subst
934 -- Then when we inline y, we must *not* replace x by x' in
935 -- the inlined copy!!
937 ---------------------------------------------------------
938 -- Dealing with a call site
940 completeCall env var cont
941 = do { dflags <- getDOptsSmpl
942 ; let (args,call_cont) = contArgs cont
943 -- The args are OutExprs, obtained by *lazily* substituting
944 -- in the args found in cont. These args are only examined
945 -- to limited depth (unless a rule fires). But we must do
946 -- the substitution; rule matching on un-simplified args would
949 ------------- First try rules ----------------
950 -- Do this before trying inlining. Some functions have
951 -- rules *and* are strict; in this case, we don't want to
952 -- inline the wrapper of the non-specialised thing; better
953 -- to call the specialised thing instead.
955 -- We used to use the black-listing mechanism to ensure that inlining of
956 -- the wrapper didn't occur for things that have specialisations till a
957 -- later phase, so but now we just try RULES first
959 -- You might think that we shouldn't apply rules for a loop breaker:
960 -- doing so might give rise to an infinite loop, because a RULE is
961 -- rather like an extra equation for the function:
962 -- RULE: f (g x) y = x+y
965 -- But it's too drastic to disable rules for loop breakers.
966 -- Even the foldr/build rule would be disabled, because foldr
967 -- is recursive, and hence a loop breaker:
968 -- foldr k z (build g) = g k z
969 -- So it's up to the programmer: rules can cause divergence
970 ; let in_scope = getInScope env
972 maybe_rule = case activeRule env of
973 Nothing -> Nothing -- No rules apply
974 Just act_fn -> lookupRule act_fn in_scope
976 ; case maybe_rule of {
977 Just (rule, rule_rhs) ->
978 tick (RuleFired (ru_name rule)) `thenSmpl_`
979 (if dopt Opt_D_dump_rule_firings dflags then
980 pprTrace "Rule fired" (vcat [
981 text "Rule:" <+> ftext (ru_name rule),
982 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
983 text "After: " <+> pprCoreExpr rule_rhs,
984 text "Cont: " <+> ppr call_cont])
987 simplExprF env rule_rhs (dropArgs (ruleArity rule) cont)
988 -- The ruleArity says how many args the rule consumed
990 ; Nothing -> do -- No rules
992 ------------- Next try inlining ----------------
993 { let arg_infos = [interestingArg arg | arg <- args, isValArg arg]
994 n_val_args = length arg_infos
995 interesting_cont = interestingCallContext (notNull args)
998 active_inline = activeInline env var
999 maybe_inline = callSiteInline dflags active_inline
1000 var arg_infos interesting_cont
1001 ; case maybe_inline of {
1002 Just unfolding -- There is an inlining!
1003 -> do { tick (UnfoldingDone var)
1004 ; (if dopt Opt_D_dump_inlinings dflags then
1005 pprTrace "Inlining done" (vcat [
1006 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1007 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1008 text "Cont: " <+> ppr call_cont])
1011 simplExprF env unfolding cont }
1013 ; Nothing -> -- No inlining!
1015 ------------- No inlining! ----------------
1016 -- Next, look for rules or specialisations that match
1018 rebuildCall env (Var var) (idType var)
1019 (mkArgInfo var n_val_args call_cont) cont
1022 rebuildCall :: SimplEnv
1023 -> OutExpr -> OutType -- Function and its type
1024 -> (Bool, [Bool]) -- See SimplUtils.mkArgInfo
1026 -> SimplM (SimplEnv, OutExpr)
1027 rebuildCall env fun fun_ty (has_rules, []) cont
1028 -- When we run out of strictness args, it means
1029 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1030 -- Then we want to discard the entire strict continuation. E.g.
1031 -- * case (error "hello") of { ... }
1032 -- * (error "Hello") arg
1033 -- * f (error "Hello") where f is strict
1035 -- Then, especially in the first of these cases, we'd like to discard
1036 -- the continuation, leaving just the bottoming expression. But the
1037 -- type might not be right, so we may have to add a coerce.
1038 | not (contIsTrivial cont) -- Only do thia if there is a non-trivial
1039 = return (env, mk_coerce fun) -- contination to discard, else we do it
1040 where -- again and again!
1041 cont_ty = contResultType cont
1042 co = mkUnsafeCoercion fun_ty cont_ty
1043 mk_coerce expr | cont_ty `coreEqType` fun_ty = fun
1044 | otherwise = mkCoerce co fun
1046 rebuildCall env fun fun_ty info (ApplyTo _ (Type arg_ty) se cont)
1047 = do { ty' <- simplType (se `setInScope` env) arg_ty
1048 ; rebuildCall env (fun `App` Type ty') (applyTy fun_ty ty') info cont }
1050 rebuildCall env fun fun_ty (has_rules, str:strs) (ApplyTo _ arg arg_se cont)
1051 | str || isStrictType arg_ty -- Strict argument
1052 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1053 simplExprF (arg_se `setFloats` env) arg
1054 (StrictArg fun fun_ty (has_rules, strs) cont)
1057 | otherwise -- Lazy argument
1058 -- DO NOT float anything outside, hence simplExprC
1059 -- There is no benefit (unlike in a let-binding), and we'd
1060 -- have to be very careful about bogus strictness through
1061 -- floating a demanded let.
1062 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1063 (mkLazyArgStop arg_ty has_rules)
1064 ; rebuildCall env (fun `App` arg') res_ty (has_rules, strs) cont }
1066 (arg_ty, res_ty) = splitFunTy fun_ty
1068 rebuildCall env fun fun_ty info cont
1069 = rebuild env fun cont
1074 This part of the simplifier may break the no-shadowing invariant
1076 f (...(\a -> e)...) (case y of (a,b) -> e')
1077 where f is strict in its second arg
1078 If we simplify the innermost one first we get (...(\a -> e)...)
1079 Simplifying the second arg makes us float the case out, so we end up with
1080 case y of (a,b) -> f (...(\a -> e)...) e'
1081 So the output does not have the no-shadowing invariant. However, there is
1082 no danger of getting name-capture, because when the first arg was simplified
1083 we used an in-scope set that at least mentioned all the variables free in its
1084 static environment, and that is enough.
1086 We can't just do innermost first, or we'd end up with a dual problem:
1087 case x of (a,b) -> f e (...(\a -> e')...)
1089 I spent hours trying to recover the no-shadowing invariant, but I just could
1090 not think of an elegant way to do it. The simplifier is already knee-deep in
1091 continuations. We have to keep the right in-scope set around; AND we have
1092 to get the effect that finding (error "foo") in a strict arg position will
1093 discard the entire application and replace it with (error "foo"). Getting
1094 all this at once is TOO HARD!
1096 %************************************************************************
1098 Rebuilding a cse expression
1100 %************************************************************************
1102 Blob of helper functions for the "case-of-something-else" situation.
1105 ---------------------------------------------------------
1106 -- Eliminate the case if possible
1108 rebuildCase :: SimplEnv
1109 -> OutExpr -- Scrutinee
1110 -> InId -- Case binder
1111 -> [InAlt] -- Alternatives (inceasing order)
1113 -> SimplM (SimplEnv, OutExpr)
1115 rebuildCase env scrut case_bndr alts cont
1116 | Just (con,args) <- exprIsConApp_maybe scrut
1117 -- Works when the scrutinee is a variable with a known unfolding
1118 -- as well as when it's an explicit constructor application
1119 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1121 | Lit lit <- scrut -- No need for same treatment as constructors
1122 -- because literals are inlined more vigorously
1123 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1126 = do { -- Prepare the continuation;
1127 -- The new subst_env is in place
1128 (env, dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1130 -- Simplify the alternatives
1131 ; (case_bndr', alts') <- simplAlts env scrut case_bndr alts dup_cont
1132 ; let res_ty' = contResultType dup_cont
1133 ; case_expr <- mkCase scrut case_bndr' res_ty' alts'
1135 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1136 -- The case binder *not* scope over the whole returned case-expression
1137 ; rebuild env case_expr nodup_cont }
1140 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1141 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1142 way, there's a chance that v will now only be used once, and hence
1145 Note [no-case-of-case]
1146 ~~~~~~~~~~~~~~~~~~~~~~
1147 There is a time we *don't* want to do that, namely when
1148 -fno-case-of-case is on. This happens in the first simplifier pass,
1149 and enhances full laziness. Here's the bad case:
1150 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1151 If we eliminate the inner case, we trap it inside the I# v -> arm,
1152 which might prevent some full laziness happening. I've seen this
1153 in action in spectral/cichelli/Prog.hs:
1154 [(m,n) | m <- [1..max], n <- [1..max]]
1155 Hence the check for NoCaseOfCase.
1157 Note [Suppressing the case binder-swap]
1158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1159 There is another situation when it might make sense to suppress the
1160 case-expression binde-swap. If we have
1162 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1163 ...other cases .... }
1165 We'll perform the binder-swap for the outer case, giving
1167 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1168 ...other cases .... }
1170 But there is no point in doing it for the inner case, because w1 can't
1171 be inlined anyway. Furthermore, doing the case-swapping involves
1172 zapping w2's occurrence info (see paragraphs that follow), and that
1173 forces us to bind w2 when doing case merging. So we get
1175 case x of w1 { A -> let w2 = w1 in e1
1176 B -> let w2 = w1 in e2
1177 ...other cases .... }
1179 This is plain silly in the common case where w2 is dead.
1181 Even so, I can't see a good way to implement this idea. I tried
1182 not doing the binder-swap if the scrutinee was already evaluated
1183 but that failed big-time:
1187 case v of w { MkT x ->
1188 case x of x1 { I# y1 ->
1189 case x of x2 { I# y2 -> ...
1191 Notice that because MkT is strict, x is marked "evaluated". But to
1192 eliminate the last case, we must either make sure that x (as well as
1193 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1194 the binder-swap. So this whole note is a no-op.
1198 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1199 any occurrence info (eg IAmDead) in the case binder, because the
1200 case-binder now effectively occurs whenever v does. AND we have to do
1201 the same for the pattern-bound variables! Example:
1203 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1205 Here, b and p are dead. But when we move the argment inside the first
1206 case RHS, and eliminate the second case, we get
1208 case x of { (a,b) -> a b }
1210 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1213 Indeed, this can happen anytime the case binder isn't dead:
1214 case <any> of x { (a,b) ->
1215 case x of { (p,q) -> p } }
1216 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1217 The point is that we bring into the envt a binding
1219 after the outer case, and that makes (a,b) alive. At least we do unless
1220 the case binder is guaranteed dead.
1224 Consider case (v `cast` co) of x { I# ->
1225 ... (case (v `cast` co) of {...}) ...
1226 We'd like to eliminate the inner case. We can get this neatly by
1227 arranging that inside the outer case we add the unfolding
1228 v |-> x `cast` (sym co)
1229 to v. Then we should inline v at the inner case, cancel the casts, and away we go
1232 simplCaseBinder :: SimplEnv -> OutExpr -> InId -> SimplM (SimplEnv, OutId)
1233 simplCaseBinder env scrut case_bndr
1234 | switchIsOn (getSwitchChecker env) NoCaseOfCase
1235 -- See Note [no-case-of-case]
1236 = do { (env, case_bndr') <- simplBinder env case_bndr
1237 ; return (env, case_bndr') }
1239 simplCaseBinder env (Var v) case_bndr
1240 -- Failed try [see Note 2 above]
1241 -- not (isEvaldUnfolding (idUnfolding v))
1242 = do { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1243 ; return (modifyInScope env v case_bndr', case_bndr') }
1244 -- We could extend the substitution instead, but it would be
1245 -- a hack because then the substitution wouldn't be idempotent
1246 -- any more (v is an OutId). And this does just as well.
1248 simplCaseBinder env (Cast (Var v) co) case_bndr -- Note [Case of cast]
1249 = do { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1250 ; let rhs = Cast (Var case_bndr') (mkSymCoercion co)
1251 ; return (addBinderUnfolding env v rhs, case_bndr') }
1253 simplCaseBinder env other_scrut case_bndr
1254 = do { (env, case_bndr') <- simplBinder env case_bndr
1255 ; return (env, case_bndr') }
1257 zapOccInfo :: InId -> InId -- See Note [zapOccInfo]
1258 zapOccInfo b = b `setIdOccInfo` NoOccInfo
1262 simplAlts does two things:
1264 1. Eliminate alternatives that cannot match, including the
1265 DEFAULT alternative.
1267 2. If the DEFAULT alternative can match only one possible constructor,
1268 then make that constructor explicit.
1270 case e of x { DEFAULT -> rhs }
1272 case e of x { (a,b) -> rhs }
1273 where the type is a single constructor type. This gives better code
1274 when rhs also scrutinises x or e.
1276 Here "cannot match" includes knowledge from GADTs
1278 It's a good idea do do this stuff before simplifying the alternatives, to
1279 avoid simplifying alternatives we know can't happen, and to come up with
1280 the list of constructors that are handled, to put into the IdInfo of the
1281 case binder, for use when simplifying the alternatives.
1283 Eliminating the default alternative in (1) isn't so obvious, but it can
1286 data Colour = Red | Green | Blue
1295 DEFAULT -> [ case y of ... ]
1297 If we inline h into f, the default case of the inlined h can't happen.
1298 If we don't notice this, we may end up filtering out *all* the cases
1299 of the inner case y, which give us nowhere to go!
1303 simplAlts :: SimplEnv
1305 -> InId -- Case binder
1306 -> [InAlt] -> SimplCont
1307 -> SimplM (OutId, [OutAlt]) -- Includes the continuation
1308 -- Like simplExpr, this just returns the simplified alternatives;
1309 -- it not return an environment
1311 simplAlts env scrut case_bndr alts cont'
1312 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1313 do { let alt_env = zapFloats env
1314 ; (alt_env, case_bndr') <- simplCaseBinder alt_env scrut case_bndr
1316 ; default_alts <- prepareDefault alt_env case_bndr' imposs_deflt_cons cont' maybe_deflt
1318 ; let inst_tys = tyConAppArgs (idType case_bndr')
1319 trimmed_alts = filter (is_possible inst_tys) alts_wo_default
1320 in_alts = mergeAlts default_alts trimmed_alts
1321 -- We need the mergeAlts in case the new default_alt
1322 -- has turned into a constructor alternative.
1324 ; alts' <- mapM (simplAlt alt_env imposs_cons case_bndr' cont') in_alts
1325 ; return (case_bndr', alts') }
1327 (alts_wo_default, maybe_deflt) = findDefault alts
1328 imposs_cons = case scrut of
1329 Var v -> otherCons (idUnfolding v)
1332 -- "imposs_deflt_cons" are handled either by the context,
1333 -- OR by a branch in this case expression. (Don't include DEFAULT!!)
1334 imposs_deflt_cons = nub (imposs_cons ++ [con | (con,_,_) <- alts_wo_default])
1336 is_possible :: [Type] -> CoreAlt -> Bool
1337 is_possible tys (con, _, _) | con `elem` imposs_cons = False
1338 is_possible tys (DataAlt con, _, _) = dataConCanMatch tys con
1339 is_possible tys alt = True
1341 ------------------------------------
1342 prepareDefault :: SimplEnv
1343 -> OutId -- Case binder; need just for its type. Note that as an
1344 -- OutId, it has maximum information; this is important.
1345 -- Test simpl013 is an example
1346 -> [AltCon] -- These cons can't happen when matching the default
1349 -> SimplM [InAlt] -- One branch or none; still unsimplified
1350 -- We use a list because it's what mergeAlts expects
1352 prepareDefault env case_bndr' imposs_cons cont Nothing
1353 = return [] -- No default branch
1355 prepareDefault env case_bndr' imposs_cons cont (Just rhs)
1356 | -- This branch handles the case where we are
1357 -- scrutinisng an algebraic data type
1358 Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr'),
1359 isAlgTyCon tycon, -- It's a data type, tuple, or unboxed tuples.
1360 not (isNewTyCon tycon), -- We can have a newtype, if we are just doing an eval:
1361 -- case x of { DEFAULT -> e }
1362 -- and we don't want to fill in a default for them!
1363 Just all_cons <- tyConDataCons_maybe tycon,
1364 not (null all_cons), -- This is a tricky corner case. If the data type has no constructors,
1365 -- which GHC allows, then the case expression will have at most a default
1366 -- alternative. We don't want to eliminate that alternative, because the
1367 -- invariant is that there's always one alternative. It's more convenient
1369 -- case x of { DEFAULT -> e }
1370 -- as it is, rather than transform it to
1371 -- error "case cant match"
1372 -- which would be quite legitmate. But it's a really obscure corner, and
1373 -- not worth wasting code on.
1375 let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1376 is_possible con = not (con `elem` imposs_data_cons)
1377 && dataConCanMatch inst_tys con
1378 = case filter is_possible all_cons of
1379 [] -> return [] -- Eliminate the default alternative
1380 -- altogether if it can't match
1382 [con] -> -- It matches exactly one constructor, so fill it in
1383 do { tick (FillInCaseDefault case_bndr')
1384 ; us <- getUniquesSmpl
1385 ; let (ex_tvs, co_tvs, arg_ids) =
1386 dataConRepInstPat us con inst_tys
1387 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, rhs)] }
1389 two_or_more -> return [(DEFAULT, [], rhs)]
1392 = return [(DEFAULT, [], rhs)]
1394 ------------------------------------
1395 simplAlt :: SimplEnv
1396 -> [AltCon] -- These constructors can't be present when
1397 -- matching this alternative
1398 -> OutId -- The case binder
1403 -- Simplify an alternative, returning the type refinement for the
1404 -- alternative, if the alternative does any refinement at all
1406 simplAlt env handled_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1407 = ASSERT( null bndrs )
1408 do { let env' = addBinderOtherCon env case_bndr' handled_cons
1409 -- Record the constructors that the case-binder *can't* be.
1410 ; rhs' <- simplExprC env' rhs cont'
1411 ; return (DEFAULT, [], rhs') }
1413 simplAlt env handled_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1414 = ASSERT( null bndrs )
1415 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1416 ; rhs' <- simplExprC env' rhs cont'
1417 ; return (LitAlt lit, [], rhs') }
1419 simplAlt env handled_cons case_bndr' cont' (DataAlt con, vs, rhs)
1420 = do { -- Deal with the pattern-bound variables
1421 -- Mark the ones that are in ! positions in the data constructor
1422 -- as certainly-evaluated.
1423 -- NB: it happens that simplBinders does *not* erase the OtherCon
1424 -- form of unfolding, so it's ok to add this info before
1425 -- doing simplBinders
1426 (env, vs') <- simplBinders env (add_evals con vs)
1428 -- Bind the case-binder to (con args)
1429 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1430 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1431 env' = addBinderUnfolding env case_bndr' (mkConApp con con_args)
1433 ; rhs' <- simplExprC env' rhs cont'
1434 ; return (DataAlt con, vs', rhs') }
1436 -- add_evals records the evaluated-ness of the bound variables of
1437 -- a case pattern. This is *important*. Consider
1438 -- data T = T !Int !Int
1440 -- case x of { T a b -> T (a+1) b }
1442 -- We really must record that b is already evaluated so that we don't
1443 -- go and re-evaluate it when constructing the result.
1444 -- See Note [Data-con worker strictness] in MkId.lhs
1445 add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1447 cat_evals dc vs strs
1451 go (v:vs) strs | isTyVar v = v : go vs strs
1452 go (v:vs) (str:strs)
1453 | isMarkedStrict str = evald_v : go vs strs
1454 | otherwise = zapped_v : go vs strs
1456 zapped_v = zap_occ_info v
1457 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1458 go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1460 -- If the case binder is alive, then we add the unfolding
1462 -- to the envt; so vs are now very much alive
1463 -- Note [Aug06] I can't see why this actually matters
1464 zap_occ_info | isDeadBinder case_bndr' = \id -> id
1465 | otherwise = zapOccInfo
1467 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1468 addBinderUnfolding env bndr rhs
1469 = modifyInScope env bndr (bndr `setIdUnfolding` mkUnfolding False rhs)
1471 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1472 addBinderOtherCon env bndr cons
1473 = modifyInScope env bndr (bndr `setIdUnfolding` mkOtherCon cons)
1477 %************************************************************************
1479 \subsection{Known constructor}
1481 %************************************************************************
1483 We are a bit careful with occurrence info. Here's an example
1485 (\x* -> case x of (a*, b) -> f a) (h v, e)
1487 where the * means "occurs once". This effectively becomes
1488 case (h v, e) of (a*, b) -> f a)
1490 let a* = h v; b = e in f a
1494 All this should happen in one sweep.
1497 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1498 -> InId -> [InAlt] -> SimplCont
1499 -> SimplM (SimplEnv, OutExpr)
1501 knownCon env scrut con args bndr alts cont
1502 = do { tick (KnownBranch bndr)
1503 ; knownAlt env scrut args bndr (findAlt con alts) cont }
1505 knownAlt env scrut args bndr (DEFAULT, bs, rhs) cont
1507 do { env <- simplNonRecX env bndr scrut
1508 -- This might give rise to a binding with non-atomic args
1509 -- like x = Node (f x) (g x)
1510 -- but simplNonRecX will atomic-ify it
1511 ; simplExprF env rhs cont }
1513 knownAlt env scrut args bndr (LitAlt lit, bs, rhs) cont
1515 do { env <- simplNonRecX env bndr scrut
1516 ; simplExprF env rhs cont }
1518 knownAlt env scrut args bndr (DataAlt dc, bs, rhs) cont
1519 = do { let dead_bndr = isDeadBinder bndr
1520 n_drop_tys = tyConArity (dataConTyCon dc)
1521 ; env <- bind_args env dead_bndr bs (drop n_drop_tys args)
1523 -- It's useful to bind bndr to scrut, rather than to a fresh
1524 -- binding x = Con arg1 .. argn
1525 -- because very often the scrut is a variable, so we avoid
1526 -- creating, and then subsequently eliminating, a let-binding
1527 -- BUT, if scrut is a not a variable, we must be careful
1528 -- about duplicating the arg redexes; in that case, make
1529 -- a new con-app from the args
1530 bndr_rhs = case scrut of
1533 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1534 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1535 -- args are aready OutExprs, but bs are InIds
1537 ; env <- simplNonRecX env bndr bndr_rhs
1538 ; -- pprTrace "knownCon2" (ppr bs $$ ppr rhs $$ ppr (seIdSubst env)) $
1539 simplExprF env rhs cont }
1542 bind_args env dead_bndr [] _ = return env
1544 bind_args env dead_bndr (b:bs) (Type ty : args)
1545 = ASSERT( isTyVar b )
1546 bind_args (extendTvSubst env b ty) dead_bndr bs args
1548 bind_args env dead_bndr (b:bs) (arg : args)
1550 do { let b' = if dead_bndr then b else zapOccInfo b
1551 -- Note that the binder might be "dead", because it doesn't occur
1552 -- in the RHS; and simplNonRecX may therefore discard it via postInlineUnconditionally
1553 -- Nevertheless we must keep it if the case-binder is alive, because it may
1554 -- be used in the con_app. See Note [zapOccInfo]
1555 ; env <- simplNonRecX env b' arg
1556 ; bind_args env dead_bndr bs args }
1558 bind_args _ _ _ _ = panic "bind_args"
1562 %************************************************************************
1564 \subsection{Duplicating continuations}
1566 %************************************************************************
1569 prepareCaseCont :: SimplEnv
1570 -> [InAlt] -> SimplCont
1571 -> SimplM (SimplEnv, SimplCont,SimplCont)
1572 -- Return a duplicatable continuation, a non-duplicable part
1573 -- plus some extra bindings (that scope over the entire
1576 -- No need to make it duplicatable if there's only one alternative
1577 prepareCaseCont env [alt] cont = return (env, cont, mkBoringStop (contResultType cont))
1578 prepareCaseCont env alts cont = mkDupableCont env cont
1582 mkDupableCont :: SimplEnv -> SimplCont
1583 -> SimplM (SimplEnv, SimplCont, SimplCont)
1585 mkDupableCont env cont
1586 | contIsDupable cont
1587 = returnSmpl (env, cont, mkBoringStop (contResultType cont))
1589 mkDupableCont env (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1591 mkDupableCont env (CoerceIt ty cont)
1592 = do { (env, dup, nodup) <- mkDupableCont env cont
1593 ; return (env, CoerceIt ty dup, nodup) }
1595 mkDupableCont env cont@(StrictBind bndr _ _ se _)
1596 = return (env, mkBoringStop (substTy se (idType bndr)), cont)
1597 -- See Note [Duplicating strict continuations]
1599 mkDupableCont env cont@(StrictArg _ fun_ty _ _)
1600 = return (env, mkBoringStop (funArgTy fun_ty), cont)
1601 -- See Note [Duplicating strict continuations]
1603 mkDupableCont env (ApplyTo _ arg se cont)
1604 = -- e.g. [...hole...] (...arg...)
1606 -- let a = ...arg...
1607 -- in [...hole...] a
1608 do { (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1609 ; arg <- simplExpr (se `setInScope` env) arg
1610 ; (env, arg) <- makeTrivial env arg
1611 ; let app_cont = ApplyTo OkToDup arg (zapSubstEnv env) dup_cont
1612 ; return (env, app_cont, nodup_cont) }
1614 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1615 -- See Note [Single-alternative case]
1616 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1617 -- | not (isDeadBinder case_bndr)
1618 | all isDeadBinder bs
1619 = return (env, mkBoringStop scrut_ty, cont)
1621 scrut_ty = substTy se (idType case_bndr)
1623 mkDupableCont env (Select _ case_bndr alts se cont)
1624 = -- e.g. (case [...hole...] of { pi -> ei })
1626 -- let ji = \xij -> ei
1627 -- in case [...hole...] of { pi -> ji xij }
1628 do { tick (CaseOfCase case_bndr)
1629 ; (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1630 -- NB: call mkDupableCont here, *not* prepareCaseCont
1631 -- We must make a duplicable continuation, whereas prepareCaseCont
1632 -- doesn't when there is a single case branch
1634 ; let alt_env = se `setInScope` env
1635 ; (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1636 ; alts' <- mapM (simplAlt alt_env [] case_bndr' dup_cont) alts
1637 -- Safe to say that there are no handled-cons for the DEFAULT case
1638 -- NB: simplBinder does not zap deadness occ-info, so
1639 -- a dead case_bndr' will still advertise its deadness
1640 -- This is really important because in
1641 -- case e of b { (# a,b #) -> ... }
1642 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1643 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1644 -- In the new alts we build, we have the new case binder, so it must retain
1646 -- NB: we don't use alt_env further; it has the substEnv for
1647 -- the alternatives, and we don't want that
1649 ; (env, alts') <- mkDupableAlts env case_bndr' alts'
1650 ; return (env, -- Note [Duplicated env]
1651 Select OkToDup case_bndr' alts' (zapSubstEnv env)
1652 (mkBoringStop (contResultType dup_cont)),
1656 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1657 -> SimplM (SimplEnv, [InAlt])
1658 -- Absorbs the continuation into the new alternatives
1660 mkDupableAlts env case_bndr' alts
1663 go env [] = return (env, [])
1665 = do { (env, alt') <- mkDupableAlt env case_bndr' alt
1666 ; (env, alts') <- go env alts
1667 ; return (env, alt' : alts' ) }
1669 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1670 | exprIsDupable rhs' -- Note [Small alternative rhs]
1671 = return (env, (con, bndrs', rhs'))
1673 = do { let rhs_ty' = exprType rhs'
1674 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1676 | isTyVar bndr = True -- Abstract over all type variables just in case
1677 | otherwise = not (isDeadBinder bndr)
1678 -- The deadness info on the new Ids is preserved by simplBinders
1680 ; (final_bndrs', final_args) -- Note [Join point abstraction]
1681 <- if (any isId used_bndrs')
1682 then return (used_bndrs', varsToCoreExprs used_bndrs')
1683 else do { rw_id <- newId FSLIT("w") realWorldStatePrimTy
1684 ; return ([rw_id], [Var realWorldPrimId]) }
1686 ; join_bndr <- newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty')
1687 -- Note [Funky mkPiTypes]
1689 ; let -- We make the lambdas into one-shot-lambdas. The
1690 -- join point is sure to be applied at most once, and doing so
1691 -- prevents the body of the join point being floated out by
1692 -- the full laziness pass
1693 really_final_bndrs = map one_shot final_bndrs'
1694 one_shot v | isId v = setOneShotLambda v
1696 join_rhs = mkLams really_final_bndrs rhs'
1697 join_call = mkApps (Var join_bndr) final_args
1699 ; return (addNonRec env join_bndr join_rhs, (con, bndrs', join_call)) }
1700 -- See Note [Duplicated env]
1703 Note [Duplicated env]
1704 ~~~~~~~~~~~~~~~~~~~~~
1705 Some of the alternatives are simplified, but have not been turned into a join point
1706 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
1707 bind the join point, because it might to do PostInlineUnconditionally, and
1708 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
1709 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1710 at worst delays the join-point inlining.
1712 Note [Small alterantive rhs]
1713 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1714 It is worth checking for a small RHS because otherwise we
1715 get extra let bindings that may cause an extra iteration of the simplifier to
1716 inline back in place. Quite often the rhs is just a variable or constructor.
1717 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1718 iterations because the version with the let bindings looked big, and so wasn't
1719 inlined, but after the join points had been inlined it looked smaller, and so
1722 NB: we have to check the size of rhs', not rhs.
1723 Duplicating a small InAlt might invalidate occurrence information
1724 However, if it *is* dupable, we return the *un* simplified alternative,
1725 because otherwise we'd need to pair it up with an empty subst-env....
1726 but we only have one env shared between all the alts.
1727 (Remember we must zap the subst-env before re-simplifying something).
1728 Rather than do this we simply agree to re-simplify the original (small) thing later.
1730 Note [Funky mkPiTypes]
1731 ~~~~~~~~~~~~~~~~~~~~~~
1732 Notice the funky mkPiTypes. If the contructor has existentials
1733 it's possible that the join point will be abstracted over
1734 type varaibles as well as term variables.
1735 Example: Suppose we have
1736 data T = forall t. C [t]
1738 case (case e of ...) of
1740 We get the join point
1741 let j :: forall t. [t] -> ...
1742 j = /\t \xs::[t] -> rhs
1744 case (case e of ...) of
1745 C t xs::[t] -> j t xs
1747 Note [Join point abstaction]
1748 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1749 If we try to lift a primitive-typed something out
1750 for let-binding-purposes, we will *caseify* it (!),
1751 with potentially-disastrous strictness results. So
1752 instead we turn it into a function: \v -> e
1753 where v::State# RealWorld#. The value passed to this function
1754 is realworld#, which generates (almost) no code.
1756 There's a slight infelicity here: we pass the overall
1757 case_bndr to all the join points if it's used in *any* RHS,
1758 because we don't know its usage in each RHS separately
1760 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1761 we make the join point into a function whenever used_bndrs'
1762 is empty. This makes the join-point more CPR friendly.
1763 Consider: let j = if .. then I# 3 else I# 4
1764 in case .. of { A -> j; B -> j; C -> ... }
1766 Now CPR doesn't w/w j because it's a thunk, so
1767 that means that the enclosing function can't w/w either,
1768 which is a lose. Here's the example that happened in practice:
1769 kgmod :: Int -> Int -> Int
1770 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1774 I have seen a case alternative like this:
1776 It's a bit silly to add the realWorld dummy arg in this case, making
1779 (the \v alone is enough to make CPR happy) but I think it's rare
1781 Note [Duplicating strict continuations]
1782 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1783 Do *not* duplicate StrictBind and StritArg continuations. We gain
1784 nothing by propagating them into the expressions, and we do lose a
1785 lot. Here's an example:
1786 && (case x of { T -> F; F -> T }) E
1787 Now, && is strict so we end up simplifying the case with
1788 an ArgOf continuation. If we let-bind it, we get
1790 let $j = \v -> && v E
1791 in simplExpr (case x of { T -> F; F -> T })
1793 And after simplifying more we get
1795 let $j = \v -> && v E
1796 in case x of { T -> $j F; F -> $j T }
1797 Which is a Very Bad Thing
1799 The desire not to duplicate is the entire reason that
1800 mkDupableCont returns a pair of continuations.
1802 The original plan had:
1803 e.g. (...strict-fn...) [...hole...]
1805 let $j = \a -> ...strict-fn...
1808 Note [Single-alternative cases]
1809 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1810 This case is just like the ArgOf case. Here's an example:
1814 case (case x of I# x' ->
1816 True -> I# (negate# x')
1817 False -> I# x') of y {
1819 Because the (case x) has only one alternative, we'll transform to
1821 case (case x' <# 0# of
1822 True -> I# (negate# x')
1823 False -> I# x') of y {
1825 But now we do *NOT* want to make a join point etc, giving
1827 let $j = \y -> MkT y
1829 True -> $j (I# (negate# x'))
1831 In this case the $j will inline again, but suppose there was a big
1832 strict computation enclosing the orginal call to MkT. Then, it won't
1833 "see" the MkT any more, because it's big and won't get duplicated.
1834 And, what is worse, nothing was gained by the case-of-case transform.
1836 When should use this case of mkDupableCont?
1837 However, matching on *any* single-alternative case is a *disaster*;
1838 e.g. case (case ....) of (a,b) -> (# a,b #)
1839 We must push the outer case into the inner one!
1842 * Match [(DEFAULT,_,_)], but in the common case of Int,
1843 the alternative-filling-in code turned the outer case into
1844 case (...) of y { I# _ -> MkT y }
1846 * Match on single alternative plus (not (isDeadBinder case_bndr))
1847 Rationale: pushing the case inwards won't eliminate the construction.
1848 But there's a risk of
1849 case (...) of y { (a,b) -> let z=(a,b) in ... }
1850 Now y looks dead, but it'll come alive again. Still, this
1851 seems like the best option at the moment.
1853 * Match on single alternative plus (all (isDeadBinder bndrs))
1854 Rationale: this is essentially seq.
1856 * Match when the rhs is *not* duplicable, and hence would lead to a
1857 join point. This catches the disaster-case above. We can test
1858 the *un-simplified* rhs, which is fine. It might get bigger or
1859 smaller after simplification; if it gets smaller, this case might
1860 fire next time round. NB also that we must test contIsDupable
1861 case_cont *btoo, because case_cont might be big!
1863 HOWEVER: I found that this version doesn't work well, because
1864 we can get let x = case (...) of { small } in ...case x...
1865 When x is inlined into its full context, we find that it was a bad
1866 idea to have pushed the outer case inside the (...) case.