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 )
19 import TcGadt ( dataConCanMatch )
20 import DataCon ( dataConTyCon, dataConRepStrictness )
21 import TyCon ( tyConArity, isAlgTyCon, isNewTyCon, tyConDataCons_maybe )
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 )
34 import Maybes ( orElse )
40 The guts of the simplifier is in this module, but the driver loop for
41 the simplifier is in SimplCore.lhs.
44 -----------------------------------------
45 *** IMPORTANT NOTE ***
46 -----------------------------------------
47 The simplifier used to guarantee that the output had no shadowing, but
48 it does not do so any more. (Actually, it never did!) The reason is
49 documented with simplifyArgs.
52 -----------------------------------------
53 *** IMPORTANT NOTE ***
54 -----------------------------------------
55 Many parts of the simplifier return a bunch of "floats" as well as an
56 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
58 All "floats" are let-binds, not case-binds, but some non-rec lets may
59 be unlifted (with RHS ok-for-speculation).
63 -----------------------------------------
64 ORGANISATION OF FUNCTIONS
65 -----------------------------------------
67 - simplify all top-level binders
68 - for NonRec, call simplRecOrTopPair
69 - for Rec, call simplRecBind
72 ------------------------------
73 simplExpr (applied lambda) ==> simplNonRecBind
74 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
75 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
77 ------------------------------
78 simplRecBind [binders already simplfied]
79 - use simplRecOrTopPair on each pair in turn
81 simplRecOrTopPair [binder already simplified]
82 Used for: recursive bindings (top level and nested)
83 top-level non-recursive bindings
85 - check for PreInlineUnconditionally
89 Used for: non-top-level non-recursive bindings
90 beta reductions (which amount to the same thing)
91 Because it can deal with strict arts, it takes a
92 "thing-inside" and returns an expression
94 - check for PreInlineUnconditionally
95 - simplify binder, including its IdInfo
104 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
105 Used for: binding case-binder and constr args in a known-constructor case
106 - check for PreInLineUnconditionally
110 ------------------------------
111 simplLazyBind: [binder already simplified, RHS not]
112 Used for: recursive bindings (top level and nested)
113 top-level non-recursive bindings
114 non-top-level, but *lazy* non-recursive bindings
115 [must not be strict or unboxed]
116 Returns floats + an augmented environment, not an expression
117 - substituteIdInfo and add result to in-scope
118 [so that rules are available in rec rhs]
121 - float if exposes constructor or PAP
125 completeNonRecX: [binder and rhs both simplified]
126 - if the the thing needs case binding (unlifted and not ok-for-spec)
132 completeBind: [given a simplified RHS]
133 [used for both rec and non-rec bindings, top level and not]
134 - try PostInlineUnconditionally
135 - add unfolding [this is the only place we add an unfolding]
140 Right hand sides and arguments
141 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142 In many ways we want to treat
143 (a) the right hand side of a let(rec), and
144 (b) a function argument
145 in the same way. But not always! In particular, we would
146 like to leave these arguments exactly as they are, so they
147 will match a RULE more easily.
152 It's harder to make the rule match if we ANF-ise the constructor,
153 or eta-expand the PAP:
155 f (let { a = g x; b = h x } in (a,b))
158 On the other hand if we see the let-defns
163 then we *do* want to ANF-ise and eta-expand, so that p and q
164 can be safely inlined.
166 Even floating lets out is a bit dubious. For let RHS's we float lets
167 out if that exposes a value, so that the value can be inlined more vigorously.
170 r = let x = e in (x,x)
172 Here, if we float the let out we'll expose a nice constructor. We did experiments
173 that showed this to be a generally good thing. But it was a bad thing to float
174 lets out unconditionally, because that meant they got allocated more often.
176 For function arguments, there's less reason to expose a constructor (it won't
177 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
178 So for the moment we don't float lets out of function arguments either.
183 For eta expansion, we want to catch things like
185 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
187 If the \x was on the RHS of a let, we'd eta expand to bring the two
188 lambdas together. And in general that's a good thing to do. Perhaps
189 we should eta expand wherever we find a (value) lambda? Then the eta
190 expansion at a let RHS can concentrate solely on the PAP case.
193 %************************************************************************
195 \subsection{Bindings}
197 %************************************************************************
200 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
202 simplTopBinds env binds
203 = do { -- Put all the top-level binders into scope at the start
204 -- so that if a transformation rule has unexpectedly brought
205 -- anything into scope, then we don't get a complaint about that.
206 -- It's rather as if the top-level binders were imported.
207 ; env <- simplRecBndrs env (bindersOfBinds binds)
208 ; dflags <- getDOptsSmpl
209 ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
210 dopt Opt_D_dump_rule_firings dflags
211 ; env' <- simpl_binds dump_flag env binds
212 ; freeTick SimplifierDone
213 ; return (getFloats env') }
215 -- We need to track the zapped top-level binders, because
216 -- they should have their fragile IdInfo zapped (notably occurrence info)
217 -- That's why we run down binds and bndrs' simultaneously.
219 -- The dump-flag emits a trace for each top-level binding, which
220 -- helps to locate the tracing for inlining and rule firing
221 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
222 simpl_binds dump env [] = return env
223 simpl_binds dump env (bind:binds) = do { env' <- trace dump bind $
225 ; simpl_binds dump env' binds }
227 trace True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
228 trace False bind = \x -> x
230 simpl_bind env (NonRec b r) = simplRecOrTopPair env TopLevel b r
231 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
235 %************************************************************************
237 \subsection{Lazy bindings}
239 %************************************************************************
241 simplRecBind is used for
242 * recursive bindings only
245 simplRecBind :: SimplEnv -> TopLevelFlag
248 simplRecBind env top_lvl pairs
249 = do { env' <- go (zapFloats env) pairs
250 ; return (env `addRecFloats` env') }
251 -- addFloats adds the floats from env',
252 -- *and* updates env with the in-scope set from env'
254 go env [] = return env
256 go env ((bndr, rhs) : pairs)
257 = do { env <- simplRecOrTopPair env top_lvl bndr rhs
261 simplOrTopPair is used for
262 * recursive bindings (whether top level or not)
263 * top-level non-recursive bindings
265 It assumes the binder has already been simplified, but not its IdInfo.
268 simplRecOrTopPair :: SimplEnv
270 -> InId -> InExpr -- Binder and rhs
271 -> SimplM SimplEnv -- Returns an env that includes the binding
273 simplRecOrTopPair env top_lvl bndr rhs
274 | preInlineUnconditionally env top_lvl bndr rhs -- Check for unconditional inline
275 = do { tick (PreInlineUnconditionally bndr)
276 ; return (extendIdSubst env bndr (mkContEx env rhs)) }
279 = do { let bndr' = lookupRecBndr env bndr
280 (env', bndr'') = addLetIdInfo env bndr bndr'
281 ; simplLazyBind env' top_lvl Recursive bndr bndr'' rhs env' }
282 -- May not actually be recursive, but it doesn't matter
286 simplLazyBind is used for
287 * [simplRecOrTopPair] recursive bindings (whether top level or not)
288 * [simplRecOrTopPair] top-level non-recursive bindings
289 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
292 1. It assumes that the binder is *already* simplified,
293 and is in scope, and its IdInfo too, except unfolding
295 2. It assumes that the binder type is lifted.
297 3. It does not check for pre-inline-unconditionallly;
298 that should have been done already.
301 simplLazyBind :: SimplEnv
302 -> TopLevelFlag -> RecFlag
303 -> InId -> OutId -- Binder, both pre-and post simpl
304 -- The OutId has IdInfo, except arity, unfolding
305 -> InExpr -> SimplEnv -- The RHS and its environment
308 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
309 = do { let rhs_env = rhs_se `setInScope` env
310 rhs_cont = mkRhsStop (idType bndr1)
312 -- Simplify the RHS; note the mkRhsStop, which tells
313 -- the simplifier that this is the RHS of a let.
314 ; (rhs_env1, rhs1) <- simplExprF rhs_env rhs rhs_cont
316 -- If any of the floats can't be floated, give up now
317 -- (The canFloat predicate says True for empty floats.)
318 ; if (not (canFloat top_lvl is_rec False rhs_env1))
319 then completeBind env top_lvl bndr bndr1
320 (wrapFloats rhs_env1 rhs1)
322 -- ANF-ise a constructor or PAP rhs
323 { (rhs_env2, rhs2) <- prepareRhs rhs_env1 rhs1
324 ; (env', rhs3) <- chooseRhsFloats top_lvl is_rec False env rhs_env2 rhs2
325 ; completeBind env' top_lvl bndr bndr1 rhs3 } }
327 chooseRhsFloats :: TopLevelFlag -> RecFlag -> Bool
328 -> SimplEnv -- Env for the let
329 -> SimplEnv -- Env for the RHS, with RHS floats in it
330 -> OutExpr -- ..and the RHS itself
331 -> SimplM (SimplEnv, OutExpr) -- New env for let, and RHS
333 chooseRhsFloats top_lvl is_rec is_strict env rhs_env rhs
334 | not (isEmptyFloats rhs_env) -- Something to float
335 , canFloat top_lvl is_rec is_strict rhs_env -- ...that can float
336 , (isTopLevel top_lvl || exprIsCheap rhs) -- ...and we want to float
337 = do { tick LetFloatFromLet -- Float
338 ; return (addFloats env rhs_env, rhs) } -- Add the floats to the main env
339 | otherwise -- Don't float
340 = return (env, wrapFloats rhs_env rhs) -- Wrap the floats around the RHS
344 %************************************************************************
346 \subsection{simplNonRec}
348 %************************************************************************
350 A specialised variant of simplNonRec used when the RHS is already simplified,
351 notably in knownCon. It uses case-binding where necessary.
354 simplNonRecX :: SimplEnv
355 -> InId -- Old binder
356 -> OutExpr -- Simplified RHS
359 simplNonRecX env bndr new_rhs
360 = do { (env, bndr') <- simplBinder env bndr
361 ; completeNonRecX env NotTopLevel NonRecursive
362 (isStrictId bndr) bndr bndr' new_rhs }
364 completeNonRecX :: SimplEnv
365 -> TopLevelFlag -> RecFlag -> Bool
366 -> InId -- Old binder
367 -> OutId -- New binder
368 -> OutExpr -- Simplified RHS
371 completeNonRecX env top_lvl is_rec is_strict old_bndr new_bndr new_rhs
372 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
373 ; (env2, rhs2) <- chooseRhsFloats top_lvl is_rec is_strict env env1 rhs1
374 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
377 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
378 Doing so risks exponential behaviour, because new_rhs has been simplified once already
379 In the cases described by the folowing commment, postInlineUnconditionally will
380 catch many of the relevant cases.
381 -- This happens; for example, the case_bndr during case of
382 -- known constructor: case (a,b) of x { (p,q) -> ... }
383 -- Here x isn't mentioned in the RHS, so we don't want to
384 -- create the (dead) let-binding let x = (a,b) in ...
386 -- Similarly, single occurrences can be inlined vigourously
387 -- e.g. case (f x, g y) of (a,b) -> ....
388 -- If a,b occur once we can avoid constructing the let binding for them.
390 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
391 -- Consider case I# (quotInt# x y) of
392 -- I# v -> let w = J# v in ...
393 -- If we gaily inline (quotInt# x y) for v, we end up building an
395 -- let w = J# (quotInt# x y) in ...
396 -- because quotInt# can fail.
398 | preInlineUnconditionally env NotTopLevel bndr new_rhs
399 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
402 prepareRhs takes a putative RHS, checks whether it's a PAP or
403 constructor application and, if so, converts it to ANF, so that the
404 resulting thing can be inlined more easily. Thus
412 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
413 -- Adds new floats to the env iff that allows us to return a good RHS
415 prepareRhs env (Cast rhs co) -- Note [Float coercions]
416 = do { (env', rhs') <- makeTrivial env rhs
417 ; return (env', Cast rhs' co) }
420 | (Var fun, args) <- collectArgs rhs -- It's an application
421 , let n_args = valArgCount args
422 , n_args > 0 -- ...but not a trivial one
423 , isDataConWorkId fun || n_args < idArity fun -- ...and it's a constructor or PAP
424 = go env (Var fun) args
426 go env fun [] = return (env, fun)
427 go env fun (arg : args) = do { (env', arg') <- makeTrivial env arg
428 ; go env' (App fun arg') args }
430 prepareRhs env rhs -- The default case
434 Note [Float coercions]
435 ~~~~~~~~~~~~~~~~~~~~~~
436 When we find the binding
438 we'd like to transform it to
440 x = x `cast` co -- A trivial binding
441 There's a chance that e will be a constructor application or function, or something
442 like that, so moving the coerion to the usage site may well cancel the coersions
443 and lead to further optimisation. Example:
446 data instance T Int = T Int
448 foo :: Int -> Int -> Int
453 go n = case x of { T m -> go (n-m) }
454 -- This case should optimise
458 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
459 -- Binds the expression to a variable, if it's not trivial, returning the variable
463 | otherwise -- See Note [Take care] below
464 = do { var <- newId FSLIT("a") (exprType expr)
465 ; env <- completeNonRecX env NotTopLevel NonRecursive
467 ; return (env, substExpr env (Var var)) }
471 %************************************************************************
473 \subsection{Completing a lazy binding}
475 %************************************************************************
478 * deals only with Ids, not TyVars
479 * takes an already-simplified binder and RHS
480 * is used for both recursive and non-recursive bindings
481 * is used for both top-level and non-top-level bindings
483 It does the following:
484 - tries discarding a dead binding
485 - tries PostInlineUnconditionally
486 - add unfolding [this is the only place we add an unfolding]
489 It does *not* attempt to do let-to-case. Why? Because it is used for
490 - top-level bindings (when let-to-case is impossible)
491 - many situations where the "rhs" is known to be a WHNF
492 (so let-to-case is inappropriate).
494 Nor does it do the atomic-argument thing
497 completeBind :: SimplEnv
498 -> TopLevelFlag -- Flag stuck into unfolding
499 -> InId -- Old binder
500 -> OutId -> OutExpr -- New binder and RHS
502 -- completeBind may choose to do its work
503 -- * by extending the substitution (e.g. let x = y in ...)
504 -- * or by adding to the floats in the envt
506 completeBind env top_lvl old_bndr new_bndr new_rhs
507 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
508 -- Inline and discard the binding
509 = do { tick (PostInlineUnconditionally old_bndr)
510 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
511 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
512 -- Use the substitution to make quite, quite sure that the
513 -- substitution will happen, since we are going to discard the binding
518 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
521 -- Add the unfolding *only* for non-loop-breakers
522 -- Making loop breakers not have an unfolding at all
523 -- means that we can avoid tests in exprIsConApp, for example.
524 -- This is important: if exprIsConApp says 'yes' for a recursive
525 -- thing, then we can get into an infinite loop
528 -- If the unfolding is a value, the demand info may
529 -- go pear-shaped, so we nuke it. Example:
531 -- case x of (p,q) -> h p q x
532 -- Here x is certainly demanded. But after we've nuked
533 -- the case, we'll get just
534 -- let x = (a,b) in h a b x
535 -- and now x is not demanded (I'm assuming h is lazy)
536 -- This really happens. Similarly
537 -- let f = \x -> e in ...f..f...
538 -- After inlining f at some of its call sites the original binding may
539 -- (for example) be no longer strictly demanded.
540 -- The solution here is a bit ad hoc...
541 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
542 final_info | loop_breaker = new_bndr_info
543 | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
544 | otherwise = info_w_unf
546 final_id = new_bndr `setIdInfo` final_info
548 -- These seqs forces the Id, and hence its IdInfo,
549 -- and hence any inner substitutions
551 -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
552 return (addNonRec env final_id new_rhs)
554 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
555 loop_breaker = isNonRuleLoopBreaker occ_info
556 old_info = idInfo old_bndr
557 occ_info = occInfo old_info
562 %************************************************************************
564 \subsection[Simplify-simplExpr]{The main function: simplExpr}
566 %************************************************************************
568 The reason for this OutExprStuff stuff is that we want to float *after*
569 simplifying a RHS, not before. If we do so naively we get quadratic
570 behaviour as things float out.
572 To see why it's important to do it after, consider this (real) example:
586 a -- Can't inline a this round, cos it appears twice
590 Each of the ==> steps is a round of simplification. We'd save a
591 whole round if we float first. This can cascade. Consider
596 let f = let d1 = ..d.. in \y -> e
600 in \x -> ...(\y ->e)...
602 Only in this second round can the \y be applied, and it
603 might do the same again.
607 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
608 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
610 expr_ty' = substTy env (exprType expr)
611 -- The type in the Stop continuation, expr_ty', is usually not used
612 -- It's only needed when discarding continuations after finding
613 -- a function that returns bottom.
614 -- Hence the lazy substitution
617 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
618 -- Simplify an expression, given a continuation
619 simplExprC env expr cont
620 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
621 do { (env', expr') <- simplExprF (zapFloats env) expr cont
622 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
623 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
624 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
625 return (wrapFloats env' expr') }
627 --------------------------------------------------
628 simplExprF :: SimplEnv -> InExpr -> SimplCont
629 -> SimplM (SimplEnv, OutExpr)
631 simplExprF env e cont
632 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
633 simplExprF' env e cont
635 simplExprF' env (Var v) cont = simplVar env v cont
636 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
637 simplExprF' env (Note n expr) cont = simplNote env n expr cont
638 simplExprF' env (Cast body co) cont = simplCast env body co cont
639 simplExprF' env (App fun arg) cont = simplExprF env fun $
640 ApplyTo NoDup arg env cont
642 simplExprF' env expr@(Lam _ _) cont
643 = simplLam env (map zap bndrs) body cont
644 -- The main issue here is under-saturated lambdas
645 -- (\x1. \x2. e) arg1
646 -- Here x1 might have "occurs-once" occ-info, because occ-info
647 -- is computed assuming that a group of lambdas is applied
648 -- all at once. If there are too few args, we must zap the
651 n_args = countArgs cont
652 n_params = length bndrs
653 (bndrs, body) = collectBinders expr
654 zap | n_args >= n_params = \b -> b
655 | otherwise = \b -> if isTyVar b then b
657 -- NB: we count all the args incl type args
658 -- so we must count all the binders (incl type lambdas)
660 simplExprF' env (Type ty) cont
661 = ASSERT( contIsRhsOrArg cont )
662 do { ty' <- simplType env ty
663 ; rebuild env (Type ty') cont }
665 simplExprF' env (Case scrut bndr case_ty alts) cont
666 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
667 = -- Simplify the scrutinee with a Select continuation
668 simplExprF env scrut (Select NoDup bndr alts env cont)
671 = -- If case-of-case is off, simply simplify the case expression
672 -- in a vanilla Stop context, and rebuild the result around it
673 do { case_expr' <- simplExprC env scrut case_cont
674 ; rebuild env case_expr' cont }
676 case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
677 case_ty' = substTy env case_ty -- c.f. defn of simplExpr
679 simplExprF' env (Let (Rec pairs) body) cont
680 = do { env <- simplRecBndrs env (map fst pairs)
681 -- NB: bndrs' don't have unfoldings or rules
682 -- We add them as we go down
684 ; env <- simplRecBind env NotTopLevel pairs
685 ; simplExprF env body cont }
687 simplExprF' env (Let (NonRec bndr rhs) body) cont
688 = simplNonRecE env bndr (rhs, env) ([], body) cont
690 ---------------------------------
691 simplType :: SimplEnv -> InType -> SimplM OutType
692 -- Kept monadic just so we can do the seqType
694 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
695 seqType new_ty `seq` returnSmpl new_ty
697 new_ty = substTy env ty
701 %************************************************************************
703 \subsection{The main rebuilder}
705 %************************************************************************
708 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
709 -- At this point the substitution in the SimplEnv should be irrelevant
710 -- only the in-scope set and floats should matter
711 rebuild env expr cont
712 = -- pprTrace "rebuild" (ppr expr $$ ppr cont $$ ppr (seFloats env)) $
714 Stop {} -> return (env, expr)
715 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
716 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
717 StrictArg fun ty info cont -> rebuildCall env (fun `App` expr) (funResultTy ty) info cont
718 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
719 ; simplLam env' bs body cont }
720 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
721 ; rebuild env (App expr arg') cont }
725 %************************************************************************
729 %************************************************************************
732 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
733 -> SimplM (SimplEnv, OutExpr)
734 simplCast env body co cont
735 = do { co' <- simplType env co
736 ; simplExprF env body (addCoerce co' cont) }
738 addCoerce co cont = add_coerce co (coercionKind co) cont
740 add_coerce co (s1, k1) cont -- co :: ty~ty
741 | s1 `coreEqType` k1 = cont -- is a no-op
743 add_coerce co1 (s1, k2) (CoerceIt co2 cont)
744 | (l1, t1) <- coercionKind co2
745 -- coerce T1 S1 (coerce S1 K1 e)
748 -- coerce T1 K1 e, otherwise
750 -- For example, in the initial form of a worker
751 -- we may find (coerce T (coerce S (\x.e))) y
752 -- and we'd like it to simplify to e[y/x] in one round
754 , s1 `coreEqType` t1 = cont -- The coerces cancel out
755 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
757 add_coerce co (s1s2, t1t2) (ApplyTo dup arg arg_se cont)
758 | not (isTypeArg arg) -- This whole case only works for value args
759 -- Could upgrade to have equiv thing for type apps too
760 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
761 -- co : s1s2 :=: t1t2
762 -- (coerce (T1->T2) (S1->S2) F) E
764 -- coerce T2 S2 (F (coerce S1 T1 E))
766 -- t1t2 must be a function type, T1->T2, because it's applied
767 -- to something but s1s2 might conceivably not be
769 -- When we build the ApplyTo we can't mix the out-types
770 -- with the InExpr in the argument, so we simply substitute
771 -- to make it all consistent. It's a bit messy.
772 -- But it isn't a common case.
774 -- Example of use: Trac #995
775 = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
777 -- we split coercion t1->t2 :=: s1->s2 into t1 :=: s1 and
778 -- t2 :=: s2 with left and right on the curried form:
779 -- (->) t1 t2 :=: (->) s1 s2
780 [co1, co2] = decomposeCo 2 co
781 new_arg = mkCoerce (mkSymCoercion co1) arg'
782 arg' = substExpr arg_se arg
784 add_coerce co _ cont = CoerceIt co cont
788 %************************************************************************
792 %************************************************************************
795 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
796 -> SimplM (SimplEnv, OutExpr)
798 simplLam env [] body cont = simplExprF env body cont
800 -- Type-beta reduction
801 simplLam env (bndr:bndrs) body (ApplyTo _ (Type ty_arg) arg_se cont)
802 = ASSERT( isTyVar bndr )
803 do { tick (BetaReduction bndr)
804 ; ty_arg' <- simplType (arg_se `setInScope` env) ty_arg
805 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
807 -- Ordinary beta reduction
808 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
809 = do { tick (BetaReduction bndr)
810 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
812 -- Not enough args, so there are real lambdas left to put in the result
813 simplLam env bndrs body cont
814 = do { (env, bndrs') <- simplLamBndrs env bndrs
815 ; body' <- simplExpr env body
816 ; new_lam <- mkLam bndrs' body'
817 ; rebuild env new_lam cont }
820 simplNonRecE :: SimplEnv
821 -> InId -- The binder
822 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
823 -> ([InId], InExpr) -- Body of the let/lambda
826 -> SimplM (SimplEnv, OutExpr)
828 -- simplNonRecE is used for
829 -- * non-top-level non-recursive lets in expressions
832 -- It deals with strict bindings, via the StrictBind continuation,
833 -- which may abort the whole process
835 -- The "body" of the binding comes as a pair of ([InId],InExpr)
836 -- representing a lambda; so we recurse back to simplLam
837 -- Why? Because of the binder-occ-info-zapping done before
838 -- the call to simplLam in simplExprF (Lam ...)
840 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
841 | preInlineUnconditionally env NotTopLevel bndr rhs
842 = do { tick (PreInlineUnconditionally bndr)
843 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
846 = do { simplExprF (rhs_se `setFloats` env) rhs
847 (StrictBind bndr bndrs body env cont) }
850 = do { (env, bndr') <- simplBinder env bndr
851 ; env <- simplLazyBind env NotTopLevel NonRecursive bndr bndr' rhs rhs_se
852 ; simplLam env bndrs body cont }
856 %************************************************************************
860 %************************************************************************
863 -- Hack alert: we only distinguish subsumed cost centre stacks for the
864 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
865 simplNote env (SCC cc) e cont
866 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
867 ; rebuild env (mkSCC cc e') cont }
869 -- See notes with SimplMonad.inlineMode
870 simplNote env InlineMe e cont
871 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
872 = do { -- Don't inline inside an INLINE expression
873 e' <- simplExpr (setMode inlineMode env) e
874 ; rebuild env (mkInlineMe e') cont }
876 | otherwise -- Dissolve the InlineMe note if there's
877 -- an interesting context of any kind to combine with
878 -- (even a type application -- anything except Stop)
879 = simplExprF env e cont
881 simplNote env (CoreNote s) e cont
882 = simplExpr env e `thenSmpl` \ e' ->
883 rebuild env (Note (CoreNote s) e') cont
887 %************************************************************************
889 \subsection{Dealing with calls}
891 %************************************************************************
894 simplVar env var cont
895 = case substId env var of
896 DoneEx e -> simplExprF (zapSubstEnv env) e cont
897 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
898 DoneId var1 -> completeCall (zapSubstEnv env) var1 cont
899 -- Note [zapSubstEnv]
900 -- The template is already simplified, so don't re-substitute.
901 -- This is VITAL. Consider
903 -- let y = \z -> ...x... in
905 -- We'll clone the inner \x, adding x->x' in the id_subst
906 -- Then when we inline y, we must *not* replace x by x' in
907 -- the inlined copy!!
909 ---------------------------------------------------------
910 -- Dealing with a call site
912 completeCall env var cont
913 = do { dflags <- getDOptsSmpl
914 ; let (args,call_cont) = contArgs cont
915 -- The args are OutExprs, obtained by *lazily* substituting
916 -- in the args found in cont. These args are only examined
917 -- to limited depth (unless a rule fires). But we must do
918 -- the substitution; rule matching on un-simplified args would
921 ------------- First try rules ----------------
922 -- Do this before trying inlining. Some functions have
923 -- rules *and* are strict; in this case, we don't want to
924 -- inline the wrapper of the non-specialised thing; better
925 -- to call the specialised thing instead.
927 -- We used to use the black-listing mechanism to ensure that inlining of
928 -- the wrapper didn't occur for things that have specialisations till a
929 -- later phase, so but now we just try RULES first
931 -- You might think that we shouldn't apply rules for a loop breaker:
932 -- doing so might give rise to an infinite loop, because a RULE is
933 -- rather like an extra equation for the function:
934 -- RULE: f (g x) y = x+y
937 -- But it's too drastic to disable rules for loop breakers.
938 -- Even the foldr/build rule would be disabled, because foldr
939 -- is recursive, and hence a loop breaker:
940 -- foldr k z (build g) = g k z
941 -- So it's up to the programmer: rules can cause divergence
942 ; let in_scope = getInScope env
944 maybe_rule = case activeRule env of
945 Nothing -> Nothing -- No rules apply
946 Just act_fn -> lookupRule act_fn in_scope
948 ; case maybe_rule of {
949 Just (rule, rule_rhs) ->
950 tick (RuleFired (ru_name rule)) `thenSmpl_`
951 (if dopt Opt_D_dump_rule_firings dflags then
952 pprTrace "Rule fired" (vcat [
953 text "Rule:" <+> ftext (ru_name rule),
954 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
955 text "After: " <+> pprCoreExpr rule_rhs,
956 text "Cont: " <+> ppr call_cont])
959 simplExprF env rule_rhs (dropArgs (ruleArity rule) cont)
960 -- The ruleArity says how many args the rule consumed
962 ; Nothing -> do -- No rules
964 ------------- Next try inlining ----------------
965 { let arg_infos = [interestingArg arg | arg <- args, isValArg arg]
966 n_val_args = length arg_infos
967 interesting_cont = interestingCallContext (notNull args)
970 active_inline = activeInline env var
971 maybe_inline = callSiteInline dflags active_inline
972 var arg_infos interesting_cont
973 ; case maybe_inline of {
974 Just unfolding -- There is an inlining!
975 -> do { tick (UnfoldingDone var)
976 ; (if dopt Opt_D_dump_inlinings dflags then
977 pprTrace "Inlining done" (vcat [
978 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
979 text "Inlined fn: " <+> nest 2 (ppr unfolding),
980 text "Cont: " <+> ppr call_cont])
983 simplExprF env unfolding cont }
985 ; Nothing -> -- No inlining!
987 ------------- No inlining! ----------------
988 -- Next, look for rules or specialisations that match
990 rebuildCall env (Var var) (idType var)
991 (mkArgInfo var n_val_args call_cont) cont
994 rebuildCall :: SimplEnv
995 -> OutExpr -> OutType -- Function and its type
996 -> (Bool, [Bool]) -- See SimplUtils.mkArgInfo
998 -> SimplM (SimplEnv, OutExpr)
999 rebuildCall env fun fun_ty (has_rules, []) cont
1000 -- When we run out of strictness args, it means
1001 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1002 -- Then we want to discard the entire strict continuation. E.g.
1003 -- * case (error "hello") of { ... }
1004 -- * (error "Hello") arg
1005 -- * f (error "Hello") where f is strict
1007 -- Then, especially in the first of these cases, we'd like to discard
1008 -- the continuation, leaving just the bottoming expression. But the
1009 -- type might not be right, so we may have to add a coerce.
1010 | not (contIsTrivial cont) -- Only do thia if there is a non-trivial
1011 = return (env, mk_coerce fun) -- contination to discard, else we do it
1012 where -- again and again!
1013 cont_ty = contResultType cont
1014 co = mkUnsafeCoercion fun_ty cont_ty
1015 mk_coerce expr | cont_ty `coreEqType` fun_ty = fun
1016 | otherwise = mkCoerce co fun
1018 rebuildCall env fun fun_ty info (ApplyTo _ (Type arg_ty) se cont)
1019 = do { ty' <- simplType (se `setInScope` env) arg_ty
1020 ; rebuildCall env (fun `App` Type ty') (applyTy fun_ty ty') info cont }
1022 rebuildCall env fun fun_ty (has_rules, str:strs) (ApplyTo _ arg arg_se cont)
1023 | str || isStrictType arg_ty -- Strict argument
1024 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1025 simplExprF (arg_se `setFloats` env) arg
1026 (StrictArg fun fun_ty (has_rules, strs) cont)
1029 | otherwise -- Lazy argument
1030 -- DO NOT float anything outside, hence simplExprC
1031 -- There is no benefit (unlike in a let-binding), and we'd
1032 -- have to be very careful about bogus strictness through
1033 -- floating a demanded let.
1034 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1035 (mkLazyArgStop arg_ty has_rules)
1036 ; rebuildCall env (fun `App` arg') res_ty (has_rules, strs) cont }
1038 (arg_ty, res_ty) = splitFunTy fun_ty
1040 rebuildCall env fun fun_ty info cont
1041 = rebuild env fun cont
1046 This part of the simplifier may break the no-shadowing invariant
1048 f (...(\a -> e)...) (case y of (a,b) -> e')
1049 where f is strict in its second arg
1050 If we simplify the innermost one first we get (...(\a -> e)...)
1051 Simplifying the second arg makes us float the case out, so we end up with
1052 case y of (a,b) -> f (...(\a -> e)...) e'
1053 So the output does not have the no-shadowing invariant. However, there is
1054 no danger of getting name-capture, because when the first arg was simplified
1055 we used an in-scope set that at least mentioned all the variables free in its
1056 static environment, and that is enough.
1058 We can't just do innermost first, or we'd end up with a dual problem:
1059 case x of (a,b) -> f e (...(\a -> e')...)
1061 I spent hours trying to recover the no-shadowing invariant, but I just could
1062 not think of an elegant way to do it. The simplifier is already knee-deep in
1063 continuations. We have to keep the right in-scope set around; AND we have
1064 to get the effect that finding (error "foo") in a strict arg position will
1065 discard the entire application and replace it with (error "foo"). Getting
1066 all this at once is TOO HARD!
1068 %************************************************************************
1070 Rebuilding a cse expression
1072 %************************************************************************
1074 Blob of helper functions for the "case-of-something-else" situation.
1077 ---------------------------------------------------------
1078 -- Eliminate the case if possible
1080 rebuildCase :: SimplEnv
1081 -> OutExpr -- Scrutinee
1082 -> InId -- Case binder
1083 -> [InAlt] -- Alternatives (inceasing order)
1085 -> SimplM (SimplEnv, OutExpr)
1087 rebuildCase env scrut case_bndr alts cont
1088 | Just (con,args) <- exprIsConApp_maybe scrut
1089 -- Works when the scrutinee is a variable with a known unfolding
1090 -- as well as when it's an explicit constructor application
1091 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1093 | Lit lit <- scrut -- No need for same treatment as constructors
1094 -- because literals are inlined more vigorously
1095 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1098 = do { -- Prepare the continuation;
1099 -- The new subst_env is in place
1100 (env, dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1102 -- Simplify the alternatives
1103 ; (case_bndr', alts') <- simplAlts env scrut case_bndr alts dup_cont
1104 ; let res_ty' = contResultType dup_cont
1105 ; case_expr <- mkCase scrut case_bndr' res_ty' alts'
1107 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1108 -- The case binder *not* scope over the whole returned case-expression
1109 ; rebuild env case_expr nodup_cont }
1112 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1113 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1114 way, there's a chance that v will now only be used once, and hence
1117 Note [no-case-of-case]
1118 ~~~~~~~~~~~~~~~~~~~~~~
1119 There is a time we *don't* want to do that, namely when
1120 -fno-case-of-case is on. This happens in the first simplifier pass,
1121 and enhances full laziness. Here's the bad case:
1122 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1123 If we eliminate the inner case, we trap it inside the I# v -> arm,
1124 which might prevent some full laziness happening. I've seen this
1125 in action in spectral/cichelli/Prog.hs:
1126 [(m,n) | m <- [1..max], n <- [1..max]]
1127 Hence the check for NoCaseOfCase.
1129 Note [Suppressing the case binder-swap]
1130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1131 There is another situation when it might make sense to suppress the
1132 case-expression binde-swap. If we have
1134 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1135 ...other cases .... }
1137 We'll perform the binder-swap for the outer case, giving
1139 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1140 ...other cases .... }
1142 But there is no point in doing it for the inner case, because w1 can't
1143 be inlined anyway. Furthermore, doing the case-swapping involves
1144 zapping w2's occurrence info (see paragraphs that follow), and that
1145 forces us to bind w2 when doing case merging. So we get
1147 case x of w1 { A -> let w2 = w1 in e1
1148 B -> let w2 = w1 in e2
1149 ...other cases .... }
1151 This is plain silly in the common case where w2 is dead.
1153 Even so, I can't see a good way to implement this idea. I tried
1154 not doing the binder-swap if the scrutinee was already evaluated
1155 but that failed big-time:
1159 case v of w { MkT x ->
1160 case x of x1 { I# y1 ->
1161 case x of x2 { I# y2 -> ...
1163 Notice that because MkT is strict, x is marked "evaluated". But to
1164 eliminate the last case, we must either make sure that x (as well as
1165 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1166 the binder-swap. So this whole note is a no-op.
1170 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1171 any occurrence info (eg IAmDead) in the case binder, because the
1172 case-binder now effectively occurs whenever v does. AND we have to do
1173 the same for the pattern-bound variables! Example:
1175 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1177 Here, b and p are dead. But when we move the argment inside the first
1178 case RHS, and eliminate the second case, we get
1180 case x of { (a,b) -> a b }
1182 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1185 Indeed, this can happen anytime the case binder isn't dead:
1186 case <any> of x { (a,b) ->
1187 case x of { (p,q) -> p } }
1188 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1189 The point is that we bring into the envt a binding
1191 after the outer case, and that makes (a,b) alive. At least we do unless
1192 the case binder is guaranteed dead.
1196 Consider case (v `cast` co) of x { I# ->
1197 ... (case (v `cast` co) of {...}) ...
1198 We'd like to eliminate the inner case. We can get this neatly by
1199 arranging that inside the outer case we add the unfolding
1200 v |-> x `cast` (sym co)
1201 to v. Then we should inline v at the inner case, cancel the casts, and away we go
1204 simplCaseBinder :: SimplEnv -> OutExpr -> InId -> SimplM (SimplEnv, OutId)
1205 simplCaseBinder env scrut case_bndr
1206 | switchIsOn (getSwitchChecker env) NoCaseOfCase
1207 -- See Note [no-case-of-case]
1208 = do { (env, case_bndr') <- simplBinder env case_bndr
1209 ; return (env, case_bndr') }
1211 simplCaseBinder env (Var v) case_bndr
1212 -- Failed try [see Note 2 above]
1213 -- not (isEvaldUnfolding (idUnfolding v))
1214 = do { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1215 ; return (modifyInScope env v case_bndr', case_bndr') }
1216 -- We could extend the substitution instead, but it would be
1217 -- a hack because then the substitution wouldn't be idempotent
1218 -- any more (v is an OutId). And this does just as well.
1220 simplCaseBinder env (Cast (Var v) co) case_bndr -- Note [Case of cast]
1221 = do { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1222 ; let rhs = Cast (Var case_bndr') (mkSymCoercion co)
1223 ; return (addBinderUnfolding env v rhs, case_bndr') }
1225 simplCaseBinder env other_scrut case_bndr
1226 = do { (env, case_bndr') <- simplBinder env case_bndr
1227 ; return (env, case_bndr') }
1229 zapOccInfo :: InId -> InId -- See Note [zapOccInfo]
1230 zapOccInfo b = b `setIdOccInfo` NoOccInfo
1234 simplAlts does two things:
1236 1. Eliminate alternatives that cannot match, including the
1237 DEFAULT alternative.
1239 2. If the DEFAULT alternative can match only one possible constructor,
1240 then make that constructor explicit.
1242 case e of x { DEFAULT -> rhs }
1244 case e of x { (a,b) -> rhs }
1245 where the type is a single constructor type. This gives better code
1246 when rhs also scrutinises x or e.
1248 Here "cannot match" includes knowledge from GADTs
1250 It's a good idea do do this stuff before simplifying the alternatives, to
1251 avoid simplifying alternatives we know can't happen, and to come up with
1252 the list of constructors that are handled, to put into the IdInfo of the
1253 case binder, for use when simplifying the alternatives.
1255 Eliminating the default alternative in (1) isn't so obvious, but it can
1258 data Colour = Red | Green | Blue
1267 DEFAULT -> [ case y of ... ]
1269 If we inline h into f, the default case of the inlined h can't happen.
1270 If we don't notice this, we may end up filtering out *all* the cases
1271 of the inner case y, which give us nowhere to go!
1275 simplAlts :: SimplEnv
1277 -> InId -- Case binder
1278 -> [InAlt] -> SimplCont
1279 -> SimplM (OutId, [OutAlt]) -- Includes the continuation
1280 -- Like simplExpr, this just returns the simplified alternatives;
1281 -- it not return an environment
1283 simplAlts env scrut case_bndr alts cont'
1284 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1285 do { let alt_env = zapFloats env
1286 ; (alt_env, case_bndr') <- simplCaseBinder alt_env scrut case_bndr
1288 ; default_alts <- prepareDefault alt_env case_bndr' imposs_deflt_cons cont' maybe_deflt
1290 ; let inst_tys = tyConAppArgs (idType case_bndr')
1291 trimmed_alts = filter (is_possible inst_tys) alts_wo_default
1292 in_alts = mergeAlts default_alts trimmed_alts
1293 -- We need the mergeAlts in case the new default_alt
1294 -- has turned into a constructor alternative.
1296 ; alts' <- mapM (simplAlt alt_env imposs_cons case_bndr' cont') in_alts
1297 ; return (case_bndr', alts') }
1299 (alts_wo_default, maybe_deflt) = findDefault alts
1300 imposs_cons = case scrut of
1301 Var v -> otherCons (idUnfolding v)
1304 -- "imposs_deflt_cons" are handled either by the context,
1305 -- OR by a branch in this case expression. (Don't include DEFAULT!!)
1306 imposs_deflt_cons = nub (imposs_cons ++ [con | (con,_,_) <- alts_wo_default])
1308 is_possible :: [Type] -> CoreAlt -> Bool
1309 is_possible tys (con, _, _) | con `elem` imposs_cons = False
1310 is_possible tys (DataAlt con, _, _) = dataConCanMatch tys con
1311 is_possible tys alt = True
1313 ------------------------------------
1314 prepareDefault :: SimplEnv
1315 -> OutId -- Case binder; need just for its type. Note that as an
1316 -- OutId, it has maximum information; this is important.
1317 -- Test simpl013 is an example
1318 -> [AltCon] -- These cons can't happen when matching the default
1321 -> SimplM [InAlt] -- One branch or none; still unsimplified
1322 -- We use a list because it's what mergeAlts expects
1324 prepareDefault env case_bndr' imposs_cons cont Nothing
1325 = return [] -- No default branch
1327 prepareDefault env case_bndr' imposs_cons cont (Just rhs)
1328 | -- This branch handles the case where we are
1329 -- scrutinisng an algebraic data type
1330 Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr'),
1331 isAlgTyCon tycon, -- It's a data type, tuple, or unboxed tuples.
1332 not (isNewTyCon tycon), -- We can have a newtype, if we are just doing an eval:
1333 -- case x of { DEFAULT -> e }
1334 -- and we don't want to fill in a default for them!
1335 Just all_cons <- tyConDataCons_maybe tycon,
1336 not (null all_cons), -- This is a tricky corner case. If the data type has no constructors,
1337 -- which GHC allows, then the case expression will have at most a default
1338 -- alternative. We don't want to eliminate that alternative, because the
1339 -- invariant is that there's always one alternative. It's more convenient
1341 -- case x of { DEFAULT -> e }
1342 -- as it is, rather than transform it to
1343 -- error "case cant match"
1344 -- which would be quite legitmate. But it's a really obscure corner, and
1345 -- not worth wasting code on.
1347 let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1348 is_possible con = not (con `elem` imposs_data_cons)
1349 && dataConCanMatch inst_tys con
1350 = case filter is_possible all_cons of
1351 [] -> return [] -- Eliminate the default alternative
1352 -- altogether if it can't match
1354 [con] -> -- It matches exactly one constructor, so fill it in
1355 do { tick (FillInCaseDefault case_bndr')
1356 ; us <- getUniquesSmpl
1357 ; let (ex_tvs, co_tvs, arg_ids) =
1358 dataConRepInstPat us con inst_tys
1359 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, rhs)] }
1361 two_or_more -> return [(DEFAULT, [], rhs)]
1364 = return [(DEFAULT, [], rhs)]
1366 ------------------------------------
1367 simplAlt :: SimplEnv
1368 -> [AltCon] -- These constructors can't be present when
1369 -- matching this alternative
1370 -> OutId -- The case binder
1375 -- Simplify an alternative, returning the type refinement for the
1376 -- alternative, if the alternative does any refinement at all
1378 simplAlt env handled_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1379 = ASSERT( null bndrs )
1380 do { let env' = addBinderOtherCon env case_bndr' handled_cons
1381 -- Record the constructors that the case-binder *can't* be.
1382 ; rhs' <- simplExprC env' rhs cont'
1383 ; return (DEFAULT, [], rhs') }
1385 simplAlt env handled_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1386 = ASSERT( null bndrs )
1387 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1388 ; rhs' <- simplExprC env' rhs cont'
1389 ; return (LitAlt lit, [], rhs') }
1391 simplAlt env handled_cons case_bndr' cont' (DataAlt con, vs, rhs)
1392 = do { -- Deal with the pattern-bound variables
1393 -- Mark the ones that are in ! positions in the data constructor
1394 -- as certainly-evaluated.
1395 -- NB: it happens that simplBinders does *not* erase the OtherCon
1396 -- form of unfolding, so it's ok to add this info before
1397 -- doing simplBinders
1398 (env, vs') <- simplBinders env (add_evals con vs)
1400 -- Bind the case-binder to (con args)
1401 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1402 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1403 env' = addBinderUnfolding env case_bndr' (mkConApp con con_args)
1405 ; rhs' <- simplExprC env' rhs cont'
1406 ; return (DataAlt con, vs', rhs') }
1408 -- add_evals records the evaluated-ness of the bound variables of
1409 -- a case pattern. This is *important*. Consider
1410 -- data T = T !Int !Int
1412 -- case x of { T a b -> T (a+1) b }
1414 -- We really must record that b is already evaluated so that we don't
1415 -- go and re-evaluate it when constructing the result.
1416 -- See Note [Data-con worker strictness] in MkId.lhs
1417 add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1419 cat_evals dc vs strs
1423 go (v:vs) strs | isTyVar v = v : go vs strs
1424 go (v:vs) (str:strs)
1425 | isMarkedStrict str = evald_v : go vs strs
1426 | otherwise = zapped_v : go vs strs
1428 zapped_v = zap_occ_info v
1429 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1430 go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1432 -- If the case binder is alive, then we add the unfolding
1434 -- to the envt; so vs are now very much alive
1435 -- Note [Aug06] I can't see why this actually matters
1436 zap_occ_info | isDeadBinder case_bndr' = \id -> id
1437 | otherwise = zapOccInfo
1439 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1440 addBinderUnfolding env bndr rhs
1441 = modifyInScope env bndr (bndr `setIdUnfolding` mkUnfolding False rhs)
1443 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1444 addBinderOtherCon env bndr cons
1445 = modifyInScope env bndr (bndr `setIdUnfolding` mkOtherCon cons)
1449 %************************************************************************
1451 \subsection{Known constructor}
1453 %************************************************************************
1455 We are a bit careful with occurrence info. Here's an example
1457 (\x* -> case x of (a*, b) -> f a) (h v, e)
1459 where the * means "occurs once". This effectively becomes
1460 case (h v, e) of (a*, b) -> f a)
1462 let a* = h v; b = e in f a
1466 All this should happen in one sweep.
1469 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1470 -> InId -> [InAlt] -> SimplCont
1471 -> SimplM (SimplEnv, OutExpr)
1473 knownCon env scrut con args bndr alts cont
1474 = do { tick (KnownBranch bndr)
1475 ; knownAlt env scrut args bndr (findAlt con alts) cont }
1477 knownAlt env scrut args bndr (DEFAULT, bs, rhs) cont
1479 do { env <- simplNonRecX env bndr scrut
1480 -- This might give rise to a binding with non-atomic args
1481 -- like x = Node (f x) (g x)
1482 -- but simplNonRecX will atomic-ify it
1483 ; simplExprF env rhs cont }
1485 knownAlt env scrut args bndr (LitAlt lit, bs, rhs) cont
1487 do { env <- simplNonRecX env bndr scrut
1488 ; simplExprF env rhs cont }
1490 knownAlt env scrut args bndr (DataAlt dc, bs, rhs) cont
1491 = do { let dead_bndr = isDeadBinder bndr
1492 n_drop_tys = tyConArity (dataConTyCon dc)
1493 ; env <- bind_args env dead_bndr bs (drop n_drop_tys args)
1495 -- It's useful to bind bndr to scrut, rather than to a fresh
1496 -- binding x = Con arg1 .. argn
1497 -- because very often the scrut is a variable, so we avoid
1498 -- creating, and then subsequently eliminating, a let-binding
1499 -- BUT, if scrut is a not a variable, we must be careful
1500 -- about duplicating the arg redexes; in that case, make
1501 -- a new con-app from the args
1502 bndr_rhs = case scrut of
1505 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1506 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1507 -- args are aready OutExprs, but bs are InIds
1509 ; env <- simplNonRecX env bndr bndr_rhs
1510 ; -- pprTrace "knownCon2" (ppr bs $$ ppr rhs $$ ppr (seIdSubst env)) $
1511 simplExprF env rhs cont }
1514 bind_args env dead_bndr [] _ = return env
1516 bind_args env dead_bndr (b:bs) (Type ty : args)
1517 = ASSERT( isTyVar b )
1518 bind_args (extendTvSubst env b ty) dead_bndr bs args
1520 bind_args env dead_bndr (b:bs) (arg : args)
1522 do { let b' = if dead_bndr then b else zapOccInfo b
1523 -- Note that the binder might be "dead", because it doesn't occur
1524 -- in the RHS; and simplNonRecX may therefore discard it via postInlineUnconditionally
1525 -- Nevertheless we must keep it if the case-binder is alive, because it may
1526 -- be used in the con_app. See Note [zapOccInfo]
1527 ; env <- simplNonRecX env b' arg
1528 ; bind_args env dead_bndr bs args }
1530 bind_args _ _ _ _ = panic "bind_args"
1534 %************************************************************************
1536 \subsection{Duplicating continuations}
1538 %************************************************************************
1541 prepareCaseCont :: SimplEnv
1542 -> [InAlt] -> SimplCont
1543 -> SimplM (SimplEnv, SimplCont,SimplCont)
1544 -- Return a duplicatable continuation, a non-duplicable part
1545 -- plus some extra bindings (that scope over the entire
1548 -- No need to make it duplicatable if there's only one alternative
1549 prepareCaseCont env [alt] cont = return (env, cont, mkBoringStop (contResultType cont))
1550 prepareCaseCont env alts cont = mkDupableCont env cont
1554 mkDupableCont :: SimplEnv -> SimplCont
1555 -> SimplM (SimplEnv, SimplCont, SimplCont)
1557 mkDupableCont env cont
1558 | contIsDupable cont
1559 = returnSmpl (env, cont, mkBoringStop (contResultType cont))
1561 mkDupableCont env (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1563 mkDupableCont env (CoerceIt ty cont)
1564 = do { (env, dup, nodup) <- mkDupableCont env cont
1565 ; return (env, CoerceIt ty dup, nodup) }
1567 mkDupableCont env cont@(StrictBind bndr _ _ se _)
1568 = return (env, mkBoringStop (substTy se (idType bndr)), cont)
1569 -- See Note [Duplicating strict continuations]
1571 mkDupableCont env cont@(StrictArg _ fun_ty _ _)
1572 = return (env, mkBoringStop (funArgTy fun_ty), cont)
1573 -- See Note [Duplicating strict continuations]
1575 mkDupableCont env (ApplyTo _ arg se cont)
1576 = -- e.g. [...hole...] (...arg...)
1578 -- let a = ...arg...
1579 -- in [...hole...] a
1580 do { (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1581 ; arg <- simplExpr (se `setInScope` env) arg
1582 ; (env, arg) <- makeTrivial env arg
1583 ; let app_cont = ApplyTo OkToDup arg (zapSubstEnv env) dup_cont
1584 ; return (env, app_cont, nodup_cont) }
1586 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1587 -- See Note [Single-alternative case]
1588 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1589 -- | not (isDeadBinder case_bndr)
1590 | all isDeadBinder bs
1591 = return (env, mkBoringStop scrut_ty, cont)
1593 scrut_ty = substTy se (idType case_bndr)
1595 mkDupableCont env (Select _ case_bndr alts se cont)
1596 = -- e.g. (case [...hole...] of { pi -> ei })
1598 -- let ji = \xij -> ei
1599 -- in case [...hole...] of { pi -> ji xij }
1600 do { tick (CaseOfCase case_bndr)
1601 ; (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1602 -- NB: call mkDupableCont here, *not* prepareCaseCont
1603 -- We must make a duplicable continuation, whereas prepareCaseCont
1604 -- doesn't when there is a single case branch
1606 ; let alt_env = se `setInScope` env
1607 ; (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1608 ; alts' <- mapM (simplAlt alt_env [] case_bndr' dup_cont) alts
1609 -- Safe to say that there are no handled-cons for the DEFAULT case
1610 -- NB: simplBinder does not zap deadness occ-info, so
1611 -- a dead case_bndr' will still advertise its deadness
1612 -- This is really important because in
1613 -- case e of b { (# a,b #) -> ... }
1614 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1615 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1616 -- In the new alts we build, we have the new case binder, so it must retain
1618 -- NB: we don't use alt_env further; it has the substEnv for
1619 -- the alternatives, and we don't want that
1621 ; (env, alts') <- mkDupableAlts env case_bndr' alts'
1622 ; return (env, -- Note [Duplicated env]
1623 Select OkToDup case_bndr' alts' (zapSubstEnv env)
1624 (mkBoringStop (contResultType dup_cont)),
1628 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1629 -> SimplM (SimplEnv, [InAlt])
1630 -- Absorbs the continuation into the new alternatives
1632 mkDupableAlts env case_bndr' alts
1635 go env [] = return (env, [])
1637 = do { (env, alt') <- mkDupableAlt env case_bndr' alt
1638 ; (env, alts') <- go env alts
1639 ; return (env, alt' : alts' ) }
1641 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1642 | exprIsDupable rhs' -- Note [Small alternative rhs]
1643 = return (env, (con, bndrs', rhs'))
1645 = do { let rhs_ty' = exprType rhs'
1646 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1648 | isTyVar bndr = True -- Abstract over all type variables just in case
1649 | otherwise = not (isDeadBinder bndr)
1650 -- The deadness info on the new Ids is preserved by simplBinders
1652 ; (final_bndrs', final_args) -- Note [Join point abstraction]
1653 <- if (any isId used_bndrs')
1654 then return (used_bndrs', varsToCoreExprs used_bndrs')
1655 else do { rw_id <- newId FSLIT("w") realWorldStatePrimTy
1656 ; return ([rw_id], [Var realWorldPrimId]) }
1658 ; join_bndr <- newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty')
1659 -- Note [Funky mkPiTypes]
1661 ; let -- We make the lambdas into one-shot-lambdas. The
1662 -- join point is sure to be applied at most once, and doing so
1663 -- prevents the body of the join point being floated out by
1664 -- the full laziness pass
1665 really_final_bndrs = map one_shot final_bndrs'
1666 one_shot v | isId v = setOneShotLambda v
1668 join_rhs = mkLams really_final_bndrs rhs'
1669 join_call = mkApps (Var join_bndr) final_args
1671 ; return (addNonRec env join_bndr join_rhs, (con, bndrs', join_call)) }
1672 -- See Note [Duplicated env]
1675 Note [Duplicated env]
1676 ~~~~~~~~~~~~~~~~~~~~~
1677 Some of the alternatives are simplified, but have not been turned into a join point
1678 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
1679 bind the join point, because it might to do PostInlineUnconditionally, and
1680 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
1681 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1682 at worst delays the join-point inlining.
1684 Note [Small alterantive rhs]
1685 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1686 It is worth checking for a small RHS because otherwise we
1687 get extra let bindings that may cause an extra iteration of the simplifier to
1688 inline back in place. Quite often the rhs is just a variable or constructor.
1689 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1690 iterations because the version with the let bindings looked big, and so wasn't
1691 inlined, but after the join points had been inlined it looked smaller, and so
1694 NB: we have to check the size of rhs', not rhs.
1695 Duplicating a small InAlt might invalidate occurrence information
1696 However, if it *is* dupable, we return the *un* simplified alternative,
1697 because otherwise we'd need to pair it up with an empty subst-env....
1698 but we only have one env shared between all the alts.
1699 (Remember we must zap the subst-env before re-simplifying something).
1700 Rather than do this we simply agree to re-simplify the original (small) thing later.
1702 Note [Funky mkPiTypes]
1703 ~~~~~~~~~~~~~~~~~~~~~~
1704 Notice the funky mkPiTypes. If the contructor has existentials
1705 it's possible that the join point will be abstracted over
1706 type varaibles as well as term variables.
1707 Example: Suppose we have
1708 data T = forall t. C [t]
1710 case (case e of ...) of
1712 We get the join point
1713 let j :: forall t. [t] -> ...
1714 j = /\t \xs::[t] -> rhs
1716 case (case e of ...) of
1717 C t xs::[t] -> j t xs
1719 Note [Join point abstaction]
1720 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1721 If we try to lift a primitive-typed something out
1722 for let-binding-purposes, we will *caseify* it (!),
1723 with potentially-disastrous strictness results. So
1724 instead we turn it into a function: \v -> e
1725 where v::State# RealWorld#. The value passed to this function
1726 is realworld#, which generates (almost) no code.
1728 There's a slight infelicity here: we pass the overall
1729 case_bndr to all the join points if it's used in *any* RHS,
1730 because we don't know its usage in each RHS separately
1732 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1733 we make the join point into a function whenever used_bndrs'
1734 is empty. This makes the join-point more CPR friendly.
1735 Consider: let j = if .. then I# 3 else I# 4
1736 in case .. of { A -> j; B -> j; C -> ... }
1738 Now CPR doesn't w/w j because it's a thunk, so
1739 that means that the enclosing function can't w/w either,
1740 which is a lose. Here's the example that happened in practice:
1741 kgmod :: Int -> Int -> Int
1742 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1746 I have seen a case alternative like this:
1748 It's a bit silly to add the realWorld dummy arg in this case, making
1751 (the \v alone is enough to make CPR happy) but I think it's rare
1753 Note [Duplicating strict continuations]
1754 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1755 Do *not* duplicate StrictBind and StritArg continuations. We gain
1756 nothing by propagating them into the expressions, and we do lose a
1757 lot. Here's an example:
1758 && (case x of { T -> F; F -> T }) E
1759 Now, && is strict so we end up simplifying the case with
1760 an ArgOf continuation. If we let-bind it, we get
1762 let $j = \v -> && v E
1763 in simplExpr (case x of { T -> F; F -> T })
1765 And after simplifying more we get
1767 let $j = \v -> && v E
1768 in case x of { T -> $j F; F -> $j T }
1769 Which is a Very Bad Thing
1771 The desire not to duplicate is the entire reason that
1772 mkDupableCont returns a pair of continuations.
1774 The original plan had:
1775 e.g. (...strict-fn...) [...hole...]
1777 let $j = \a -> ...strict-fn...
1780 Note [Single-alternative cases]
1781 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1782 This case is just like the ArgOf case. Here's an example:
1786 case (case x of I# x' ->
1788 True -> I# (negate# x')
1789 False -> I# x') of y {
1791 Because the (case x) has only one alternative, we'll transform to
1793 case (case x' <# 0# of
1794 True -> I# (negate# x')
1795 False -> I# x') of y {
1797 But now we do *NOT* want to make a join point etc, giving
1799 let $j = \y -> MkT y
1801 True -> $j (I# (negate# x'))
1803 In this case the $j will inline again, but suppose there was a big
1804 strict computation enclosing the orginal call to MkT. Then, it won't
1805 "see" the MkT any more, because it's big and won't get duplicated.
1806 And, what is worse, nothing was gained by the case-of-case transform.
1808 When should use this case of mkDupableCont?
1809 However, matching on *any* single-alternative case is a *disaster*;
1810 e.g. case (case ....) of (a,b) -> (# a,b #)
1811 We must push the outer case into the inner one!
1814 * Match [(DEFAULT,_,_)], but in the common case of Int,
1815 the alternative-filling-in code turned the outer case into
1816 case (...) of y { I# _ -> MkT y }
1818 * Match on single alternative plus (not (isDeadBinder case_bndr))
1819 Rationale: pushing the case inwards won't eliminate the construction.
1820 But there's a risk of
1821 case (...) of y { (a,b) -> let z=(a,b) in ... }
1822 Now y looks dead, but it'll come alive again. Still, this
1823 seems like the best option at the moment.
1825 * Match on single alternative plus (all (isDeadBinder bndrs))
1826 Rationale: this is essentially seq.
1828 * Match when the rhs is *not* duplicable, and hence would lead to a
1829 join point. This catches the disaster-case above. We can test
1830 the *un-simplified* rhs, which is fine. It might get bigger or
1831 smaller after simplification; if it gets smaller, this case might
1832 fire next time round. NB also that we must test contIsDupable
1833 case_cont *btoo, because case_cont might be big!
1835 HOWEVER: I found that this version doesn't work well, because
1836 we can get let x = case (...) of { small } in ...case x...
1837 When x is inlined into its full context, we find that it was a bad
1838 idea to have pushed the outer case inside the (...) case.