2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
9 mkLam, mkCase, prepareAlts,
12 preInlineUnconditionally, postInlineUnconditionally,
13 activeUnfolding, activeUnfInRule, activeRule,
14 simplEnvForGHCi, simplEnvForRules, updModeForInlineRules,
16 -- The continuation type
17 SimplCont(..), DupFlag(..), ArgInfo(..),
18 contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs,
19 pushArgs, countValArgs, countArgs, addArgTo,
20 mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg,
21 interestingCallContext,
23 interestingArg, mkArgInfo,
28 #include "HsVersions.h"
34 import qualified CoreSubst
38 import CoreArity ( etaExpand, exprEtaExpandArity )
42 import Var ( isCoVar )
45 import Type hiding( substTy )
46 import Coercion ( coercionKind )
48 import Unify ( dataConCannotMatch )
60 %************************************************************************
64 %************************************************************************
66 A SimplCont allows the simplifier to traverse the expression in a
67 zipper-like fashion. The SimplCont represents the rest of the expression,
68 "above" the point of interest.
70 You can also think of a SimplCont as an "evaluation context", using
71 that term in the way it is used for operational semantics. This is the
72 way I usually think of it, For example you'll often see a syntax for
73 evaluation context looking like
74 C ::= [] | C e | case C of alts | C `cast` co
75 That's the kind of thing we are doing here, and I use that syntax in
80 * A SimplCont describes a *strict* context (just like
81 evaluation contexts do). E.g. Just [] is not a SimplCont
83 * A SimplCont describes a context that *does not* bind
84 any variables. E.g. \x. [] is not a SimplCont
88 = Stop -- An empty context, or hole, []
89 CallCtxt -- True <=> There is something interesting about
90 -- the context, and hence the inliner
91 -- should be a bit keener (see interestingCallContext)
93 -- This is an argument of a function that has RULES
94 -- Inlining the call might allow the rule to fire
96 | CoerceIt -- C `cast` co
97 OutCoercion -- The coercion simplified
102 InExpr StaticEnv -- The argument and its static env
105 | Select -- case C of alts
107 InId [InAlt] StaticEnv -- The case binder, alts, and subst-env
110 -- The two strict forms have no DupFlag, because we never duplicate them
111 | StrictBind -- (\x* \xs. e) C
112 InId [InBndr] -- let x* = [] in e
113 InExpr StaticEnv -- is a special case
116 | StrictArg -- f e1 ..en C
117 ArgInfo -- Specifies f, e1..en, Whether f has rules, etc
118 -- plus strictness flags for *further* args
119 CallCtxt -- Whether *this* argument position is interesting
124 ai_fun :: Id, -- The function
125 ai_args :: [OutExpr], -- ...applied to these args (which are in *reverse* order)
126 ai_rules :: [CoreRule], -- Rules for this function
128 ai_encl :: Bool, -- Flag saying whether this function
129 -- or an enclosing one has rules (recursively)
130 -- True => be keener to inline in all args
132 ai_strs :: [Bool], -- Strictness of remaining arguments
133 -- Usually infinite, but if it is finite it guarantees
134 -- that the function diverges after being given
135 -- that number of args
136 ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline
140 addArgTo :: ArgInfo -> OutExpr -> ArgInfo
141 addArgTo ai arg = ai { ai_args = arg : ai_args ai }
143 instance Outputable SimplCont where
144 ppr (Stop interesting) = ptext (sLit "Stop") <> brackets (ppr interesting)
145 ppr (ApplyTo dup arg _ cont) = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
146 {- $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
147 ppr (StrictBind b _ _ _ cont) = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
148 ppr (StrictArg ai _ cont) = (ptext (sLit "StrictArg") <+> ppr (ai_fun ai)) $$ ppr cont
149 ppr (Select dup bndr alts _ cont) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$
150 (nest 4 (ppr alts)) $$ ppr cont
151 ppr (CoerceIt co cont) = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
153 data DupFlag = OkToDup | NoDup
155 instance Outputable DupFlag where
156 ppr OkToDup = ptext (sLit "ok")
157 ppr NoDup = ptext (sLit "nodup")
162 mkBoringStop :: SimplCont
163 mkBoringStop = Stop BoringCtxt
165 mkRhsStop :: SimplCont -- See Note [RHS of lets] in CoreUnfold
166 mkRhsStop = Stop (ArgCtxt False)
168 mkLazyArgStop :: CallCtxt -> SimplCont
169 mkLazyArgStop cci = Stop cci
172 contIsRhsOrArg :: SimplCont -> Bool
173 contIsRhsOrArg (Stop {}) = True
174 contIsRhsOrArg (StrictBind {}) = True
175 contIsRhsOrArg (StrictArg {}) = True
176 contIsRhsOrArg _ = False
179 contIsDupable :: SimplCont -> Bool
180 contIsDupable (Stop {}) = True
181 contIsDupable (ApplyTo OkToDup _ _ _) = True
182 contIsDupable (Select OkToDup _ _ _ _) = True
183 contIsDupable (CoerceIt _ cont) = contIsDupable cont
184 contIsDupable _ = False
187 contIsTrivial :: SimplCont -> Bool
188 contIsTrivial (Stop {}) = True
189 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
190 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
191 contIsTrivial _ = False
194 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
195 contResultType env ty cont
198 subst_ty se ty = substTy (se `setInScope` env) ty
201 go (CoerceIt co cont) _ = go cont (snd (coercionKind co))
202 go (StrictBind _ bs body se cont) _ = go cont (subst_ty se (exprType (mkLams bs body)))
203 go (StrictArg ai _ cont) _ = go cont (funResultTy (argInfoResultTy ai))
204 go (Select _ _ alts se cont) _ = go cont (subst_ty se (coreAltsType alts))
205 go (ApplyTo _ arg se cont) ty = go cont (apply_to_arg ty arg se)
207 apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
208 apply_to_arg ty _ _ = funResultTy ty
210 argInfoResultTy :: ArgInfo -> OutType
211 argInfoResultTy (ArgInfo { ai_fun = fun, ai_args = args })
212 = foldr (\arg fn_ty -> applyTypeToArg fn_ty arg) (idType fun) args
215 countValArgs :: SimplCont -> Int
216 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
217 countValArgs (ApplyTo _ _ _ cont) = 1 + countValArgs cont
220 countArgs :: SimplCont -> Int
221 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
224 contArgs :: SimplCont -> ([OutExpr], SimplCont)
225 -- Uses substitution to turn each arg into an OutExpr
226 contArgs cont = go [] cont
228 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
229 go args cont = (reverse args, cont)
231 pushArgs :: SimplEnv -> [CoreExpr] -> SimplCont -> SimplCont
232 pushArgs _env [] cont = cont
233 pushArgs env (arg:args) cont = ApplyTo NoDup arg env (pushArgs env args cont)
235 dropArgs :: Int -> SimplCont -> SimplCont
236 dropArgs 0 cont = cont
237 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
238 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
242 Note [Interesting call context]
243 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
244 We want to avoid inlining an expression where there can't possibly be
245 any gain, such as in an argument position. Hence, if the continuation
246 is interesting (eg. a case scrutinee, application etc.) then we
247 inline, otherwise we don't.
249 Previously some_benefit used to return True only if the variable was
250 applied to some value arguments. This didn't work:
252 let x = _coerce_ (T Int) Int (I# 3) in
253 case _coerce_ Int (T Int) x of
256 we want to inline x, but can't see that it's a constructor in a case
257 scrutinee position, and some_benefit is False.
261 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
263 .... case dMonadST _@_ x0 of (a,b,c) -> ....
265 we'd really like to inline dMonadST here, but we *don't* want to
266 inline if the case expression is just
268 case x of y { DEFAULT -> ... }
270 since we can just eliminate this case instead (x is in WHNF). Similar
271 applies when x is bound to a lambda expression. Hence
272 contIsInteresting looks for case expressions with just a single
277 interestingCallContext :: SimplCont -> CallCtxt
278 -- See Note [Interesting call context]
279 interestingCallContext cont
282 interesting (Select _ bndr _ _ _)
283 | isDeadBinder bndr = CaseCtxt
284 | otherwise = ArgCtxt False -- If the binder is used, this
285 -- is like a strict let
286 -- See Note [RHS of lets] in CoreUnfold
288 interesting (ApplyTo _ arg _ cont)
289 | isTypeArg arg = interesting cont
290 | otherwise = ValAppCtxt -- Can happen if we have (f Int |> co) y
291 -- If f has an INLINE prag we need to give it some
292 -- motivation to inline. See Note [Cast then apply]
295 interesting (StrictArg _ cci _) = cci
296 interesting (StrictBind {}) = BoringCtxt
297 interesting (Stop cci) = cci
298 interesting (CoerceIt _ cont) = interesting cont
299 -- If this call is the arg of a strict function, the context
300 -- is a bit interesting. If we inline here, we may get useful
301 -- evaluation information to avoid repeated evals: e.g.
303 -- Here the contIsInteresting makes the '*' keener to inline,
304 -- which in turn exposes a constructor which makes the '+' inline.
305 -- Assuming that +,* aren't small enough to inline regardless.
307 -- It's also very important to inline in a strict context for things
310 -- Here, the context of (f x) is strict, and if f's unfolding is
311 -- a build it's *great* to inline it here. So we must ensure that
312 -- the context for (f x) is not totally uninteresting.
317 -> [CoreRule] -- Rules for function
318 -> Int -- Number of value args
319 -> SimplCont -- Context of the call
322 mkArgInfo fun rules n_val_args call_cont
323 | n_val_args < idArity fun -- Note [Unsaturated functions]
324 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
326 , ai_strs = vanilla_stricts
327 , ai_discs = vanilla_discounts }
329 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
330 , ai_encl = interestingArgContext rules call_cont
331 , ai_strs = add_type_str (idType fun) arg_stricts
332 , ai_discs = arg_discounts }
334 vanilla_discounts, arg_discounts :: [Int]
335 vanilla_discounts = repeat 0
336 arg_discounts = case idUnfolding fun of
337 CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}}
338 -> discounts ++ vanilla_discounts
339 _ -> vanilla_discounts
341 vanilla_stricts, arg_stricts :: [Bool]
342 vanilla_stricts = repeat False
345 = case splitStrictSig (idStrictness fun) of
346 (demands, result_info)
347 | not (demands `lengthExceeds` n_val_args)
348 -> -- Enough args, use the strictness given.
349 -- For bottoming functions we used to pretend that the arg
350 -- is lazy, so that we don't treat the arg as an
351 -- interesting context. This avoids substituting
352 -- top-level bindings for (say) strings into
353 -- calls to error. But now we are more careful about
354 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
355 if isBotRes result_info then
356 map isStrictDmd demands -- Finite => result is bottom
358 map isStrictDmd demands ++ vanilla_stricts
360 -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun)
361 <+> ppr n_val_args <+> ppr demands )
362 vanilla_stricts -- Not enough args, or no strictness
364 add_type_str :: Type -> [Bool] -> [Bool]
365 -- If the function arg types are strict, record that in the 'strictness bits'
366 -- No need to instantiate because unboxed types (which dominate the strict
367 -- types) can't instantiate type variables.
368 -- add_type_str is done repeatedly (for each call); might be better
369 -- once-for-all in the function
370 -- But beware primops/datacons with no strictness
371 add_type_str _ [] = []
372 add_type_str fun_ty strs -- Look through foralls
373 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions
374 = add_type_str fun_ty' strs
375 add_type_str fun_ty (str:strs) -- Add strict-type info
376 | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
377 = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
381 {- Note [Unsaturated functions]
382 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 Consider (test eyeball/inline4)
386 where f has arity 2. Then we do not want to inline 'x', because
387 it'll just be floated out again. Even if f has lots of discounts
388 on its first argument -- it must be saturated for these to kick in
391 interestingArgContext :: [CoreRule] -> SimplCont -> Bool
392 -- If the argument has form (f x y), where x,y are boring,
393 -- and f is marked INLINE, then we don't want to inline f.
394 -- But if the context of the argument is
396 -- where g has rules, then we *do* want to inline f, in case it
397 -- exposes a rule that might fire. Similarly, if the context is
399 -- where h has rules, then we do want to inline f; hence the
400 -- call_cont argument to interestingArgContext
402 -- The ai-rules flag makes this happen; if it's
403 -- set, the inliner gets just enough keener to inline f
404 -- regardless of how boring f's arguments are, if it's marked INLINE
406 -- The alternative would be to *always* inline an INLINE function,
407 -- regardless of how boring its context is; but that seems overkill
408 -- For example, it'd mean that wrapper functions were always inlined
409 interestingArgContext rules call_cont
410 = notNull rules || enclosing_fn_has_rules
412 enclosing_fn_has_rules = go call_cont
414 go (Select {}) = False
415 go (ApplyTo {}) = False
416 go (StrictArg _ cci _) = interesting cci
417 go (StrictBind {}) = False -- ??
418 go (CoerceIt _ c) = go c
419 go (Stop cci) = interesting cci
421 interesting (ArgCtxt rules) = rules
422 interesting _ = False
427 %************************************************************************
429 \subsection{Decisions about inlining}
431 %************************************************************************
434 simplEnvForGHCi :: SimplEnv
435 simplEnvForGHCi = mkSimplEnv allOffSwitchChecker $
436 SimplGently { sm_rules = False, sm_inline = False }
437 -- Do not do any inlining, in case we expose some unboxed
438 -- tuple stuff that confuses the bytecode interpreter
440 simplEnvForRules :: SimplEnv
441 simplEnvForRules = mkSimplEnv allOffSwitchChecker $
442 SimplGently { sm_rules = True, sm_inline = False }
444 updModeForInlineRules :: SimplifierMode -> SimplifierMode
445 updModeForInlineRules mode
447 SimplGently {} -> mode -- Don't modify mode if we already gentle
448 SimplPhase {} -> SimplGently { sm_rules = True, sm_inline = True }
449 -- Simplify as much as possible, subject to the usual "gentle" rules
452 Inlining is controlled partly by the SimplifierMode switch. This has two
455 SimplGently (a) Simplifying before specialiser/full laziness
456 (b) Simplifiying inside InlineRules
457 (c) Simplifying the LHS of a rule
458 (d) Simplifying a GHCi expression or Template
461 SimplPhase n _ Used at all other times
465 Gentle mode has a separate boolean flag to control
466 a) inlining (sm_inline flag)
467 b) rules (sm_rules flag)
468 A key invariant about Gentle mode is that it is treated as the EARLIEST
469 phase. Something is inlined if the sm_inline flag is on AND the thing
470 is inlinable in the earliest phase. This is important. Example
472 {-# INLINE [~1] g #-}
478 If we were to inline g into f's inlining, then an importing module would
480 f e --> g (g e) ---> RULE fires
481 because the InlineRule for f has had g inlined into it.
483 On the other hand, it is bad not to do ANY inlining into an
484 InlineRule, because then recursive knots in instance declarations
485 don't get unravelled.
487 However, *sometimes* SimplGently must do no call-site inlining at all.
488 Before full laziness we must be careful not to inline wrappers,
489 because doing so inhibits floating
490 e.g. ...(case f x of ...)...
491 ==> ...(case (case x of I# x# -> fw x#) of ...)...
492 ==> ...(case x of I# x# -> case fw x# of ...)...
493 and now the redex (f x) isn't floatable any more.
495 The no-inlining thing is also important for Template Haskell. You might be
496 compiling in one-shot mode with -O2; but when TH compiles a splice before
497 running it, we don't want to use -O2. Indeed, we don't want to inline
498 anything, because the byte-code interpreter might get confused about
499 unboxed tuples and suchlike.
501 Note [RULEs enabled in SimplGently]
502 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
503 RULES are enabled when doing "gentle" simplification. Two reasons:
505 * We really want the class-op cancellation to happen:
506 op (df d1 d2) --> $cop3 d1 d2
507 because this breaks the mutual recursion between 'op' and 'df'
511 to work in Template Haskell when simplifying
512 splices, so we get simpler code for literal strings
514 Note [Simplifying gently inside InlineRules]
515 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
516 We don't do much simplification inside InlineRules (which come from
517 INLINE pragmas). It really is important to switch off inlinings
518 inside such expressions. Consider the following example
524 in ...g...g...g...g...g...
526 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
527 and thence copied multiple times when g is inlined.
529 This function may be inlinined in other modules, so we don't want to
530 remove (by inlining) calls to functions that have specialisations, or
531 that may have transformation rules in an importing scope.
533 E.g. {-# INLINE f #-}
536 and suppose that g is strict *and* has specialisations. If we inline
537 g's wrapper, we deny f the chance of getting the specialised version
538 of g when f is inlined at some call site (perhaps in some other
541 It's also important not to inline a worker back into a wrapper.
543 wraper = inline_me (\x -> ...worker... )
544 Normally, the inline_me prevents the worker getting inlined into
545 the wrapper (initially, the worker's only call site!). But,
546 if the wrapper is sure to be called, the strictness analyser will
547 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
548 continuation. That's why the keep_inline predicate returns True for
549 ArgOf continuations. It shouldn't do any harm not to dissolve the
550 inline-me note under these circumstances.
552 Although we do very little simplification inside an InlineRule,
553 the RHS is simplified as normal. For example:
555 all xs = foldr (&&) True xs
556 any p = all . map p {-# INLINE any #-}
558 The RHS of 'any' will get optimised and deforested; but the InlineRule
559 will still mention the original RHS.
562 preInlineUnconditionally
563 ~~~~~~~~~~~~~~~~~~~~~~~~
564 @preInlineUnconditionally@ examines a bndr to see if it is used just
565 once in a completely safe way, so that it is safe to discard the
566 binding inline its RHS at the (unique) usage site, REGARDLESS of how
567 big the RHS might be. If this is the case we don't simplify the RHS
568 first, but just inline it un-simplified.
570 This is much better than first simplifying a perhaps-huge RHS and then
571 inlining and re-simplifying it. Indeed, it can be at least quadratically
580 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
581 This can happen with cascades of functions too:
588 THE MAIN INVARIANT is this:
590 ---- preInlineUnconditionally invariant -----
591 IF preInlineUnconditionally chooses to inline x = <rhs>
592 THEN doing the inlining should not change the occurrence
593 info for the free vars of <rhs>
594 ----------------------------------------------
596 For example, it's tempting to look at trivial binding like
598 and inline it unconditionally. But suppose x is used many times,
599 but this is the unique occurrence of y. Then inlining x would change
600 y's occurrence info, which breaks the invariant. It matters: y
601 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
604 Even RHSs labelled InlineMe aren't caught here, because there might be
605 no benefit from inlining at the call site.
607 [Sept 01] Don't unconditionally inline a top-level thing, because that
608 can simply make a static thing into something built dynamically. E.g.
612 [Remember that we treat \s as a one-shot lambda.] No point in
613 inlining x unless there is something interesting about the call site.
615 But watch out: if you aren't careful, some useful foldr/build fusion
616 can be lost (most notably in spectral/hartel/parstof) because the
617 foldr didn't see the build. Doing the dynamic allocation isn't a big
618 deal, in fact, but losing the fusion can be. But the right thing here
619 seems to be to do a callSiteInline based on the fact that there is
620 something interesting about the call site (it's strict). Hmm. That
623 Conclusion: inline top level things gaily until Phase 0 (the last
624 phase), at which point don't.
626 Note [pre/postInlineUnconditionally in gentle mode]
627 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
628 Even in gentle mode we want to do preInlineUnconditionally. The
629 reason is that too little clean-up happens if you don't inline
630 use-once things. Also a bit of inlining is *good* for full laziness;
631 it can expose constant sub-expressions. Example in
632 spectral/mandel/Mandel.hs, where the mandelset function gets a useful
633 let-float if you inline windowToViewport
635 However, as usual for Gentle mode, do not inline things that are
636 inactive in the intial stages. See Note [Gentle mode].
639 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
640 preInlineUnconditionally env top_lvl bndr rhs
642 | opt_SimplNoPreInlining = False
643 | otherwise = case idOccInfo bndr of
644 IAmDead -> True -- Happens in ((\x.1) v)
645 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
649 active = case phase of
650 SimplGently {} -> isEarlyActive act
651 -- See Note [pre/postInlineUnconditionally in gentle mode]
652 SimplPhase n _ -> isActive n act
653 act = idInlineActivation bndr
655 try_once in_lam int_cxt -- There's one textual occurrence
656 | not in_lam = isNotTopLevel top_lvl || early_phase
657 | otherwise = int_cxt && canInlineInLam rhs
659 -- Be very careful before inlining inside a lambda, becuase (a) we must not
660 -- invalidate occurrence information, and (b) we want to avoid pushing a
661 -- single allocation (here) into multiple allocations (inside lambda).
662 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
663 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
665 -- is_cheap = exprIsCheap rhs
666 -- ok = is_cheap && int_cxt
668 -- int_cxt The context isn't totally boring
669 -- E.g. let f = \ab.BIG in \y. map f xs
670 -- Don't want to substitute for f, because then we allocate
671 -- its closure every time the \y is called
672 -- But: let f = \ab.BIG in \y. map (f y) xs
673 -- Now we do want to substitute for f, even though it's not
674 -- saturated, because we're going to allocate a closure for
675 -- (f y) every time round the loop anyhow.
677 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
678 -- so substituting rhs inside a lambda doesn't change the occ info.
679 -- Sadly, not quite the same as exprIsHNF.
680 canInlineInLam (Lit _) = True
681 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
682 canInlineInLam (Note _ e) = canInlineInLam e
683 canInlineInLam _ = False
685 early_phase = case phase of
686 SimplPhase 0 _ -> False
688 -- If we don't have this early_phase test, consider
689 -- x = length [1,2,3]
690 -- The full laziness pass carefully floats all the cons cells to
691 -- top level, and preInlineUnconditionally floats them all back in.
692 -- Result is (a) static allocation replaced by dynamic allocation
693 -- (b) many simplifier iterations because this tickles
694 -- a related problem; only one inlining per pass
696 -- On the other hand, I have seen cases where top-level fusion is
697 -- lost if we don't inline top level thing (e.g. string constants)
698 -- Hence the test for phase zero (which is the phase for all the final
699 -- simplifications). Until phase zero we take no special notice of
700 -- top level things, but then we become more leery about inlining
705 postInlineUnconditionally
706 ~~~~~~~~~~~~~~~~~~~~~~~~~
707 @postInlineUnconditionally@ decides whether to unconditionally inline
708 a thing based on the form of its RHS; in particular if it has a
709 trivial RHS. If so, we can inline and discard the binding altogether.
711 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
712 only have *forward* references Hence, it's safe to discard the binding
714 NOTE: This isn't our last opportunity to inline. We're at the binding
715 site right now, and we'll get another opportunity when we get to the
718 Note that we do this unconditional inlining only for trival RHSs.
719 Don't inline even WHNFs inside lambdas; doing so may simply increase
720 allocation when the function is called. This isn't the last chance; see
723 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
724 Because we don't even want to inline them into the RHS of constructor
725 arguments. See NOTE above
727 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
728 it's best to inline it anyway. We often get a=E; b=a from desugaring,
729 with both a and b marked NOINLINE. But that seems incompatible with
730 our new view that inlining is like a RULE, so I'm sticking to the 'active'
734 postInlineUnconditionally
735 :: SimplEnv -> TopLevelFlag
736 -> OutId -- The binder (an InId would be fine too)
737 -> OccInfo -- From the InId
741 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
743 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline
744 -- because it might be referred to "earlier"
745 | isExportedId bndr = False
746 | isStableUnfolding unfolding = False -- Note [InlineRule and postInlineUnconditionally]
747 | exprIsTrivial rhs = True
750 -- The point of examining occ_info here is that for *non-values*
751 -- that occur outside a lambda, the call-site inliner won't have
752 -- a chance (becuase it doesn't know that the thing
753 -- only occurs once). The pre-inliner won't have gotten
754 -- it either, if the thing occurs in more than one branch
755 -- So the main target is things like
758 -- True -> case x of ...
759 -- False -> case x of ...
760 -- This is very important in practice; e.g. wheel-seive1 doubles
761 -- in allocation if you miss this out
762 OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue
763 -> smallEnoughToInline unfolding -- Small enough to dup
764 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
766 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
767 -- Reason: doing so risks exponential behaviour. We simplify a big
768 -- expression, inline it, and simplify it again. But if the
769 -- very same thing happens in the big expression, we get
771 -- PRINCIPLE: when we've already simplified an expression once,
772 -- make sure that we only inline it if it's reasonably small.
774 && ((isNotTopLevel top_lvl && not in_lam) ||
775 -- But outside a lambda, we want to be reasonably aggressive
776 -- about inlining into multiple branches of case
777 -- e.g. let x = <non-value>
778 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
779 -- Inlining can be a big win if C3 is the hot-spot, even if
780 -- the uses in C1, C2 are not 'interesting'
781 -- An example that gets worse if you add int_cxt here is 'clausify'
783 (isCheapUnfolding unfolding && int_cxt))
784 -- isCheap => acceptable work duplication; in_lam may be true
785 -- int_cxt to prevent us inlining inside a lambda without some
786 -- good reason. See the notes on int_cxt in preInlineUnconditionally
788 IAmDead -> True -- This happens; for example, the case_bndr during case of
789 -- known constructor: case (a,b) of x { (p,q) -> ... }
790 -- Here x isn't mentioned in the RHS, so we don't want to
791 -- create the (dead) let-binding let x = (a,b) in ...
795 -- Here's an example that we don't handle well:
796 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
797 -- in \y. ....case f of {...} ....
798 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
800 -- - We can't preInlineUnconditionally because that woud invalidate
801 -- the occ info for b.
802 -- - We can't postInlineUnconditionally because the RHS is big, and
803 -- that risks exponential behaviour
804 -- - We can't call-site inline, because the rhs is big
808 active = case getMode env of
809 SimplGently {} -> isEarlyActive act
810 -- See Note [pre/postInlineUnconditionally in gentle mode]
811 SimplPhase n _ -> isActive n act
812 act = idInlineActivation bndr
814 activeUnfolding :: SimplEnv -> IdUnfoldingFun
816 = case getMode env of
817 SimplGently { sm_inline = False } -> active_unfolding_minimal
818 SimplGently { sm_inline = True } -> active_unfolding_gentle
819 SimplPhase n _ -> active_unfolding n
821 activeUnfInRule :: SimplEnv -> IdUnfoldingFun
822 -- When matching in RULE, we want to "look through" an unfolding
823 -- if *rules* are on, even if *inlinings* are not. A notable example
824 -- is DFuns, which really we want to match in rules like (op dfun)
827 = case getMode env of
828 SimplGently { sm_rules = False } -> active_unfolding_minimal
829 SimplGently { sm_rules = True } -> active_unfolding_gentle
830 SimplPhase n _ -> active_unfolding n
832 active_unfolding_minimal :: IdUnfoldingFun
833 -- Compuslory unfoldings only
834 -- Ignore SimplGently, because we want to inline regardless;
835 -- the Id has no top-level binding at all
837 -- NB: we used to have a second exception, for data con wrappers.
838 -- On the grounds that we use gentle mode for rule LHSs, and
839 -- they match better when data con wrappers are inlined.
840 -- But that only really applies to the trivial wrappers (like (:)),
841 -- and they are now constructed as Compulsory unfoldings (in MkId)
842 -- so they'll happen anyway.
843 active_unfolding_minimal id
844 | isCompulsoryUnfolding unf = unf
845 | otherwise = NoUnfolding
847 unf = realIdUnfolding id -- Never a loop breaker
849 active_unfolding_gentle :: IdUnfoldingFun
850 -- Anything that is early-active
851 -- See Note [Gentle mode]
852 active_unfolding_gentle id
853 | isEarlyActive (idInlineActivation id) = idUnfolding id
854 | otherwise = NoUnfolding
855 -- idUnfolding checks for loop-breakers
856 -- Things with an INLINE pragma may have
857 -- an unfolding *and* be a loop breaker
858 -- (maybe the knot is not yet untied)
860 active_unfolding :: CompilerPhase -> IdUnfoldingFun
861 active_unfolding n id
862 | isActive n (idInlineActivation id) = idUnfolding id
863 | otherwise = NoUnfolding
865 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
866 -- Nothing => No rules at all
867 activeRule dflags env
868 | not (dopt Opt_EnableRewriteRules dflags)
869 = Nothing -- Rewriting is off
871 = case getMode env of
872 SimplGently { sm_rules = rules_on }
873 | rules_on -> Just isEarlyActive -- Note [RULEs enabled in SimplGently]
874 | otherwise -> Nothing
875 SimplPhase n _ -> Just (isActive n)
878 Note [InlineRule and postInlineUnconditionally]
879 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
880 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
881 we lose the unfolding. Example
883 -- f has InlineRule with rhs (e |> co)
887 Then there's a danger we'll optimise to
892 and now postInlineUnconditionally, losing the InlineRule on f. Now f'
893 won't inline because 'e' is too big.
896 %************************************************************************
900 %************************************************************************
903 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
904 -- mkLam tries three things
905 -- a) eta reduction, if that gives a trivial expression
906 -- b) eta expansion [only if there are some value lambdas]
911 = do { dflags <- getDOptsSmpl
912 ; mkLam' dflags bndrs body }
914 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
915 mkLam' dflags bndrs (Cast body co)
916 | not (any bad bndrs)
917 -- Note [Casts and lambdas]
918 = do { lam <- mkLam' dflags bndrs body
919 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
921 co_vars = tyVarsOfType co
922 bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars
924 mkLam' dflags bndrs body
925 | dopt Opt_DoEtaReduction dflags,
926 Just etad_lam <- tryEtaReduce bndrs body
927 = do { tick (EtaReduction (head bndrs))
930 | dopt Opt_DoLambdaEtaExpansion dflags,
931 not (inGentleMode env), -- In gentle mode don't eta-expansion
932 any isRuntimeVar bndrs -- because it can clutter up the code
933 -- with casts etc that may not be removed
934 = do { let body' = tryEtaExpansion dflags body
935 ; return (mkLams bndrs body') }
938 = return (mkLams bndrs body)
941 Note [Casts and lambdas]
942 ~~~~~~~~~~~~~~~~~~~~~~~~
944 (\x. (\y. e) `cast` g1) `cast` g2
945 There is a danger here that the two lambdas look separated, and the
946 full laziness pass might float an expression to between the two.
948 So this equation in mkLam' floats the g1 out, thus:
949 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
952 In general, this floats casts outside lambdas, where (I hope) they
953 might meet and cancel with some other cast:
954 \x. e `cast` co ===> (\x. e) `cast` (tx -> co)
955 /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co)
956 /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co)
959 Notice that it works regardless of 'e'. Originally it worked only
960 if 'e' was itself a lambda, but in some cases that resulted in
961 fruitless iteration in the simplifier. A good example was when
962 compiling Text.ParserCombinators.ReadPrec, where we had a definition
963 like (\x. Get `cast` g)
964 where Get is a constructor with nonzero arity. Then mkLam eta-expanded
965 the Get, and the next iteration eta-reduced it, and then eta-expanded
968 Note also the side condition for the case of coercion binders.
969 It does not make sense to transform
970 /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g)
971 because the latter is not well-kinded.
973 -- c) floating lets out through big lambdas
974 -- [only if all tyvar lambdas, and only if this lambda
975 -- is the RHS of a let]
977 {- Sept 01: I'm experimenting with getting the
978 full laziness pass to float out past big lambdsa
979 | all isTyVar bndrs, -- Only for big lambdas
980 contIsRhs cont -- Only try the rhs type-lambda floating
981 -- if this is indeed a right-hand side; otherwise
982 -- we end up floating the thing out, only for float-in
983 -- to float it right back in again!
984 = do (floats, body') <- tryRhsTyLam env bndrs body
985 return (floats, mkLams bndrs body')
989 %************************************************************************
993 %************************************************************************
995 Note [Eta reduction conditions]
996 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
997 We try for eta reduction here, but *only* if we get all the way to an
998 trivial expression. We don't want to remove extra lambdas unless we
999 are going to avoid allocating this thing altogether.
1001 There are some particularly delicate points here:
1003 * Eta reduction is not valid in general:
1005 This matters, partly for old-fashioned correctness reasons but,
1006 worse, getting it wrong can yield a seg fault. Consider
1008 h y = case (case y of { True -> f `seq` True; False -> False }) of
1009 True -> ...; False -> ...
1011 If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
1012 says f=bottom, and replaces the (f `seq` True) with just
1013 (f `cast` unsafe-co). BUT, as thing stand, 'f' got arity 1, and it
1014 *keeps* arity 1 (perhaps also wrongly). So CorePrep eta-expands
1015 the definition again, so that it does not termninate after all.
1016 Result: seg-fault because the boolean case actually gets a function value.
1019 So it's important to to the right thing.
1021 * Note [Arity care]: we need to be careful if we just look at f's
1022 arity. Currently (Dec07), f's arity is visible in its own RHS (see
1023 Note [Arity robustness] in SimplEnv) so we must *not* trust the
1024 arity when checking that 'f' is a value. Otherwise we will
1029 Which might change a terminiating program (think (f `seq` e)) to a
1030 non-terminating one. So we check for being a loop breaker first.
1032 However for GlobalIds we can look at the arity; and for primops we
1033 must, since they have no unfolding.
1035 * Regardless of whether 'f' is a value, we always want to
1036 reduce (/\a -> f a) to f
1037 This came up in a RULE: foldr (build (/\a -> g a))
1038 did not match foldr (build (/\b -> ...something complex...))
1039 The type checker can insert these eta-expanded versions,
1040 with both type and dictionary lambdas; hence the slightly
1043 * Never *reduce* arity. For example
1045 Then if h has arity 1 we don't want to eta-reduce because then
1046 f's arity would decrease, and that is bad
1048 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1052 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
1053 tryEtaReduce bndrs body
1054 = go (reverse bndrs) body
1056 incoming_arity = count isId bndrs
1058 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
1059 go [] fun | ok_fun fun = Just fun -- Success!
1060 go _ _ = Nothing -- Failure!
1062 -- Note [Eta reduction conditions]
1063 ok_fun (App fun (Type ty))
1064 | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1067 = not (fun_id `elem` bndrs)
1068 && (ok_fun_id fun_id || all ok_lam bndrs)
1071 ok_fun_id fun = fun_arity fun >= incoming_arity
1073 fun_arity fun -- See Note [Arity care]
1074 | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1075 | otherwise = idArity fun
1077 ok_lam v = isTyVar v || isDictId v
1079 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
1083 %************************************************************************
1087 %************************************************************************
1091 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
1094 where (in both cases)
1096 * The xi can include type variables
1098 * The yi are all value variables
1100 * N is a NORMAL FORM (i.e. no redexes anywhere)
1101 wanting a suitable number of extra args.
1103 The biggest reason for doing this is for cases like
1109 Here we want to get the lambdas together. A good exmaple is the nofib
1110 program fibheaps, which gets 25% more allocation if you don't do this
1113 We may have to sandwich some coerces between the lambdas
1114 to make the types work. exprEtaExpandArity looks through coerces
1115 when computing arity; and etaExpand adds the coerces as necessary when
1116 actually computing the expansion.
1119 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1120 -- There is at least one runtime binder in the binders
1121 tryEtaExpansion dflags body
1122 = etaExpand fun_arity body
1124 fun_arity = exprEtaExpandArity dflags body
1128 %************************************************************************
1130 \subsection{Floating lets out of big lambdas}
1132 %************************************************************************
1134 Note [Floating and type abstraction]
1135 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1138 We'd like to float this to
1141 x = /\a. C (y1 a) (y2 a)
1142 for the usual reasons: we want to inline x rather vigorously.
1144 You may think that this kind of thing is rare. But in some programs it is
1145 common. For example, if you do closure conversion you might get:
1147 data a :-> b = forall e. (e -> a -> b) :$ e
1149 f_cc :: forall a. a :-> a
1150 f_cc = /\a. (\e. id a) :$ ()
1152 Now we really want to inline that f_cc thing so that the
1153 construction of the closure goes away.
1155 So I have elaborated simplLazyBind to understand right-hand sides that look
1159 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1160 but there is quite a bit of plumbing in simplLazyBind as well.
1162 The same transformation is good when there are lets in the body:
1164 /\abc -> let(rec) x = e in b
1166 let(rec) x' = /\abc -> let x = x' a b c in e
1168 /\abc -> let x = x' a b c in b
1170 This is good because it can turn things like:
1172 let f = /\a -> letrec g = ... g ... in g
1174 letrec g' = /\a -> ... g' a ...
1176 let f = /\ a -> g' a
1178 which is better. In effect, it means that big lambdas don't impede
1181 This optimisation is CRUCIAL in eliminating the junk introduced by
1182 desugaring mutually recursive definitions. Don't eliminate it lightly!
1184 [May 1999] If we do this transformation *regardless* then we can
1185 end up with some pretty silly stuff. For example,
1188 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1193 st = /\s -> ...[y1 s/x1, y2 s/x2]
1196 Unless the "..." is a WHNF there is really no point in doing this.
1197 Indeed it can make things worse. Suppose x1 is used strictly,
1200 x1* = case f y of { (a,b) -> e }
1202 If we abstract this wrt the tyvar we then can't do the case inline
1203 as we would normally do.
1205 That's why the whole transformation is part of the same process that
1206 floats let-bindings and constructor arguments out of RHSs. In particular,
1207 it is guarded by the doFloatFromRhs call in simplLazyBind.
1211 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1212 abstractFloats main_tvs body_env body
1213 = ASSERT( notNull body_floats )
1214 do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1215 ; return (float_binds, CoreSubst.substExpr subst body) }
1217 main_tv_set = mkVarSet main_tvs
1218 body_floats = getFloats body_env
1219 empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1221 abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1222 abstract subst (NonRec id rhs)
1223 = do { (poly_id, poly_app) <- mk_poly tvs_here id
1224 ; let poly_rhs = mkLams tvs_here rhs'
1225 subst' = CoreSubst.extendIdSubst subst id poly_app
1226 ; return (subst', (NonRec poly_id poly_rhs)) }
1228 rhs' = CoreSubst.substExpr subst rhs
1229 tvs_here | any isCoVar main_tvs = main_tvs -- Note [Abstract over coercions]
1231 = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1233 -- Abstract only over the type variables free in the rhs
1234 -- wrt which the new binding is abstracted. But the naive
1235 -- approach of abstract wrt the tyvars free in the Id's type
1237 -- /\ a b -> let t :: (a,b) = (e1, e2)
1240 -- Here, b isn't free in x's type, but we must nevertheless
1241 -- abstract wrt b as well, because t's type mentions b.
1242 -- Since t is floated too, we'd end up with the bogus:
1243 -- poly_t = /\ a b -> (e1, e2)
1244 -- poly_x = /\ a -> fst (poly_t a *b*)
1245 -- So for now we adopt the even more naive approach of
1246 -- abstracting wrt *all* the tyvars. We'll see if that
1247 -- gives rise to problems. SLPJ June 98
1249 abstract subst (Rec prs)
1250 = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1251 ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1252 poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1253 ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1255 (ids,rhss) = unzip prs
1256 -- For a recursive group, it's a bit of a pain to work out the minimal
1257 -- set of tyvars over which to abstract:
1258 -- /\ a b c. let x = ...a... in
1259 -- letrec { p = ...x...q...
1260 -- q = .....p...b... } in
1262 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1263 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.
1264 -- Since it's a pain, we just use the whole set, which is always safe
1266 -- If you ever want to be more selective, remember this bizarre case too:
1268 -- Here, we must abstract 'x' over 'a'.
1271 mk_poly tvs_here var
1272 = do { uniq <- getUniqueM
1273 ; let poly_name = setNameUnique (idName var) uniq -- Keep same name
1274 poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
1275 poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1276 mkLocalId poly_name poly_ty
1277 ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1278 -- In the olden days, it was crucial to copy the occInfo of the original var,
1279 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1280 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1281 -- at already simplified code, so it doesn't matter
1283 -- It's even right to retain single-occurrence or dead-var info:
1284 -- Suppose we started with /\a -> let x = E in B
1285 -- where x occurs once in B. Then we transform to:
1286 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1287 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1288 -- the occurrences of x' will be just the occurrences originally
1292 Note [Abstract over coercions]
1293 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1294 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1295 type variable a. Rather than sort this mess out, we simply bale out and abstract
1296 wrt all the type variables if any of them are coercion variables.
1299 Historical note: if you use let-bindings instead of a substitution, beware of this:
1301 -- Suppose we start with:
1303 -- x = /\ a -> let g = G in E
1305 -- Then we'll float to get
1307 -- x = let poly_g = /\ a -> G
1308 -- in /\ a -> let g = poly_g a in E
1310 -- But now the occurrence analyser will see just one occurrence
1311 -- of poly_g, not inside a lambda, so the simplifier will
1312 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1313 -- (I used to think that the "don't inline lone occurrences" stuff
1314 -- would stop this happening, but since it's the *only* occurrence,
1315 -- PreInlineUnconditionally kicks in first!)
1317 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1318 -- to appear many times. (NB: mkInlineMe eliminates
1319 -- such notes on trivial RHSs, so do it manually.)
1321 %************************************************************************
1325 %************************************************************************
1327 prepareAlts tries these things:
1329 1. Eliminate alternatives that cannot match, including the
1330 DEFAULT alternative.
1332 2. If the DEFAULT alternative can match only one possible constructor,
1333 then make that constructor explicit.
1335 case e of x { DEFAULT -> rhs }
1337 case e of x { (a,b) -> rhs }
1338 where the type is a single constructor type. This gives better code
1339 when rhs also scrutinises x or e.
1341 3. Returns a list of the constructors that cannot holds in the
1342 DEFAULT alternative (if there is one)
1344 Here "cannot match" includes knowledge from GADTs
1346 It's a good idea do do this stuff before simplifying the alternatives, to
1347 avoid simplifying alternatives we know can't happen, and to come up with
1348 the list of constructors that are handled, to put into the IdInfo of the
1349 case binder, for use when simplifying the alternatives.
1351 Eliminating the default alternative in (1) isn't so obvious, but it can
1354 data Colour = Red | Green | Blue
1363 DEFAULT -> [ case y of ... ]
1365 If we inline h into f, the default case of the inlined h can't happen.
1366 If we don't notice this, we may end up filtering out *all* the cases
1367 of the inner case y, which give us nowhere to go!
1370 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1371 prepareAlts scrut case_bndr' alts
1372 = do { let (alts_wo_default, maybe_deflt) = findDefault alts
1373 alt_cons = [con | (con,_,_) <- alts_wo_default]
1374 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1375 -- "imposs_deflt_cons" are handled
1376 -- EITHER by the context,
1377 -- OR by a non-DEFAULT branch in this case expression.
1379 ; default_alts <- prepareDefault case_bndr' mb_tc_app
1380 imposs_deflt_cons maybe_deflt
1382 ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1383 merged_alts = mergeAlts trimmed_alts default_alts
1384 -- We need the mergeAlts in case the new default_alt
1385 -- has turned into a constructor alternative.
1386 -- The merge keeps the inner DEFAULT at the front, if there is one
1387 -- and interleaves the alternatives in the right order
1389 ; return (imposs_deflt_cons, merged_alts) }
1391 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1392 Just (_, inst_tys) = mb_tc_app
1394 imposs_cons = case scrut of
1395 Var v -> otherCons (idUnfolding v)
1398 impossible_alt :: CoreAlt -> Bool
1399 impossible_alt (con, _, _) | con `elem` imposs_cons = True
1400 impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1401 impossible_alt _ = False
1404 prepareDefault :: OutId -- Case binder; need just for its type. Note that as an
1405 -- OutId, it has maximum information; this is important.
1406 -- Test simpl013 is an example
1407 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1408 -> [AltCon] -- These cons can't happen when matching the default
1409 -> Maybe InExpr -- Rhs
1410 -> SimplM [InAlt] -- Still unsimplified
1411 -- We use a list because it's what mergeAlts expects,
1413 --------- Fill in known constructor -----------
1414 prepareDefault case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1415 | -- This branch handles the case where we are
1416 -- scrutinisng an algebraic data type
1417 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1418 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1419 -- case x of { DEFAULT -> e }
1420 -- and we don't want to fill in a default for them!
1421 , Just all_cons <- tyConDataCons_maybe tycon
1422 , not (null all_cons) -- This is a tricky corner case. If the data type has no constructors,
1423 -- which GHC allows, then the case expression will have at most a default
1424 -- alternative. We don't want to eliminate that alternative, because the
1425 -- invariant is that there's always one alternative. It's more convenient
1427 -- case x of { DEFAULT -> e }
1428 -- as it is, rather than transform it to
1429 -- error "case cant match"
1430 -- which would be quite legitmate. But it's a really obscure corner, and
1431 -- not worth wasting code on.
1432 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1433 impossible con = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1434 = case filterOut impossible all_cons of
1435 [] -> return [] -- Eliminate the default alternative
1436 -- altogether if it can't match
1438 [con] -> -- It matches exactly one constructor, so fill it in
1439 do { tick (FillInCaseDefault case_bndr)
1441 ; let (ex_tvs, co_tvs, arg_ids) =
1442 dataConRepInstPat us con inst_tys
1443 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1445 _ -> return [(DEFAULT, [], deflt_rhs)]
1447 | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1448 -- Check for no data constructors
1449 -- This can legitimately happen for type families, so don't report that
1450 = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1451 $ return [(DEFAULT, [], deflt_rhs)]
1453 --------- Catch-all cases -----------
1454 prepareDefault _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1455 = return [(DEFAULT, [], deflt_rhs)]
1457 prepareDefault _case_bndr _bndr_ty _imposs_cons Nothing
1458 = return [] -- No default branch
1463 %************************************************************************
1467 %************************************************************************
1469 mkCase tries these things
1471 1. Merge Nested Cases
1473 case e of b { ==> case e of b {
1474 p1 -> rhs1 p1 -> rhs1
1476 pm -> rhsm pm -> rhsm
1477 _ -> case b of b' { pn -> let b'=b in rhsn
1479 ... po -> let b'=b in rhso
1480 po -> rhso _ -> let b'=b in rhsd
1484 which merges two cases in one case when -- the default alternative of
1485 the outer case scrutises the same variable as the outer case. This
1486 transformation is called Case Merging. It avoids that the same
1487 variable is scrutinised multiple times.
1489 2. Eliminate Identity Case
1495 and similar friends.
1497 3. Merge identical alternatives.
1498 If several alternatives are identical, merge them into
1499 a single DEFAULT alternative. I've occasionally seen this
1500 making a big difference:
1502 case e of =====> case e of
1503 C _ -> f x D v -> ....v....
1504 D v -> ....v.... DEFAULT -> f x
1507 The point is that we merge common RHSs, at least for the DEFAULT case.
1508 [One could do something more elaborate but I've never seen it needed.]
1509 To avoid an expensive test, we just merge branches equal to the *first*
1510 alternative; this picks up the common cases
1511 a) all branches equal
1512 b) some branches equal to the DEFAULT (which occurs first)
1514 The case where Merge Identical Alternatives transformation showed up
1515 was like this (base/Foreign/C/Err/Error.lhs):
1521 where @is@ was something like
1523 p `is` n = p /= (-1) && p == n
1525 This gave rise to a horrible sequence of cases
1532 and similarly in cascade for all the join points!
1536 mkCase, mkCase1, mkCase2
1539 -> [OutAlt] -- Alternatives in standard (increasing) order
1542 --------------------------------------------------
1543 -- 1. Merge Nested Cases
1544 --------------------------------------------------
1546 mkCase dflags scrut outer_bndr ((DEFAULT, _, deflt_rhs) : outer_alts)
1547 | dopt Opt_CaseMerge dflags
1548 , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1549 , inner_scrut_var == outer_bndr
1550 = do { tick (CaseMerge outer_bndr)
1552 ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args )
1553 (con, args, wrap_rhs rhs)
1554 -- Simplifier's no-shadowing invariant should ensure
1555 -- that outer_bndr is not shadowed by the inner patterns
1556 wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs
1557 -- The let is OK even for unboxed binders,
1559 wrapped_alts | isDeadBinder inner_bndr = inner_alts
1560 | otherwise = map wrap_alt inner_alts
1562 merged_alts = mergeAlts outer_alts wrapped_alts
1563 -- NB: mergeAlts gives priority to the left
1566 -- DEFAULT -> case x of
1569 -- When we merge, we must ensure that e1 takes
1570 -- precedence over e2 as the value for A!
1572 ; mkCase1 dflags scrut outer_bndr merged_alts
1574 -- Warning: don't call mkCase recursively!
1575 -- Firstly, there's no point, because inner alts have already had
1576 -- mkCase applied to them, so they won't have a case in their default
1577 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1578 -- in munge_rhs may put a case into the DEFAULT branch!
1580 mkCase dflags scrut bndr alts = mkCase1 dflags scrut bndr alts
1582 --------------------------------------------------
1583 -- 2. Eliminate Identity Case
1584 --------------------------------------------------
1586 mkCase1 _dflags scrut case_bndr alts -- Identity case
1587 | all identity_alt alts
1588 = do { tick (CaseIdentity case_bndr)
1589 ; return (re_cast scrut) }
1591 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1593 check_eq DEFAULT _ (Var v) = v == case_bndr
1594 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1595 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1596 || rhs `cheapEqExpr` Var case_bndr
1597 check_eq _ _ _ = False
1599 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1602 -- case e of x { _ -> x `cast` c }
1603 -- And we definitely want to eliminate this case, to give
1605 -- So we throw away the cast from the RHS, and reconstruct
1606 -- it at the other end. All the RHS casts must be the same
1607 -- if (all identity_alt alts) holds.
1609 -- Don't worry about nested casts, because the simplifier combines them
1610 de_cast (Cast e _) = e
1613 re_cast scrut = case head alts of
1614 (_,_,Cast _ co) -> Cast scrut co
1617 --------------------------------------------------
1618 -- 3. Merge Identical Alternatives
1619 --------------------------------------------------
1620 mkCase1 dflags scrut case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1621 | all isDeadBinder bndrs1 -- Remember the default
1622 , length filtered_alts < length con_alts -- alternative comes first
1623 -- Also Note [Dead binders]
1624 = do { tick (AltMerge case_bndr)
1625 ; mkCase2 dflags scrut case_bndr alts' }
1627 alts' = (DEFAULT, [], rhs1) : filtered_alts
1628 filtered_alts = filter keep con_alts
1629 keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1631 mkCase1 dflags scrut bndr alts = mkCase2 dflags scrut bndr alts
1633 --------------------------------------------------
1635 --------------------------------------------------
1636 mkCase2 _dflags scrut bndr alts
1637 = return (Case scrut bndr (coreAltsType alts) alts)
1641 ~~~~~~~~~~~~~~~~~~~~
1642 Note that dead-ness is maintained by the simplifier, so that it is
1643 accurate after simplification as well as before.
1646 Note [Cascading case merge]
1647 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1648 Case merging should cascade in one sweep, because it
1652 DEFAULT -> case a of b
1653 DEFAULT -> case b of c {
1660 DEFAULT -> case a of b
1661 DEFAULT -> let c = b in e
1662 A -> let c = b in ea
1667 DEFAULT -> let b = a in let c = b in e
1668 A -> let b = a in let c = b in ea
1669 B -> let b = a in eb
1673 However here's a tricky case that we still don't catch, and I don't
1674 see how to catch it in one pass:
1676 case x of c1 { I# a1 ->
1679 DEFAULT -> case x of c3 { I# a2 ->
1682 After occurrence analysis (and its binder-swap) we get this
1684 case x of c1 { I# a1 ->
1685 let x = c1 in -- Binder-swap addition
1688 DEFAULT -> case x of c3 { I# a2 ->
1691 When we simplify the inner case x, we'll see that
1692 x=c1=I# a1. So we'll bind a2 to a1, and get
1694 case x of c1 { I# a1 ->
1697 DEFAULT -> case a1 of ...
1699 This is corect, but we can't do a case merge in this sweep
1700 because c2 /= a1. Reason: the binding c1=I# a1 went inwards
1701 without getting changed to c1=I# c2.
1703 I don't think this is worth fixing, even if I knew how. It'll
1704 all come out in the next pass anyway.