2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[Simplify]{The main module of the simplifier}
7 module Simplify ( simplTopBinds, simplExpr ) where
9 #include "HsVersions.h"
13 import Type hiding ( substTy, extendTvSubst, substTyVar )
16 import FamInstEnv ( FamInstEnv )
18 import MkId ( seqId, realWorldPrimId )
19 import MkCore ( mkImpossibleExpr )
22 import Name ( mkSystemVarName, isExternalName )
24 import OptCoercion ( optCoercion )
25 import FamInstEnv ( topNormaliseType )
26 import DataCon ( DataCon, dataConWorkId, dataConRepStrictness )
27 import CoreMonad ( Tick(..), SimplifierMode(..) )
29 import Demand ( isStrictDmd )
30 import PprCore ( pprParendExpr, pprCoreExpr )
33 import qualified CoreSubst
35 import Rules ( lookupRule, getRules )
36 import BasicTypes ( isMarkedStrict, Arity )
37 import CostCentre ( currentCCS, pushCCisNop )
38 import TysPrim ( realWorldStatePrimTy )
39 import BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) )
40 import MonadUtils ( foldlM, mapAccumLM )
41 import Maybes ( orElse, isNothing )
42 import Data.List ( mapAccumL )
48 The guts of the simplifier is in this module, but the driver loop for
49 the simplifier is in SimplCore.lhs.
52 -----------------------------------------
53 *** IMPORTANT NOTE ***
54 -----------------------------------------
55 The simplifier used to guarantee that the output had no shadowing, but
56 it does not do so any more. (Actually, it never did!) The reason is
57 documented with simplifyArgs.
60 -----------------------------------------
61 *** IMPORTANT NOTE ***
62 -----------------------------------------
63 Many parts of the simplifier return a bunch of "floats" as well as an
64 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
66 All "floats" are let-binds, not case-binds, but some non-rec lets may
67 be unlifted (with RHS ok-for-speculation).
71 -----------------------------------------
72 ORGANISATION OF FUNCTIONS
73 -----------------------------------------
75 - simplify all top-level binders
76 - for NonRec, call simplRecOrTopPair
77 - for Rec, call simplRecBind
80 ------------------------------
81 simplExpr (applied lambda) ==> simplNonRecBind
82 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
83 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
85 ------------------------------
86 simplRecBind [binders already simplfied]
87 - use simplRecOrTopPair on each pair in turn
89 simplRecOrTopPair [binder already simplified]
90 Used for: recursive bindings (top level and nested)
91 top-level non-recursive bindings
93 - check for PreInlineUnconditionally
97 Used for: non-top-level non-recursive bindings
98 beta reductions (which amount to the same thing)
99 Because it can deal with strict arts, it takes a
100 "thing-inside" and returns an expression
102 - check for PreInlineUnconditionally
103 - simplify binder, including its IdInfo
112 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
113 Used for: binding case-binder and constr args in a known-constructor case
114 - check for PreInLineUnconditionally
118 ------------------------------
119 simplLazyBind: [binder already simplified, RHS not]
120 Used for: recursive bindings (top level and nested)
121 top-level non-recursive bindings
122 non-top-level, but *lazy* non-recursive bindings
123 [must not be strict or unboxed]
124 Returns floats + an augmented environment, not an expression
125 - substituteIdInfo and add result to in-scope
126 [so that rules are available in rec rhs]
129 - float if exposes constructor or PAP
133 completeNonRecX: [binder and rhs both simplified]
134 - if the the thing needs case binding (unlifted and not ok-for-spec)
140 completeBind: [given a simplified RHS]
141 [used for both rec and non-rec bindings, top level and not]
142 - try PostInlineUnconditionally
143 - add unfolding [this is the only place we add an unfolding]
148 Right hand sides and arguments
149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150 In many ways we want to treat
151 (a) the right hand side of a let(rec), and
152 (b) a function argument
153 in the same way. But not always! In particular, we would
154 like to leave these arguments exactly as they are, so they
155 will match a RULE more easily.
160 It's harder to make the rule match if we ANF-ise the constructor,
161 or eta-expand the PAP:
163 f (let { a = g x; b = h x } in (a,b))
166 On the other hand if we see the let-defns
171 then we *do* want to ANF-ise and eta-expand, so that p and q
172 can be safely inlined.
174 Even floating lets out is a bit dubious. For let RHS's we float lets
175 out if that exposes a value, so that the value can be inlined more vigorously.
178 r = let x = e in (x,x)
180 Here, if we float the let out we'll expose a nice constructor. We did experiments
181 that showed this to be a generally good thing. But it was a bad thing to float
182 lets out unconditionally, because that meant they got allocated more often.
184 For function arguments, there's less reason to expose a constructor (it won't
185 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
186 So for the moment we don't float lets out of function arguments either.
191 For eta expansion, we want to catch things like
193 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
195 If the \x was on the RHS of a let, we'd eta expand to bring the two
196 lambdas together. And in general that's a good thing to do. Perhaps
197 we should eta expand wherever we find a (value) lambda? Then the eta
198 expansion at a let RHS can concentrate solely on the PAP case.
201 %************************************************************************
203 \subsection{Bindings}
205 %************************************************************************
208 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
210 simplTopBinds env0 binds0
211 = do { -- Put all the top-level binders into scope at the start
212 -- so that if a transformation rule has unexpectedly brought
213 -- anything into scope, then we don't get a complaint about that.
214 -- It's rather as if the top-level binders were imported.
215 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
216 ; dflags <- getDOptsSmpl
217 ; let dump_flag = dopt Opt_D_verbose_core2core dflags
218 ; env2 <- simpl_binds dump_flag env1 binds0
219 ; freeTick SimplifierDone
222 -- We need to track the zapped top-level binders, because
223 -- they should have their fragile IdInfo zapped (notably occurrence info)
224 -- That's why we run down binds and bndrs' simultaneously.
226 -- The dump-flag emits a trace for each top-level binding, which
227 -- helps to locate the tracing for inlining and rule firing
228 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
229 simpl_binds _ env [] = return env
230 simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
232 ; simpl_binds dump env' binds }
234 trace_bind True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
235 trace_bind False _ = \x -> x
237 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
238 simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel NonRecursive b b' r
240 (env', b') = addBndrRules env b (lookupRecBndr env b)
244 %************************************************************************
246 \subsection{Lazy bindings}
248 %************************************************************************
250 simplRecBind is used for
251 * recursive bindings only
254 simplRecBind :: SimplEnv -> TopLevelFlag
257 simplRecBind env0 top_lvl pairs0
258 = do { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
259 ; env1 <- go (zapFloats env_with_info) triples
260 ; return (env0 `addRecFloats` env1) }
261 -- addFloats adds the floats from env1,
262 -- _and_ updates env0 with the in-scope set from env1
264 add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
265 -- Add the (substituted) rules to the binder
266 add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
268 (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
270 go env [] = return env
272 go env ((old_bndr, new_bndr, rhs) : pairs)
273 = do { env' <- simplRecOrTopPair env top_lvl Recursive old_bndr new_bndr rhs
277 simplOrTopPair is used for
278 * recursive bindings (whether top level or not)
279 * top-level non-recursive bindings
281 It assumes the binder has already been simplified, but not its IdInfo.
284 simplRecOrTopPair :: SimplEnv
285 -> TopLevelFlag -> RecFlag
286 -> InId -> OutBndr -> InExpr -- Binder and rhs
287 -> SimplM SimplEnv -- Returns an env that includes the binding
289 simplRecOrTopPair env top_lvl is_rec old_bndr new_bndr rhs
290 | preInlineUnconditionally env top_lvl old_bndr rhs -- Check for unconditional inline
291 = do { tick (PreInlineUnconditionally old_bndr)
292 ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
295 = simplLazyBind env top_lvl is_rec old_bndr new_bndr rhs env
299 simplLazyBind is used for
300 * [simplRecOrTopPair] recursive bindings (whether top level or not)
301 * [simplRecOrTopPair] top-level non-recursive bindings
302 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
305 1. It assumes that the binder is *already* simplified,
306 and is in scope, and its IdInfo too, except unfolding
308 2. It assumes that the binder type is lifted.
310 3. It does not check for pre-inline-unconditionallly;
311 that should have been done already.
314 simplLazyBind :: SimplEnv
315 -> TopLevelFlag -> RecFlag
316 -> InId -> OutId -- Binder, both pre-and post simpl
317 -- The OutId has IdInfo, except arity, unfolding
318 -> InExpr -> SimplEnv -- The RHS and its environment
321 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
322 = -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $
323 do { let rhs_env = rhs_se `setInScope` env
324 (tvs, body) = case collectTyBinders rhs of
325 (tvs, body) | not_lam body -> (tvs,body)
326 | otherwise -> ([], rhs)
327 not_lam (Lam _ _) = False
329 -- Do not do the "abstract tyyvar" thing if there's
330 -- a lambda inside, becuase it defeats eta-reduction
331 -- f = /\a. \x. g a x
334 ; (body_env, tvs') <- simplBinders rhs_env tvs
335 -- See Note [Floating and type abstraction] in SimplUtils
338 ; (body_env1, body1) <- simplExprF body_env body mkRhsStop
339 -- ANF-ise a constructor or PAP rhs
340 ; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1
343 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
344 then -- No floating, revert to body1
345 do { rhs' <- mkLam env tvs' (wrapFloats body_env1 body1)
346 ; return (env, rhs') }
348 else if null tvs then -- Simple floating
349 do { tick LetFloatFromLet
350 ; return (addFloats env body_env2, body2) }
352 else -- Do type-abstraction first
353 do { tick LetFloatFromLet
354 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
355 ; rhs' <- mkLam env tvs' body3
356 ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
357 ; return (env', rhs') }
359 ; completeBind env' top_lvl bndr bndr1 rhs' }
362 A specialised variant of simplNonRec used when the RHS is already simplified,
363 notably in knownCon. It uses case-binding where necessary.
366 simplNonRecX :: SimplEnv
367 -> InId -- Old binder
368 -> OutExpr -- Simplified RHS
371 simplNonRecX env bndr new_rhs
372 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
373 = return env -- Here b is dead, and we avoid creating
374 | otherwise -- the binding b = (a,b)
375 = do { (env', bndr') <- simplBinder env bndr
376 ; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs }
377 -- simplNonRecX is only used for NotTopLevel things
379 completeNonRecX :: TopLevelFlag -> SimplEnv
381 -> InId -- Old binder
382 -> OutId -- New binder
383 -> OutExpr -- Simplified RHS
386 completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs
387 = do { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs
389 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
390 then do { tick LetFloatFromLet
391 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
392 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
393 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
396 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
397 Doing so risks exponential behaviour, because new_rhs has been simplified once already
398 In the cases described by the folowing commment, postInlineUnconditionally will
399 catch many of the relevant cases.
400 -- This happens; for example, the case_bndr during case of
401 -- known constructor: case (a,b) of x { (p,q) -> ... }
402 -- Here x isn't mentioned in the RHS, so we don't want to
403 -- create the (dead) let-binding let x = (a,b) in ...
405 -- Similarly, single occurrences can be inlined vigourously
406 -- e.g. case (f x, g y) of (a,b) -> ....
407 -- If a,b occur once we can avoid constructing the let binding for them.
409 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
410 -- Consider case I# (quotInt# x y) of
411 -- I# v -> let w = J# v in ...
412 -- If we gaily inline (quotInt# x y) for v, we end up building an
414 -- let w = J# (quotInt# x y) in ...
415 -- because quotInt# can fail.
417 | preInlineUnconditionally env NotTopLevel bndr new_rhs
418 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
421 ----------------------------------
422 prepareRhs takes a putative RHS, checks whether it's a PAP or
423 constructor application and, if so, converts it to ANF, so that the
424 resulting thing can be inlined more easily. Thus
431 We also want to deal well cases like this
432 v = (f e1 `cast` co) e2
433 Here we want to make e1,e2 trivial and get
434 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
435 That's what the 'go' loop in prepareRhs does
438 prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
439 -- Adds new floats to the env iff that allows us to return a good RHS
440 prepareRhs top_lvl env id (Cast rhs co) -- Note [Float coercions]
441 | (ty1, _ty2) <- coercionKind co -- Do *not* do this if rhs has an unlifted type
442 , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
443 = do { (env', rhs') <- makeTrivialWithInfo top_lvl env sanitised_info rhs
444 ; return (env', Cast rhs' co) }
446 sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
447 `setDemandInfo` demandInfo info
450 prepareRhs top_lvl env0 _ rhs0
451 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
452 ; return (env1, rhs1) }
454 go n_val_args env (Cast rhs co)
455 = do { (is_exp, env', rhs') <- go n_val_args env rhs
456 ; return (is_exp, env', Cast rhs' co) }
457 go n_val_args env (App fun (Type ty))
458 = do { (is_exp, env', rhs') <- go n_val_args env fun
459 ; return (is_exp, env', App rhs' (Type ty)) }
460 go n_val_args env (App fun arg)
461 = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
463 True -> do { (env'', arg') <- makeTrivial top_lvl env' arg
464 ; return (True, env'', App fun' arg') }
465 False -> return (False, env, App fun arg) }
466 go n_val_args env (Var fun)
467 = return (is_exp, env, Var fun)
469 is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
470 -- See Note [CONLIKE pragma] in BasicTypes
471 -- The definition of is_exp should match that in
472 -- OccurAnal.occAnalApp
475 = return (False, env, other)
479 Note [Float coercions]
480 ~~~~~~~~~~~~~~~~~~~~~~
481 When we find the binding
483 we'd like to transform it to
485 x = x `cast` co -- A trivial binding
486 There's a chance that e will be a constructor application or function, or something
487 like that, so moving the coerion to the usage site may well cancel the coersions
488 and lead to further optimisation. Example:
491 data instance T Int = T Int
493 foo :: Int -> Int -> Int
498 go n = case x of { T m -> go (n-m) }
499 -- This case should optimise
501 Note [Preserve strictness when floating coercions]
502 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
503 In the Note [Float coercions] transformation, keep the strictness info.
505 f = e `cast` co -- f has strictness SSL
507 f' = e -- f' also has strictness SSL
508 f = f' `cast` co -- f still has strictness SSL
510 Its not wrong to drop it on the floor, but better to keep it.
512 Note [Float coercions (unlifted)]
513 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
514 BUT don't do [Float coercions] if 'e' has an unlifted type.
517 foo :: Int = (error (# Int,Int #) "urk")
518 `cast` CoUnsafe (# Int,Int #) Int
520 If do the makeTrivial thing to the error call, we'll get
521 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
522 But 'v' isn't in scope!
524 These strange casts can happen as a result of case-of-case
525 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
530 makeTrivial :: TopLevelFlag -> SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
531 -- Binds the expression to a variable, if it's not trivial, returning the variable
532 makeTrivial top_lvl env expr = makeTrivialWithInfo top_lvl env vanillaIdInfo expr
534 makeTrivialWithInfo :: TopLevelFlag -> SimplEnv -> IdInfo
535 -> OutExpr -> SimplM (SimplEnv, OutExpr)
536 -- Propagate strictness and demand info to the new binder
537 -- Note [Preserve strictness when floating coercions]
538 -- Returned SimplEnv has same substitution as incoming one
539 makeTrivialWithInfo top_lvl env info expr
540 | exprIsTrivial expr -- Already trivial
541 || not (bindingOk top_lvl expr expr_ty) -- Cannot trivialise
542 -- See Note [Cannot trivialise]
544 | otherwise -- See Note [Take care] below
545 = do { uniq <- getUniqueM
546 ; let name = mkSystemVarName uniq (fsLit "a")
547 var = mkLocalIdWithInfo name expr_ty info
548 ; env' <- completeNonRecX top_lvl env False var var expr
549 ; expr' <- simplVar env' var
550 ; return (env', expr') }
551 -- The simplVar is needed becase we're constructing a new binding
553 -- And if rhs is of form (rhs1 |> co), then we might get
556 -- and now a's RHS is trivial and can be substituted out, and that
557 -- is what completeNonRecX will do
558 -- To put it another way, it's as if we'd simplified
559 -- let var = e in var
561 expr_ty = exprType expr
563 bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
564 -- True iff we can have a binding of this expression at this level
565 -- Precondition: the type is the type of the expression
566 bindingOk top_lvl _ expr_ty
567 | isTopLevel top_lvl = not (isUnLiftedType expr_ty)
571 Note [Cannot trivialise]
572 ~~~~~~~~~~~~~~~~~~~~~~~~
579 Then we can't ANF-ise foo, even though we'd like to, because
580 we can't make a top-level binding for the Addr# (f 3). And if
581 so we don't want to turn it into
582 foo = let x = f 3 in Bar x
583 because we'll just end up inlining x back, and that makes the
584 simplifier loop. Better not to ANF-ise it at all.
586 A case in point is literal strings (a MachStr is not regarded as
591 We don't want to ANF-ise this.
593 %************************************************************************
595 \subsection{Completing a lazy binding}
597 %************************************************************************
600 * deals only with Ids, not TyVars
601 * takes an already-simplified binder and RHS
602 * is used for both recursive and non-recursive bindings
603 * is used for both top-level and non-top-level bindings
605 It does the following:
606 - tries discarding a dead binding
607 - tries PostInlineUnconditionally
608 - add unfolding [this is the only place we add an unfolding]
611 It does *not* attempt to do let-to-case. Why? Because it is used for
612 - top-level bindings (when let-to-case is impossible)
613 - many situations where the "rhs" is known to be a WHNF
614 (so let-to-case is inappropriate).
616 Nor does it do the atomic-argument thing
619 completeBind :: SimplEnv
620 -> TopLevelFlag -- Flag stuck into unfolding
621 -> InId -- Old binder
622 -> OutId -> OutExpr -- New binder and RHS
624 -- completeBind may choose to do its work
625 -- * by extending the substitution (e.g. let x = y in ...)
626 -- * or by adding to the floats in the envt
628 completeBind env top_lvl old_bndr new_bndr new_rhs
629 = ASSERT( isId new_bndr )
630 do { let old_info = idInfo old_bndr
631 old_unf = unfoldingInfo old_info
632 occ_info = occInfo old_info
634 -- Do eta-expansion on the RHS of the binding
635 -- See Note [Eta-expanding at let bindings] in SimplUtils
636 ; (new_arity, final_rhs) <- tryEtaExpand env new_bndr new_rhs
638 -- Simplify the unfolding
639 ; new_unfolding <- simplUnfolding env top_lvl old_bndr final_rhs old_unf
641 ; if postInlineUnconditionally env top_lvl new_bndr occ_info final_rhs new_unfolding
642 -- Inline and discard the binding
643 then do { tick (PostInlineUnconditionally old_bndr)
644 ; -- pprTrace "postInlineUnconditionally"
645 -- (ppr old_bndr <+> equals <+> ppr final_rhs $$ ppr occ_info) $
646 return (extendIdSubst env old_bndr (DoneEx final_rhs)) }
647 -- Use the substitution to make quite, quite sure that the
648 -- substitution will happen, since we are going to discard the binding
650 do { let info1 = idInfo new_bndr `setArityInfo` new_arity
652 -- Unfolding info: Note [Setting the new unfolding]
653 info2 = info1 `setUnfoldingInfo` new_unfolding
655 -- Demand info: Note [Setting the demand info]
656 info3 | isEvaldUnfolding new_unfolding = zapDemandInfo info2 `orElse` info2
659 final_id = new_bndr `setIdInfo` info3
661 ; -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
662 return (addNonRec env final_id final_rhs) } }
663 -- The addNonRec adds it to the in-scope set too
665 ------------------------------
666 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
667 -- Add a new binding to the environment, complete with its unfolding
668 -- but *do not* do postInlineUnconditionally, because we have already
669 -- processed some of the scope of the binding
670 -- We still want the unfolding though. Consider
672 -- x = /\a. let y = ... in Just y
674 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
675 -- but 'x' may well then be inlined in 'body' in which case we'd like the
676 -- opportunity to inline 'y' too.
678 addPolyBind top_lvl env (NonRec poly_id rhs)
679 = do { unfolding <- simplUnfolding env top_lvl poly_id rhs noUnfolding
680 -- Assumes that poly_id did not have an INLINE prag
681 -- which is perhaps wrong. ToDo: think about this
682 ; let final_id = setIdInfo poly_id $
683 idInfo poly_id `setUnfoldingInfo` unfolding
684 `setArityInfo` exprArity rhs
686 ; return (addNonRec env final_id rhs) }
688 addPolyBind _ env bind@(Rec _)
689 = return (extendFloats env bind)
690 -- Hack: letrecs are more awkward, so we extend "by steam"
691 -- without adding unfoldings etc. At worst this leads to
692 -- more simplifier iterations
694 ------------------------------
695 simplUnfolding :: SimplEnv-> TopLevelFlag
698 -> Unfolding -> SimplM Unfolding
699 -- Note [Setting the new unfolding]
700 simplUnfolding env _ _ _ (DFunUnfolding ar con ops)
701 = return (DFunUnfolding ar con ops')
703 ops' = map (fmap (substExpr (text "simplUnfolding") env)) ops
705 simplUnfolding env top_lvl id _
706 (CoreUnfolding { uf_tmpl = expr, uf_arity = arity
707 , uf_src = src, uf_guidance = guide })
709 = do { expr' <- simplExpr rule_env expr
710 ; let src' = CoreSubst.substUnfoldingSource (mkCoreSubst (text "inline-unf") env) src
711 is_top_lvl = isTopLevel top_lvl
713 UnfWhen sat_ok _ -- Happens for INLINE things
714 -> let guide' = UnfWhen sat_ok (inlineBoringOk expr')
715 -- Refresh the boring-ok flag, in case expr'
716 -- has got small. This happens, notably in the inlinings
717 -- for dfuns for single-method classes; see
718 -- Note [Single-method classes] in TcInstDcls.
719 -- A test case is Trac #4138
720 in return (mkCoreUnfolding src' is_top_lvl expr' arity guide')
721 -- See Note [Top-level flag on inline rules] in CoreUnfold
723 _other -- Happens for INLINABLE things
724 -> let bottoming = isBottomingId id
725 in bottoming `seq` -- See Note [Force bottoming field]
726 return (mkUnfolding src' is_top_lvl bottoming expr')
727 -- If the guidance is UnfIfGoodArgs, this is an INLINABLE
728 -- unfolding, and we need to make sure the guidance is kept up
729 -- to date with respect to any changes in the unfolding.
732 act = idInlineActivation id
733 rule_env = updMode (updModeForInlineRules act) env
734 -- See Note [Simplifying inside InlineRules] in SimplUtils
736 simplUnfolding _ top_lvl id new_rhs _
737 = let bottoming = isBottomingId id
738 in bottoming `seq` -- See Note [Force bottoming field]
739 return (mkUnfolding InlineRhs (isTopLevel top_lvl) bottoming new_rhs)
740 -- We make an unfolding *even for loop-breakers*.
741 -- Reason: (a) It might be useful to know that they are WHNF
742 -- (b) In TidyPgm we currently assume that, if we want to
743 -- expose the unfolding then indeed we *have* an unfolding
744 -- to expose. (We could instead use the RHS, but currently
745 -- we don't.) The simple thing is always to have one.
748 Note [Force bottoming field]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 We need to force bottoming, or the new unfolding holds
751 on to the old unfolding (which is part of the id).
753 Note [Arity decrease]
754 ~~~~~~~~~~~~~~~~~~~~~
755 Generally speaking the arity of a binding should not decrease. But it *can*
756 legitimately happen becuase of RULES. Eg
758 where g has arity 2, will have arity 2. But if there's a rewrite rule
760 where h has arity 1, then f's arity will decrease. Here's a real-life example,
761 which is in the output of Specialise:
764 $dm {Arity 2} = \d.\x. op d
765 {-# RULES forall d. $dm Int d = $s$dm #-}
767 dInt = MkD .... opInt ...
768 opInt {Arity 1} = $dm dInt
770 $s$dm {Arity 0} = \x. op dInt }
772 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
773 That's why Specialise goes to a little trouble to pin the right arity
774 on specialised functions too.
776 Note [Setting the new unfolding]
777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
778 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
779 should do nothing at all, but simplifying gently might get rid of
782 * If not, we make an unfolding from the new RHS. But *only* for
783 non-loop-breakers. Making loop breakers not have an unfolding at all
784 means that we can avoid tests in exprIsConApp, for example. This is
785 important: if exprIsConApp says 'yes' for a recursive thing, then we
786 can get into an infinite loop
788 If there's an InlineRule on a loop breaker, we hang on to the inlining.
789 It's pretty dodgy, but the user did say 'INLINE'. May need to revisit
792 Note [Setting the demand info]
793 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
794 If the unfolding is a value, the demand info may
795 go pear-shaped, so we nuke it. Example:
797 case x of (p,q) -> h p q x
798 Here x is certainly demanded. But after we've nuked
799 the case, we'll get just
800 let x = (a,b) in h a b x
801 and now x is not demanded (I'm assuming h is lazy)
802 This really happens. Similarly
803 let f = \x -> e in ...f..f...
804 After inlining f at some of its call sites the original binding may
805 (for example) be no longer strictly demanded.
806 The solution here is a bit ad hoc...
809 %************************************************************************
811 \subsection[Simplify-simplExpr]{The main function: simplExpr}
813 %************************************************************************
815 The reason for this OutExprStuff stuff is that we want to float *after*
816 simplifying a RHS, not before. If we do so naively we get quadratic
817 behaviour as things float out.
819 To see why it's important to do it after, consider this (real) example:
833 a -- Can't inline a this round, cos it appears twice
837 Each of the ==> steps is a round of simplification. We'd save a
838 whole round if we float first. This can cascade. Consider
843 let f = let d1 = ..d.. in \y -> e
847 in \x -> ...(\y ->e)...
849 Only in this second round can the \y be applied, and it
850 might do the same again.
854 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
855 simplExpr env expr = simplExprC env expr mkBoringStop
857 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
858 -- Simplify an expression, given a continuation
859 simplExprC env expr cont
860 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
861 do { (env', expr') <- simplExprF (zapFloats env) expr cont
862 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
863 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
864 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
865 return (wrapFloats env' expr') }
867 --------------------------------------------------
868 simplExprF :: SimplEnv -> InExpr -> SimplCont
869 -> SimplM (SimplEnv, OutExpr)
871 simplExprF env e cont
872 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
873 simplExprF' env e cont
875 simplExprF' :: SimplEnv -> InExpr -> SimplCont
876 -> SimplM (SimplEnv, OutExpr)
877 simplExprF' env (Var v) cont = simplVarF env v cont
878 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
879 simplExprF' env (Note n expr) cont = simplNote env n expr cont
880 simplExprF' env (Cast body co) cont = simplCast env body co cont
881 simplExprF' env (App fun arg) cont = simplExprF env fun $
882 ApplyTo NoDup arg env cont
884 simplExprF' env expr@(Lam _ _) cont
885 = simplLam env zapped_bndrs body cont
886 -- The main issue here is under-saturated lambdas
887 -- (\x1. \x2. e) arg1
888 -- Here x1 might have "occurs-once" occ-info, because occ-info
889 -- is computed assuming that a group of lambdas is applied
890 -- all at once. If there are too few args, we must zap the
891 -- occ-info, UNLESS the remaining binders are one-shot
893 (bndrs, body) = collectBinders expr
894 zapped_bndrs | need_to_zap = map zap bndrs
897 need_to_zap = any zappable_bndr (drop n_args bndrs)
898 n_args = countArgs cont
899 -- NB: countArgs counts all the args (incl type args)
900 -- and likewise drop counts all binders (incl type lambdas)
902 zappable_bndr b = isId b && not (isOneShotBndr b)
903 zap b | isTyCoVar b = b
904 | otherwise = zapLamIdInfo b
906 simplExprF' env (Type ty) cont
907 = ASSERT( contIsRhsOrArg cont )
908 do { ty' <- simplCoercion env ty
909 ; rebuild env (Type ty') cont }
911 simplExprF' env (Case scrut bndr _ alts) cont
912 | sm_case_case (getMode env)
913 = -- Simplify the scrutinee with a Select continuation
914 simplExprF env scrut (Select NoDup bndr alts env cont)
917 = -- If case-of-case is off, simply simplify the case expression
918 -- in a vanilla Stop context, and rebuild the result around it
919 do { case_expr' <- simplExprC env scrut
920 (Select NoDup bndr alts env mkBoringStop)
921 ; rebuild env case_expr' cont }
923 simplExprF' env (Let (Rec pairs) body) cont
924 = do { env' <- simplRecBndrs env (map fst pairs)
925 -- NB: bndrs' don't have unfoldings or rules
926 -- We add them as we go down
928 ; env'' <- simplRecBind env' NotTopLevel pairs
929 ; simplExprF env'' body cont }
931 simplExprF' env (Let (NonRec bndr rhs) body) cont
932 = simplNonRecE env bndr (rhs, env) ([], body) cont
934 ---------------------------------
935 simplType :: SimplEnv -> InType -> SimplM OutType
936 -- Kept monadic just so we can do the seqType
938 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
939 seqType new_ty `seq` return new_ty
941 new_ty = substTy env ty
943 ---------------------------------
944 simplCoercion :: SimplEnv -> InType -> SimplM OutType
945 -- The InType isn't *necessarily* a coercion, but it might be
946 -- (in a type application, say) and optCoercion is a no-op on types
948 = seqType new_co `seq` return new_co
950 new_co = optCoercion (getTvSubst env) co
954 %************************************************************************
956 \subsection{The main rebuilder}
958 %************************************************************************
961 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
962 -- At this point the substitution in the SimplEnv should be irrelevant
963 -- only the in-scope set and floats should matter
964 rebuild env expr cont
966 Stop {} -> return (env, expr)
967 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
968 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
969 StrictArg info _ cont -> rebuildCall env (info `addArgTo` expr) cont
970 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
971 ; simplLam env' bs body cont }
972 ApplyTo dup_flag arg se cont -- See Note [Avoid redundant simplification]
973 | isSimplified dup_flag -> rebuild env (App expr arg) cont
974 | otherwise -> do { arg' <- simplExpr (se `setInScope` env) arg
975 ; rebuild env (App expr arg') cont }
979 %************************************************************************
983 %************************************************************************
986 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
987 -> SimplM (SimplEnv, OutExpr)
988 simplCast env body co0 cont0
989 = do { co1 <- simplCoercion env co0
990 ; simplExprF env body (addCoerce co1 cont0) }
992 addCoerce co cont = add_coerce co (coercionKind co) cont
994 add_coerce _co (s1, k1) cont -- co :: ty~ty
995 | s1 `coreEqType` k1 = cont -- is a no-op
997 add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
998 | (_l1, t1) <- coercionKind co2
999 -- e |> (g1 :: S1~L) |> (g2 :: L~T1)
1002 -- e |> (g1 . g2 :: S1~T1) otherwise
1004 -- For example, in the initial form of a worker
1005 -- we may find (coerce T (coerce S (\x.e))) y
1006 -- and we'd like it to simplify to e[y/x] in one round
1007 -- of simplification
1008 , s1 `coreEqType` t1 = cont -- The coerces cancel out
1009 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
1011 add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
1012 -- (f |> g) ty ---> (f ty) |> (g @ ty)
1013 -- This implements the PushT and PushC rules from the paper
1014 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
1016 (new_arg_ty, new_cast)
1017 | isCoVar tyvar = (new_arg_co, mkCselRCoercion co) -- PushC rule
1018 | otherwise = (ty', mkInstCoercion co ty') -- PushT rule
1020 ApplyTo dup (Type new_arg_ty) (zapSubstEnv arg_se) (addCoerce new_cast cont)
1022 ty' = substTy (arg_se `setInScope` env) arg_ty
1023 new_arg_co = mkCsel1Coercion co `mkTransCoercion`
1024 ty' `mkTransCoercion`
1025 mkSymCoercion (mkCsel2Coercion co)
1027 add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
1028 | not (isTypeArg arg) -- This implements the Push rule from the paper
1029 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
1030 -- (e |> (g :: s1s2 ~ t1->t2)) f
1032 -- (e (f |> (arg g :: t1~s1))
1033 -- |> (res g :: s2->t2)
1035 -- t1t2 must be a function type, t1->t2, because it's applied
1036 -- to something but s1s2 might conceivably not be
1038 -- When we build the ApplyTo we can't mix the out-types
1039 -- with the InExpr in the argument, so we simply substitute
1040 -- to make it all consistent. It's a bit messy.
1041 -- But it isn't a common case.
1043 -- Example of use: Trac #995
1044 = ApplyTo dup new_arg (zapSubstEnv arg_se) (addCoerce co2 cont)
1046 -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
1047 -- t2 ~ s2 with left and right on the curried form:
1048 -- (->) t1 t2 ~ (->) s1 s2
1049 [co1, co2] = decomposeCo 2 co
1050 new_arg = mkCoerce (mkSymCoercion co1) arg'
1051 arg' = substExpr (text "move-cast") (arg_se `setInScope` env) arg
1053 add_coerce co _ cont = CoerceIt co cont
1057 %************************************************************************
1059 \subsection{Lambdas}
1061 %************************************************************************
1063 Note [Zap unfolding when beta-reducing]
1064 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1065 Lambda-bound variables can have stable unfoldings, such as
1066 $j = \x. \b{Unf=Just x}. e
1067 See Note [Case binders and join points] below; the unfolding for lets
1068 us optimise e better. However when we beta-reduce it we want to
1069 revert to using the actual value, otherwise we can end up in the
1072 let b{Unf=Just x} = y
1074 Here it'd be far better to drop the unfolding and use the actual RHS.
1077 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1078 -> SimplM (SimplEnv, OutExpr)
1080 simplLam env [] body cont = simplExprF env body cont
1083 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
1084 = do { tick (BetaReduction bndr)
1085 ; simplNonRecE env (zap_unfolding bndr) (arg, arg_se) (bndrs, body) cont }
1087 zap_unfolding bndr -- See Note [Zap unfolding when beta-reducing]
1088 | isId bndr, isStableUnfolding (realIdUnfolding bndr)
1089 = setIdUnfolding bndr NoUnfolding
1092 -- Not enough args, so there are real lambdas left to put in the result
1093 simplLam env bndrs body cont
1094 = do { (env', bndrs') <- simplLamBndrs env bndrs
1095 ; body' <- simplExpr env' body
1096 ; new_lam <- mkLam env' bndrs' body'
1097 ; rebuild env' new_lam cont }
1100 simplNonRecE :: SimplEnv
1101 -> InBndr -- The binder
1102 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1103 -> ([InBndr], InExpr) -- Body of the let/lambda
1106 -> SimplM (SimplEnv, OutExpr)
1108 -- simplNonRecE is used for
1109 -- * non-top-level non-recursive lets in expressions
1112 -- It deals with strict bindings, via the StrictBind continuation,
1113 -- which may abort the whole process
1115 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1116 -- representing a lambda; so we recurse back to simplLam
1117 -- Why? Because of the binder-occ-info-zapping done before
1118 -- the call to simplLam in simplExprF (Lam ...)
1120 -- First deal with type applications and type lets
1121 -- (/\a. e) (Type ty) and (let a = Type ty in e)
1122 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1123 = ASSERT( isTyCoVar bndr )
1124 do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1125 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1127 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1128 | preInlineUnconditionally env NotTopLevel bndr rhs
1129 = do { tick (PreInlineUnconditionally bndr)
1130 ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
1131 simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1134 = do { simplExprF (rhs_se `setFloats` env) rhs
1135 (StrictBind bndr bndrs body env cont) }
1138 = ASSERT( not (isTyCoVar bndr) )
1139 do { (env1, bndr1) <- simplNonRecBndr env bndr
1140 ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
1141 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1142 ; simplLam env3 bndrs body cont }
1146 %************************************************************************
1150 %************************************************************************
1153 -- Hack alert: we only distinguish subsumed cost centre stacks for the
1154 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
1155 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
1156 -> SimplM (SimplEnv, OutExpr)
1157 simplNote env (SCC cc) e cont
1158 | pushCCisNop cc (getEnclosingCC env) -- scc "f" (...(scc "f" e)...)
1159 = simplExprF env e cont -- ==> scc "f" (...e...)
1161 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
1162 ; rebuild env (mkSCC cc e') cont }
1164 simplNote env (CoreNote s) e cont
1165 = do { e' <- simplExpr env e
1166 ; rebuild env (Note (CoreNote s) e') cont }
1170 %************************************************************************
1174 %************************************************************************
1177 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1178 -- Look up an InVar in the environment
1181 = return (Type (substTyVar env var))
1183 = case substId env var of
1184 DoneId var1 -> return (Var var1)
1185 DoneEx e -> return e
1186 ContEx tvs ids e -> simplExpr (setSubstEnv env tvs ids) e
1188 simplVarF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1189 simplVarF env var cont
1190 = case substId env var of
1191 DoneEx e -> simplExprF (zapSubstEnv env) e cont
1192 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1193 DoneId var1 -> completeCall env var1 cont
1194 -- Note [zapSubstEnv]
1195 -- The template is already simplified, so don't re-substitute.
1196 -- This is VITAL. Consider
1198 -- let y = \z -> ...x... in
1200 -- We'll clone the inner \x, adding x->x' in the id_subst
1201 -- Then when we inline y, we must *not* replace x by x' in
1202 -- the inlined copy!!
1204 ---------------------------------------------------------
1205 -- Dealing with a call site
1207 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1208 completeCall env var cont
1209 = do { ------------- Try inlining ----------------
1210 dflags <- getDOptsSmpl
1211 ; let (lone_variable, arg_infos, call_cont) = contArgs cont
1212 -- The args are OutExprs, obtained by *lazily* substituting
1213 -- in the args found in cont. These args are only examined
1214 -- to limited depth (unless a rule fires). But we must do
1215 -- the substitution; rule matching on un-simplified args would
1218 n_val_args = length arg_infos
1219 interesting_cont = interestingCallContext call_cont
1220 unfolding = activeUnfolding env var
1221 maybe_inline = callSiteInline dflags var unfolding
1222 lone_variable arg_infos interesting_cont
1223 ; case maybe_inline of {
1224 Just expr -- There is an inlining!
1225 -> do { tick (UnfoldingDone var)
1226 ; trace_inline dflags expr cont $
1227 simplExprF (zapSubstEnv env) expr cont }
1229 ; Nothing -> do -- No inlining!
1231 { rule_base <- getSimplRules
1232 ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
1233 ; rebuildCall env info cont
1236 trace_inline dflags unfolding cont stuff
1237 | not (dopt Opt_D_dump_inlinings dflags) = stuff
1238 | not (dopt Opt_D_verbose_core2core dflags)
1239 = if isExternalName (idName var) then
1240 pprTrace "Inlining done:" (ppr var) stuff
1243 = pprTrace ("Inlining done: " ++ showSDoc (ppr var))
1244 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1245 text "Cont: " <+> ppr cont])
1248 rebuildCall :: SimplEnv
1251 -> SimplM (SimplEnv, OutExpr)
1252 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1253 -- When we run out of strictness args, it means
1254 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1255 -- Then we want to discard the entire strict continuation. E.g.
1256 -- * case (error "hello") of { ... }
1257 -- * (error "Hello") arg
1258 -- * f (error "Hello") where f is strict
1260 -- Then, especially in the first of these cases, we'd like to discard
1261 -- the continuation, leaving just the bottoming expression. But the
1262 -- type might not be right, so we may have to add a coerce.
1263 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1264 = return (env, mk_coerce res) -- contination to discard, else we do it
1265 where -- again and again!
1266 res = mkApps (Var fun) (reverse rev_args)
1267 res_ty = exprType res
1268 cont_ty = contResultType env res_ty cont
1269 co = mkUnsafeCoercion res_ty cont_ty
1270 mk_coerce expr | cont_ty `coreEqType` res_ty = expr
1271 | otherwise = mkCoerce co expr
1273 rebuildCall env info (ApplyTo _ (Type arg_ty) se cont)
1274 = do { ty' <- simplCoercion (se `setInScope` env) arg_ty
1275 ; rebuildCall env (info `addArgTo` Type ty') cont }
1277 rebuildCall env info@(ArgInfo { ai_encl = encl_rules
1278 , ai_strs = str:strs, ai_discs = disc:discs })
1279 (ApplyTo dup_flag arg arg_se cont)
1280 | isSimplified dup_flag -- See Note [Avoid redundant simplification]
1281 = rebuildCall env (addArgTo info' arg) cont
1283 | str -- Strict argument
1284 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1285 simplExprF (arg_se `setFloats` env) arg
1286 (StrictArg info' cci cont)
1289 | otherwise -- Lazy argument
1290 -- DO NOT float anything outside, hence simplExprC
1291 -- There is no benefit (unlike in a let-binding), and we'd
1292 -- have to be very careful about bogus strictness through
1293 -- floating a demanded let.
1294 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1296 ; rebuildCall env (addArgTo info' arg') cont }
1298 info' = info { ai_strs = strs, ai_discs = discs }
1299 cci | encl_rules || disc > 0 = ArgCtxt encl_rules -- Be keener here
1300 | otherwise = BoringCtxt -- Nothing interesting
1302 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
1303 = do { -- We've accumulated a simplified call in <fun,rev_args>
1304 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1305 -- See also Note [Rules for recursive functions]
1306 ; let args = reverse rev_args
1307 env' = zapSubstEnv env
1308 ; mb_rule <- tryRules env rules fun args cont
1310 Just (n_args, rule_rhs) -> simplExprF env' rule_rhs $
1311 pushSimplifiedArgs env' (drop n_args args) cont ;
1312 -- n_args says how many args the rule consumed
1313 ; Nothing -> rebuild env (mkApps (Var fun) args) cont -- No rules
1317 Note [RULES apply to simplified arguments]
1318 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1319 It's very desirable to try RULES once the arguments have been simplified, because
1320 doing so ensures that rule cascades work in one pass. Consider
1321 {-# RULES g (h x) = k x
1324 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1325 we match f's rules against the un-simplified RHS, it won't match. This
1326 makes a particularly big difference when superclass selectors are involved:
1327 op ($p1 ($p2 (df d)))
1328 We want all this to unravel in one sweeep.
1330 Note [Avoid redundant simplification]
1331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1332 Because RULES apply to simplified arguments, there's a danger of repeatedly
1333 simplifying already-simplified arguments. An important example is that of
1335 Here e1, e2 are simplified before the rule is applied, but don't really
1336 participate in the rule firing. So we mark them as Simplified to avoid
1337 re-simplifying them.
1341 This part of the simplifier may break the no-shadowing invariant
1343 f (...(\a -> e)...) (case y of (a,b) -> e')
1344 where f is strict in its second arg
1345 If we simplify the innermost one first we get (...(\a -> e)...)
1346 Simplifying the second arg makes us float the case out, so we end up with
1347 case y of (a,b) -> f (...(\a -> e)...) e'
1348 So the output does not have the no-shadowing invariant. However, there is
1349 no danger of getting name-capture, because when the first arg was simplified
1350 we used an in-scope set that at least mentioned all the variables free in its
1351 static environment, and that is enough.
1353 We can't just do innermost first, or we'd end up with a dual problem:
1354 case x of (a,b) -> f e (...(\a -> e')...)
1356 I spent hours trying to recover the no-shadowing invariant, but I just could
1357 not think of an elegant way to do it. The simplifier is already knee-deep in
1358 continuations. We have to keep the right in-scope set around; AND we have
1359 to get the effect that finding (error "foo") in a strict arg position will
1360 discard the entire application and replace it with (error "foo"). Getting
1361 all this at once is TOO HARD!
1364 %************************************************************************
1368 %************************************************************************
1371 tryRules :: SimplEnv -> [CoreRule]
1372 -> Id -> [OutExpr] -> SimplCont
1373 -> SimplM (Maybe (Arity, CoreExpr)) -- The arity is the number of
1374 -- args consumed by the rule
1375 tryRules env rules fn args call_cont
1379 = do { dflags <- getDOptsSmpl
1380 ; case activeRule dflags env of {
1381 Nothing -> return Nothing ; -- No rules apply
1383 case lookupRule act_fn (getUnfoldingInRuleMatch env) (getInScope env) fn args rules of {
1384 Nothing -> return Nothing ; -- No rule matches
1385 Just (rule, rule_rhs) ->
1387 do { tick (RuleFired (ru_name rule))
1388 ; trace_dump dflags rule rule_rhs $
1389 return (Just (ruleArity rule, rule_rhs)) }}}}
1391 trace_dump dflags rule rule_rhs stuff
1392 | not (dopt Opt_D_dump_rule_firings dflags)
1393 , not (dopt Opt_D_dump_rule_rewrites dflags) = stuff
1394 | not (dopt Opt_D_dump_rule_rewrites dflags)
1396 = pprTrace "Rule fired:" (ftext (ru_name rule)) stuff
1398 = pprTrace "Rule fired"
1399 (vcat [text "Rule:" <+> ftext (ru_name rule),
1400 text "Before:" <+> hang (ppr fn) 2 (sep (map pprParendExpr args)),
1401 text "After: " <+> pprCoreExpr rule_rhs,
1402 text "Cont: " <+> ppr call_cont])
1406 Note [Rules for recursive functions]
1407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1408 You might think that we shouldn't apply rules for a loop breaker:
1409 doing so might give rise to an infinite loop, because a RULE is
1410 rather like an extra equation for the function:
1411 RULE: f (g x) y = x+y
1414 But it's too drastic to disable rules for loop breakers.
1415 Even the foldr/build rule would be disabled, because foldr
1416 is recursive, and hence a loop breaker:
1417 foldr k z (build g) = g k z
1418 So it's up to the programmer: rules can cause divergence
1421 %************************************************************************
1423 Rebuilding a case expression
1425 %************************************************************************
1427 Note [Case elimination]
1428 ~~~~~~~~~~~~~~~~~~~~~~~
1429 The case-elimination transformation discards redundant case expressions.
1430 Start with a simple situation:
1432 case x# of ===> let y# = x# in e
1435 (when x#, y# are of primitive type, of course). We can't (in general)
1436 do this for algebraic cases, because we might turn bottom into
1439 The code in SimplUtils.prepareAlts has the effect of generalise this
1440 idea to look for a case where we're scrutinising a variable, and we
1441 know that only the default case can match. For example:
1445 DEFAULT -> ...(case x of
1449 Here the inner case is first trimmed to have only one alternative, the
1450 DEFAULT, after which it's an instance of the previous case. This
1451 really only shows up in eliminating error-checking code.
1453 Note that SimplUtils.mkCase combines identical RHSs. So
1455 case e of ===> case e of DEFAULT -> r
1459 Now again the case may be elminated by the CaseElim transformation.
1460 This includes things like (==# a# b#)::Bool so that we simplify
1461 case ==# a# b# of { True -> x; False -> x }
1464 This particular example shows up in default methods for
1465 comparision operations (e.g. in (>=) for Int.Int32)
1467 Note [CaseElimination: lifted case]
1468 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1469 We also make sure that we deal with this very common case,
1470 where x has a lifted type:
1475 Here we are using the case as a strict let; if x is used only once
1476 then we want to inline it. We have to be careful that this doesn't
1477 make the program terminate when it would have diverged before, so we
1479 (a) 'e' is already evaluated (it may so if e is a variable)
1480 Specifically we check (exprIsHNF e)
1482 (b) the scrutinee is a variable and 'x' is used strictly
1484 (c) 'x' is not used at all and e is ok-for-speculation
1486 For the (c), consider
1487 case (case a ># b of { True -> (p,q); False -> (q,p) }) of
1489 The scrutinee is ok-for-speculation (it looks inside cases), but we do
1490 not want to transform to
1491 let r = case a ># b of { True -> (p,q); False -> (q,p) }
1493 because that builds an unnecessary thunk.
1496 Further notes about case elimination
1497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1498 Consider: test :: Integer -> IO ()
1501 Turns out that this compiles to:
1504 eta1 :: State# RealWorld ->
1505 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1507 (PrelNum.jtos eta ($w[] @ Char))
1509 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1511 Notice the strange '<' which has no effect at all. This is a funny one.
1512 It started like this:
1514 f x y = if x < 0 then jtos x
1515 else if y==0 then "" else jtos x
1517 At a particular call site we have (f v 1). So we inline to get
1519 if v < 0 then jtos x
1520 else if 1==0 then "" else jtos x
1522 Now simplify the 1==0 conditional:
1524 if v<0 then jtos v else jtos v
1526 Now common-up the two branches of the case:
1528 case (v<0) of DEFAULT -> jtos v
1530 Why don't we drop the case? Because it's strict in v. It's technically
1531 wrong to drop even unnecessary evaluations, and in practice they
1532 may be a result of 'seq' so we *definitely* don't want to drop those.
1533 I don't really know how to improve this situation.
1536 ---------------------------------------------------------
1537 -- Eliminate the case if possible
1539 rebuildCase, reallyRebuildCase
1541 -> OutExpr -- Scrutinee
1542 -> InId -- Case binder
1543 -> [InAlt] -- Alternatives (inceasing order)
1545 -> SimplM (SimplEnv, OutExpr)
1547 --------------------------------------------------
1548 -- 1. Eliminate the case if there's a known constructor
1549 --------------------------------------------------
1551 rebuildCase env scrut case_bndr alts cont
1552 | Lit lit <- scrut -- No need for same treatment as constructors
1553 -- because literals are inlined more vigorously
1554 = do { tick (KnownBranch case_bndr)
1555 ; case findAlt (LitAlt lit) alts of
1556 Nothing -> missingAlt env case_bndr alts cont
1557 Just (_, bs, rhs) -> simple_rhs bs rhs }
1559 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
1560 -- Works when the scrutinee is a variable with a known unfolding
1561 -- as well as when it's an explicit constructor application
1562 = do { tick (KnownBranch case_bndr)
1563 ; case findAlt (DataAlt con) alts of
1564 Nothing -> missingAlt env case_bndr alts cont
1565 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1566 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
1567 case_bndr bs rhs cont
1570 simple_rhs bs rhs = ASSERT( null bs )
1571 do { env' <- simplNonRecX env case_bndr scrut
1572 ; simplExprF env' rhs cont }
1575 --------------------------------------------------
1576 -- 2. Eliminate the case if scrutinee is evaluated
1577 --------------------------------------------------
1579 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1580 -- See if we can get rid of the case altogether
1581 -- See Note [Case elimination]
1582 -- mkCase made sure that if all the alternatives are equal,
1583 -- then there is now only one (DEFAULT) rhs
1584 | all isDeadBinder bndrs -- bndrs are [InId]
1586 , if isUnLiftedType (idType case_bndr)
1587 then ok_for_spec -- Satisfy the let-binding invariant
1589 = do { tick (CaseElim case_bndr)
1590 ; env' <- simplNonRecX env case_bndr scrut
1591 -- If case_bndr is deads, simplNonRecX will discard
1592 ; simplExprF env' rhs cont }
1594 elim_lifted -- See Note [Case elimination: lifted case]
1596 || (strict_case_bndr && scrut_is_var scrut)
1597 -- The case binder is going to be evaluated later,
1598 -- and the scrutinee is a simple variable
1600 || (is_plain_seq && ok_for_spec)
1601 -- Note: not the same as exprIsHNF
1603 ok_for_spec = exprOkForSpeculation scrut
1604 is_plain_seq = isDeadBinder case_bndr -- Evaluation *only* for effect
1605 strict_case_bndr = isStrictDmd (idDemandInfo case_bndr)
1607 scrut_is_var (Cast s _) = scrut_is_var s
1608 scrut_is_var (Var v) = not (isTickBoxOp v)
1609 -- ugly hack; covering this case is what
1610 -- exprOkForSpeculation was intended for.
1611 scrut_is_var _ = False
1614 --------------------------------------------------
1615 -- 3. Try seq rules; see Note [User-defined RULES for seq] in MkId
1616 --------------------------------------------------
1618 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1619 | all isDeadBinder (case_bndr : bndrs) -- So this is just 'seq'
1620 = do { let rhs' = substExpr (text "rebuild-case") env rhs
1621 out_args = [Type (substTy env (idType case_bndr)),
1622 Type (exprType rhs'), scrut, rhs']
1623 -- Lazily evaluated, so we don't do most of this
1625 ; rule_base <- getSimplRules
1626 ; mb_rule <- tryRules env (getRules rule_base seqId) seqId out_args cont
1628 Just (n_args, res) -> simplExprF (zapSubstEnv env)
1629 (mkApps res (drop n_args out_args))
1631 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1633 rebuildCase env scrut case_bndr alts cont
1634 = reallyRebuildCase env scrut case_bndr alts cont
1636 --------------------------------------------------
1637 -- 3. Catch-all case
1638 --------------------------------------------------
1640 reallyRebuildCase env scrut case_bndr alts cont
1641 = do { -- Prepare the continuation;
1642 -- The new subst_env is in place
1643 (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1645 -- Simplify the alternatives
1646 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1648 -- Check for empty alternatives
1649 ; if null alts' then missingAlt env case_bndr alts cont
1651 { dflags <- getDOptsSmpl
1652 ; case_expr <- mkCase dflags scrut' case_bndr' alts'
1654 -- Notice that rebuild gets the in-scope set from env', not alt_env
1655 -- (which in any case is only build in simplAlts)
1656 -- The case binder *not* scope over the whole returned case-expression
1657 ; rebuild env' case_expr nodup_cont } }
1660 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1661 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1662 way, there's a chance that v will now only be used once, and hence
1665 Historical note: we use to do the "case binder swap" in the Simplifier
1666 so there were additional complications if the scrutinee was a variable.
1667 Now the binder-swap stuff is done in the occurrence analyer; see
1668 OccurAnal Note [Binder swap].
1672 If the case binder is not dead, then neither are the pattern bound
1674 case <any> of x { (a,b) ->
1675 case x of { (p,q) -> p } }
1676 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1677 The point is that we bring into the envt a binding
1679 after the outer case, and that makes (a,b) alive. At least we do unless
1680 the case binder is guaranteed dead.
1682 In practice, the scrutinee is almost always a variable, so we pretty
1683 much always zap the OccInfo of the binders. It doesn't matter much though.
1685 Note [Improving seq]
1688 type family F :: * -> *
1689 type instance F Int = Int
1691 ... case e of x { DEFAULT -> rhs } ...
1693 where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
1695 case e `cast` co of x'::Int
1696 I# x# -> let x = x' `cast` sym co
1699 so that 'rhs' can take advantage of the form of x'.
1701 Notice that Note [Case of cast] (in OccurAnal) may then apply to the result.
1703 Nota Bene: We only do the [Improving seq] transformation if the
1704 case binder 'x' is actually used in the rhs; that is, if the case
1705 is *not* a *pure* seq.
1706 a) There is no point in adding the cast to a pure seq.
1707 b) There is a good reason not to: doing so would interfere
1708 with seq rules (Note [Built-in RULES for seq] in MkId).
1709 In particular, this [Improving seq] thing *adds* a cast
1710 while [Built-in RULES for seq] *removes* one, so they
1713 You might worry about
1714 case v of x { __DEFAULT ->
1715 ... case (v `cast` co) of y { I# -> ... }}
1716 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1717 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1718 case v of x { __DEFAULT ->
1719 ... case (x `cast` co) of y { I# -> ... }}
1720 Now the outer case is not a pure seq, so [Improving seq] will happen,
1721 and then the inner case will disappear.
1723 The need for [Improving seq] showed up in Roman's experiments. Example:
1724 foo :: F Int -> Int -> Int
1725 foo t n = t `seq` bar n
1728 bar n = bar (n - case t of TI i -> i)
1729 Here we'd like to avoid repeated evaluating t inside the loop, by
1730 taking advantage of the `seq`.
1732 At one point I did transformation in LiberateCase, but it's more
1733 robust here. (Otherwise, there's a danger that we'll simply drop the
1734 'seq' altogether, before LiberateCase gets to see it.)
1737 simplAlts :: SimplEnv
1739 -> InId -- Case binder
1740 -> [InAlt] -- Non-empty
1742 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
1743 -- Like simplExpr, this just returns the simplified alternatives;
1744 -- it does not return an environment
1746 simplAlts env scrut case_bndr alts cont'
1747 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seTvSubst env)) $
1748 do { let env0 = zapFloats env
1750 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1752 ; fam_envs <- getFamEnvs
1753 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
1754 case_bndr case_bndr1 alts
1756 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
1758 ; let mb_var_scrut = case scrut' of { Var v -> Just v; _ -> Nothing }
1759 ; alts' <- mapM (simplAlt alt_env' mb_var_scrut
1760 imposs_deflt_cons case_bndr' cont') in_alts
1761 ; return (scrut', case_bndr', alts') }
1764 ------------------------------------
1765 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1766 -> OutExpr -> InId -> OutId -> [InAlt]
1767 -> SimplM (SimplEnv, OutExpr, OutId)
1768 -- Note [Improving seq]
1769 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1770 | not (isDeadBinder case_bndr) -- Not a pure seq! See Note [Improving seq]
1771 , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1772 = do { case_bndr2 <- newId (fsLit "nt") ty2
1773 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1774 env2 = extendIdSubst env case_bndr rhs
1775 ; return (env2, scrut `Cast` co, case_bndr2) }
1777 improveSeq _ env scrut _ case_bndr1 _
1778 = return (env, scrut, case_bndr1)
1781 ------------------------------------
1782 simplAlt :: SimplEnv
1783 -> Maybe OutId -- Scrutinee
1784 -> [AltCon] -- These constructors can't be present when
1785 -- matching the DEFAULT alternative
1786 -> OutId -- The case binder
1791 simplAlt env scrut imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1792 = ASSERT( null bndrs )
1793 do { let env' = addBinderUnfolding env scrut case_bndr'
1794 (mkOtherCon imposs_deflt_cons)
1795 -- Record the constructors that the case-binder *can't* be.
1796 ; rhs' <- simplExprC env' rhs cont'
1797 ; return (DEFAULT, [], rhs') }
1799 simplAlt env scrut _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1800 = ASSERT( null bndrs )
1801 do { let env' = addBinderUnfolding env scrut case_bndr'
1802 (mkSimpleUnfolding (Lit lit))
1803 ; rhs' <- simplExprC env' rhs cont'
1804 ; return (LitAlt lit, [], rhs') }
1806 simplAlt env scrut _ case_bndr' cont' (DataAlt con, vs, rhs)
1807 = do { -- Deal with the pattern-bound variables
1808 -- Mark the ones that are in ! positions in the
1809 -- data constructor as certainly-evaluated.
1810 -- NB: simplLamBinders preserves this eval info
1811 let vs_with_evals = add_evals (dataConRepStrictness con)
1812 ; (env', vs') <- simplLamBndrs env vs_with_evals
1814 -- Bind the case-binder to (con args)
1815 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1816 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1817 unf = mkSimpleUnfolding (mkConApp con con_args)
1818 env'' = addBinderUnfolding env' scrut case_bndr' unf
1820 ; rhs' <- simplExprC env'' rhs cont'
1821 ; return (DataAlt con, vs', rhs') }
1823 -- add_evals records the evaluated-ness of the bound variables of
1824 -- a case pattern. This is *important*. Consider
1825 -- data T = T !Int !Int
1827 -- case x of { T a b -> T (a+1) b }
1829 -- We really must record that b is already evaluated so that we don't
1830 -- go and re-evaluate it when constructing the result.
1831 -- See Note [Data-con worker strictness] in MkId.lhs
1836 go (v:vs') strs | isTyCoVar v = v : go vs' strs
1837 go (v:vs') (str:strs)
1838 | isMarkedStrict str = evald_v : go vs' strs
1839 | otherwise = zapped_v : go vs' strs
1841 zapped_v = zapBndrOccInfo keep_occ_info v
1842 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1843 go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1845 -- See Note [zapOccInfo]
1846 -- zap_occ_info: if the case binder is alive, then we add the unfolding
1848 -- to the envt; so vs are now very much alive
1849 -- Note [Aug06] I can't see why this actually matters, but it's neater
1850 -- case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1851 -- ==> case e of t { (a,b) -> ...(a)... }
1852 -- Look, Ma, a is alive now.
1853 keep_occ_info = isDeadBinder case_bndr' && isNothing scrut
1855 addBinderUnfolding :: SimplEnv -> Maybe OutId -> Id -> Unfolding -> SimplEnv
1856 addBinderUnfolding env scrut bndr unf
1858 Just v -> modifyInScope env1 (v `setIdUnfolding` unf)
1861 env1 = modifyInScope env bndr_w_unf
1862 bndr_w_unf = bndr `setIdUnfolding` unf
1864 zapBndrOccInfo :: Bool -> Id -> Id
1865 -- Consider case e of b { (a,b) -> ... }
1866 -- Then if we bind b to (a,b) in "...", and b is not dead,
1867 -- then we must zap the deadness info on a,b
1868 zapBndrOccInfo keep_occ_info pat_id
1869 | keep_occ_info = pat_id
1870 | otherwise = zapIdOccInfo pat_id
1873 Note [Add unfolding for scrutinee]
1874 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1875 In general it's unlikely that a variable scrutinee will appear
1876 in the case alternatives case x of { ...x unlikely to appear... }
1877 because the binder-swap in OccAnal has got rid of all such occcurrences
1878 See Note [Binder swap] in OccAnal.
1880 BUT it is still VERY IMPORTANT to add a suitable unfolding for a
1881 variable scrutinee, in simplAlt. Here's why
1883 (a,b) -> case b of c
1885 There is no occurrence of 'b' in the (...(f y)...). But y gets
1886 the unfolding (a,b), and *that* mentions b. If f has a RULE
1887 RULE f (p, I# q) = ...
1888 we want that rule to match, so we must extend the in-scope env with a
1889 suitable unfolding for 'y'. It's *essential* for rule matching; but
1890 it's also good for case-elimintation -- suppose that 'f' was inlined
1891 and did multi-level case analysis, then we'd solve it in one
1892 simplifier sweep instead of two.
1894 Exactly the same issue arises in SpecConstr;
1895 see Note [Add scrutinee to ValueEnv too] in SpecConstr
1897 %************************************************************************
1899 \subsection{Known constructor}
1901 %************************************************************************
1903 We are a bit careful with occurrence info. Here's an example
1905 (\x* -> case x of (a*, b) -> f a) (h v, e)
1907 where the * means "occurs once". This effectively becomes
1908 case (h v, e) of (a*, b) -> f a)
1910 let a* = h v; b = e in f a
1914 All this should happen in one sweep.
1917 knownCon :: SimplEnv
1918 -> OutExpr -- The scrutinee
1919 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
1920 -> InId -> [InBndr] -> InExpr -- The alternative
1922 -> SimplM (SimplEnv, OutExpr)
1924 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1925 = do { env' <- bind_args env bs dc_args
1926 ; env'' <- bind_case_bndr env'
1927 ; simplExprF env'' rhs cont }
1929 zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId
1932 bind_args env' [] _ = return env'
1934 bind_args env' (b:bs') (Type ty : args)
1935 = ASSERT( isTyCoVar b )
1936 bind_args (extendTvSubst env' b ty) bs' args
1938 bind_args env' (b:bs') (arg : args)
1940 do { let b' = zap_occ b
1941 -- Note that the binder might be "dead", because it doesn't
1942 -- occur in the RHS; and simplNonRecX may therefore discard
1943 -- it via postInlineUnconditionally.
1944 -- Nevertheless we must keep it if the case-binder is alive,
1945 -- because it may be used in the con_app. See Note [zapOccInfo]
1946 ; env'' <- simplNonRecX env' b' arg
1947 ; bind_args env'' bs' args }
1950 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1951 text "scrut:" <+> ppr scrut
1953 -- It's useful to bind bndr to scrut, rather than to a fresh
1954 -- binding x = Con arg1 .. argn
1955 -- because very often the scrut is a variable, so we avoid
1956 -- creating, and then subsequently eliminating, a let-binding
1957 -- BUT, if scrut is a not a variable, we must be careful
1958 -- about duplicating the arg redexes; in that case, make
1959 -- a new con-app from the args
1961 | isDeadBinder bndr = return env
1962 | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
1963 | otherwise = do { dc_args <- mapM (simplVar env) bs
1964 -- dc_ty_args are aready OutTypes,
1965 -- but bs are InBndrs
1966 ; let con_app = Var (dataConWorkId dc)
1967 `mkTyApps` dc_ty_args
1969 ; simplNonRecX env bndr con_app }
1972 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1973 -- This isn't strictly an error, although it is unusual.
1974 -- It's possible that the simplifer might "see" that
1975 -- an inner case has no accessible alternatives before
1976 -- it "sees" that the entire branch of an outer case is
1977 -- inaccessible. So we simply put an error case here instead.
1978 missingAlt env case_bndr alts cont
1979 = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1980 return (env, mkImpossibleExpr res_ty)
1982 res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1986 %************************************************************************
1988 \subsection{Duplicating continuations}
1990 %************************************************************************
1993 prepareCaseCont :: SimplEnv
1994 -> [InAlt] -> SimplCont
1995 -> SimplM (SimplEnv, SimplCont, SimplCont)
1996 -- We are considering
1997 -- K[case _ of { p1 -> r1; ...; pn -> rn }]
1998 -- where K is some enclosing continuation for the case
1999 -- Goal: split K into two pieces Kdup,Knodup so that
2000 -- a) Kdup can be duplicated
2001 -- b) Knodup[Kdup[e]] = K[e]
2002 -- The idea is that we'll transform thus:
2003 -- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
2005 -- We also return some extra bindings in SimplEnv (that scope over
2006 -- the entire continuation)
2008 prepareCaseCont env alts cont
2009 | many_alts alts = mkDupableCont env cont
2010 | otherwise = return (env, cont, mkBoringStop)
2012 many_alts :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative
2013 many_alts [] = False -- See Note [Bottom alternatives]
2014 many_alts [_] = False
2015 many_alts (alt:alts)
2016 | is_bot_alt alt = many_alts alts
2017 | otherwise = not (all is_bot_alt alts)
2019 is_bot_alt (_,_,rhs) = exprIsBottom rhs
2022 Note [Bottom alternatives]
2023 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2025 case (case x of { A -> error .. ; B -> e; C -> error ..)
2027 then we can just duplicate those alts because the A and C cases
2028 will disappear immediately. This is more direct than creating
2029 join points and inlining them away; and in some cases we would
2030 not even create the join points (see Note [Single-alternative case])
2031 and we would keep the case-of-case which is silly. See Trac #4930.
2034 mkDupableCont :: SimplEnv -> SimplCont
2035 -> SimplM (SimplEnv, SimplCont, SimplCont)
2037 mkDupableCont env cont
2038 | contIsDupable cont
2039 = return (env, cont, mkBoringStop)
2041 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
2043 mkDupableCont env (CoerceIt ty cont)
2044 = do { (env', dup, nodup) <- mkDupableCont env cont
2045 ; return (env', CoerceIt ty dup, nodup) }
2047 mkDupableCont env cont@(StrictBind {})
2048 = return (env, mkBoringStop, cont)
2049 -- See Note [Duplicating StrictBind]
2051 mkDupableCont env (StrictArg info cci cont)
2052 -- See Note [Duplicating StrictArg]
2053 = do { (env', dup, nodup) <- mkDupableCont env cont
2054 ; (env'', args') <- mapAccumLM (makeTrivial NotTopLevel) env' (ai_args info)
2055 ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
2057 mkDupableCont env (ApplyTo _ arg se cont)
2058 = -- e.g. [...hole...] (...arg...)
2060 -- let a = ...arg...
2061 -- in [...hole...] a
2062 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
2063 ; arg' <- simplExpr (se `setInScope` env') arg
2064 ; (env'', arg'') <- makeTrivial NotTopLevel env' arg'
2065 ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
2066 ; return (env'', app_cont, nodup_cont) }
2068 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
2069 -- See Note [Single-alternative case]
2070 -- | not (exprIsDupable rhs && contIsDupable case_cont)
2071 -- | not (isDeadBinder case_bndr)
2072 | all isDeadBinder bs -- InIds
2073 && not (isUnLiftedType (idType case_bndr))
2074 -- Note [Single-alternative-unlifted]
2075 = return (env, mkBoringStop, cont)
2077 mkDupableCont env (Select _ case_bndr alts se cont)
2078 = -- e.g. (case [...hole...] of { pi -> ei })
2080 -- let ji = \xij -> ei
2081 -- in case [...hole...] of { pi -> ji xij }
2082 do { tick (CaseOfCase case_bndr)
2083 ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
2084 -- NB: call mkDupableCont here, *not* prepareCaseCont
2085 -- We must make a duplicable continuation, whereas prepareCaseCont
2086 -- doesn't when there is a single case branch
2088 ; let alt_env = se `setInScope` env'
2089 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
2090 ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' dup_cont) alts
2091 -- Safe to say that there are no handled-cons for the DEFAULT case
2092 -- NB: simplBinder does not zap deadness occ-info, so
2093 -- a dead case_bndr' will still advertise its deadness
2094 -- This is really important because in
2095 -- case e of b { (# p,q #) -> ... }
2096 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
2097 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
2098 -- In the new alts we build, we have the new case binder, so it must retain
2100 -- NB: we don't use alt_env further; it has the substEnv for
2101 -- the alternatives, and we don't want that
2103 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
2104 ; return (env'', -- Note [Duplicated env]
2105 Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
2109 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
2110 -> SimplM (SimplEnv, [InAlt])
2111 -- Absorbs the continuation into the new alternatives
2113 mkDupableAlts env case_bndr' the_alts
2116 go env0 [] = return (env0, [])
2118 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
2119 ; (env2, alts') <- go env1 alts
2120 ; return (env2, alt' : alts' ) }
2122 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
2123 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
2124 mkDupableAlt env case_bndr (con, bndrs', rhs')
2125 | exprIsDupable rhs' -- Note [Small alternative rhs]
2126 = return (env, (con, bndrs', rhs'))
2128 = do { let rhs_ty' = exprType rhs'
2129 scrut_ty = idType case_bndr
2132 DEFAULT -> case_bndr
2133 DataAlt dc -> setIdUnfolding case_bndr unf
2135 -- See Note [Case binders and join points]
2136 unf = mkInlineUnfolding Nothing rhs
2137 rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
2138 ++ varsToCoreExprs bndrs')
2140 LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
2141 <+> ppr case_bndr <+> ppr con )
2143 -- The case binder is alive but trivial, so why has
2144 -- it not been substituted away?
2146 used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
2147 | otherwise = bndrs' ++ [case_bndr_w_unf]
2150 | isTyCoVar bndr = True -- Abstract over all type variables just in case
2151 | otherwise = not (isDeadBinder bndr)
2152 -- The deadness info on the new Ids is preserved by simplBinders
2154 ; (final_bndrs', final_args) -- Note [Join point abstraction]
2155 <- if (any isId used_bndrs')
2156 then return (used_bndrs', varsToCoreExprs used_bndrs')
2157 else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
2158 ; return ([rw_id], [Var realWorldPrimId]) }
2160 ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2161 -- Note [Funky mkPiTypes]
2163 ; let -- We make the lambdas into one-shot-lambdas. The
2164 -- join point is sure to be applied at most once, and doing so
2165 -- prevents the body of the join point being floated out by
2166 -- the full laziness pass
2167 really_final_bndrs = map one_shot final_bndrs'
2168 one_shot v | isId v = setOneShotLambda v
2170 join_rhs = mkLams really_final_bndrs rhs'
2171 join_call = mkApps (Var join_bndr) final_args
2173 ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2174 ; return (env', (con, bndrs', join_call)) }
2175 -- See Note [Duplicated env]
2178 Note [Case binders and join points]
2179 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2181 case (case .. ) of c {
2184 If we make a join point with c but not c# we get
2185 $j = \c -> ....c....
2187 But if later inlining scrutines the c, thus
2189 $j = \c -> ... case c of { I# y -> ... } ...
2191 we won't see that 'c' has already been scrutinised. This actually
2192 happens in the 'tabulate' function in wave4main, and makes a significant
2193 difference to allocation.
2195 An alternative plan is this:
2197 $j = \c# -> let c = I# c# in ...c....
2199 but that is bad if 'c' is *not* later scrutinised.
2201 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2202 (an InlineRule) that it's really I# c#, thus
2204 $j = \c# -> \c[=I# c#] -> ...c....
2206 Absence analysis may later discard 'c'.
2208 NB: take great care when doing strictness analysis;
2209 see Note [Lamba-bound unfoldings] in DmdAnal.
2211 Also note that we can still end up passing stuff that isn't used. Before
2212 strictness analysis we have
2213 let $j x y c{=(x,y)} = (h c, ...)
2215 After strictness analysis we see that h is strict, we end up with
2216 let $j x y c{=(x,y)} = ($wh x y, ...)
2219 Note [Duplicated env]
2220 ~~~~~~~~~~~~~~~~~~~~~
2221 Some of the alternatives are simplified, but have not been turned into a join point
2222 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
2223 bind the join point, because it might to do PostInlineUnconditionally, and
2224 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
2225 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2226 at worst delays the join-point inlining.
2228 Note [Small alternative rhs]
2229 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2230 It is worth checking for a small RHS because otherwise we
2231 get extra let bindings that may cause an extra iteration of the simplifier to
2232 inline back in place. Quite often the rhs is just a variable or constructor.
2233 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2234 iterations because the version with the let bindings looked big, and so wasn't
2235 inlined, but after the join points had been inlined it looked smaller, and so
2238 NB: we have to check the size of rhs', not rhs.
2239 Duplicating a small InAlt might invalidate occurrence information
2240 However, if it *is* dupable, we return the *un* simplified alternative,
2241 because otherwise we'd need to pair it up with an empty subst-env....
2242 but we only have one env shared between all the alts.
2243 (Remember we must zap the subst-env before re-simplifying something).
2244 Rather than do this we simply agree to re-simplify the original (small) thing later.
2246 Note [Funky mkPiTypes]
2247 ~~~~~~~~~~~~~~~~~~~~~~
2248 Notice the funky mkPiTypes. If the contructor has existentials
2249 it's possible that the join point will be abstracted over
2250 type varaibles as well as term variables.
2251 Example: Suppose we have
2252 data T = forall t. C [t]
2254 case (case e of ...) of
2256 We get the join point
2257 let j :: forall t. [t] -> ...
2258 j = /\t \xs::[t] -> rhs
2260 case (case e of ...) of
2261 C t xs::[t] -> j t xs
2263 Note [Join point abstaction]
2264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2265 If we try to lift a primitive-typed something out
2266 for let-binding-purposes, we will *caseify* it (!),
2267 with potentially-disastrous strictness results. So
2268 instead we turn it into a function: \v -> e
2269 where v::State# RealWorld#. The value passed to this function
2270 is realworld#, which generates (almost) no code.
2272 There's a slight infelicity here: we pass the overall
2273 case_bndr to all the join points if it's used in *any* RHS,
2274 because we don't know its usage in each RHS separately
2276 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2277 we make the join point into a function whenever used_bndrs'
2278 is empty. This makes the join-point more CPR friendly.
2279 Consider: let j = if .. then I# 3 else I# 4
2280 in case .. of { A -> j; B -> j; C -> ... }
2282 Now CPR doesn't w/w j because it's a thunk, so
2283 that means that the enclosing function can't w/w either,
2284 which is a lose. Here's the example that happened in practice:
2285 kgmod :: Int -> Int -> Int
2286 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2290 I have seen a case alternative like this:
2292 It's a bit silly to add the realWorld dummy arg in this case, making
2295 (the \v alone is enough to make CPR happy) but I think it's rare
2297 Note [Duplicating StrictArg]
2298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2299 The original plan had (where E is a big argument)
2301 ==> let $j = \a -> f E a
2304 But this is terrible! Here's an example:
2305 && E (case x of { T -> F; F -> T })
2306 Now, && is strict so we end up simplifying the case with
2307 an ArgOf continuation. If we let-bind it, we get
2308 let $j = \v -> && E v
2309 in simplExpr (case x of { T -> F; F -> T })
2311 And after simplifying more we get
2312 let $j = \v -> && E v
2313 in case x of { T -> $j F; F -> $j T }
2314 Which is a Very Bad Thing
2316 What we do now is this
2320 Now if the thing in the hole is a case expression (which is when
2321 we'll call mkDupableCont), we'll push the function call into the
2322 branches, which is what we want. Now RULES for f may fire, and
2323 call-pattern specialisation. Here's an example from Trac #3116
2326 _ -> Chunk p fpc (o+1) (l-1) bs')
2327 If we can push the call for 'go' inside the case, we get
2328 call-pattern specialisation for 'go', which is *crucial* for
2331 Here is the (&&) example:
2332 && E (case x of { T -> F; F -> T })
2334 case x of { T -> && a F; F -> && a T }
2338 * Arguments to f *after* the strict one are handled by
2339 the ApplyTo case of mkDupableCont. Eg
2342 * We can only do the let-binding of E because the function
2343 part of a StrictArg continuation is an explicit syntax
2344 tree. In earlier versions we represented it as a function
2345 (CoreExpr -> CoreEpxr) which we couldn't take apart.
2347 Do *not* duplicate StrictBind and StritArg continuations. We gain
2348 nothing by propagating them into the expressions, and we do lose a
2351 The desire not to duplicate is the entire reason that
2352 mkDupableCont returns a pair of continuations.
2354 Note [Duplicating StrictBind]
2355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2356 Unlike StrictArg, there doesn't seem anything to gain from
2357 duplicating a StrictBind continuation, so we don't.
2359 The desire not to duplicate is the entire reason that
2360 mkDupableCont returns a pair of continuations.
2363 Note [Single-alternative cases]
2364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2365 This case is just like the ArgOf case. Here's an example:
2369 case (case x of I# x' ->
2371 True -> I# (negate# x')
2372 False -> I# x') of y {
2374 Because the (case x) has only one alternative, we'll transform to
2376 case (case x' <# 0# of
2377 True -> I# (negate# x')
2378 False -> I# x') of y {
2380 But now we do *NOT* want to make a join point etc, giving
2382 let $j = \y -> MkT y
2384 True -> $j (I# (negate# x'))
2386 In this case the $j will inline again, but suppose there was a big
2387 strict computation enclosing the orginal call to MkT. Then, it won't
2388 "see" the MkT any more, because it's big and won't get duplicated.
2389 And, what is worse, nothing was gained by the case-of-case transform.
2391 So, in circumstances like these, we don't want to build join points
2392 and push the outer case into the branches of the inner one. Instead,
2393 don't duplicate the continuation.
2395 When should we use this strategy? We should not use it on *every*
2396 single-alternative case:
2397 e.g. case (case ....) of (a,b) -> (# a,b #)
2398 Here we must push the outer case into the inner one!
2401 * Match [(DEFAULT,_,_)], but in the common case of Int,
2402 the alternative-filling-in code turned the outer case into
2403 case (...) of y { I# _ -> MkT y }
2405 * Match on single alternative plus (not (isDeadBinder case_bndr))
2406 Rationale: pushing the case inwards won't eliminate the construction.
2407 But there's a risk of
2408 case (...) of y { (a,b) -> let z=(a,b) in ... }
2409 Now y looks dead, but it'll come alive again. Still, this
2410 seems like the best option at the moment.
2412 * Match on single alternative plus (all (isDeadBinder bndrs))
2413 Rationale: this is essentially seq.
2415 * Match when the rhs is *not* duplicable, and hence would lead to a
2416 join point. This catches the disaster-case above. We can test
2417 the *un-simplified* rhs, which is fine. It might get bigger or
2418 smaller after simplification; if it gets smaller, this case might
2419 fire next time round. NB also that we must test contIsDupable
2420 case_cont *too, because case_cont might be big!
2422 HOWEVER: I found that this version doesn't work well, because
2423 we can get let x = case (...) of { small } in ...case x...
2424 When x is inlined into its full context, we find that it was a bad
2425 idea to have pushed the outer case inside the (...) case.
2427 Note [Single-alternative-unlifted]
2428 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2429 Here's another single-alternative where we really want to do case-of-case:
2437 case y_s6X of tpl_s7m {
2438 M1.Mk1 ipv_s70 -> ipv_s70;
2439 M1.Mk2 ipv_s72 -> ipv_s72;
2445 case x_s74 of tpl_s7n {
2446 M1.Mk1 ipv_s77 -> ipv_s77;
2447 M1.Mk2 ipv_s79 -> ipv_s79;
2451 { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2455 So the outer case is doing *nothing at all*, other than serving as a
2456 join-point. In this case we really want to do case-of-case and decide
2457 whether to use a real join point or just duplicate the continuation.
2459 Hence: check whether the case binder's type is unlifted, because then
2460 the outer case is *not* a seq.