Adjust Activations for specialise and work/wrap, and better simplify in InlineRules
[ghc-hetmet.git] / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 module SimplUtils (
8         -- Rebuilding
9         mkLam, mkCase, prepareAlts, 
10
11         -- Inlining,
12         preInlineUnconditionally, postInlineUnconditionally, 
13         activeUnfolding, activeUnfInRule, activeRule, 
14         simplEnvForGHCi, simplEnvForRules, updModeForInlineRules,
15
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, 
22
23         interestingArg, mkArgInfo,
24         
25         abstractFloats
26     ) where
27
28 #include "HsVersions.h"
29
30 import SimplEnv
31 import DynFlags
32 import StaticFlags
33 import CoreSyn
34 import qualified CoreSubst
35 import PprCore
36 import CoreFVs
37 import CoreUtils
38 import CoreArity        ( etaExpand, exprEtaExpandArity )
39 import CoreUnfold
40 import Name
41 import Id
42 import Var      ( isCoVar )
43 import Demand
44 import SimplMonad
45 import Type     hiding( substTy )
46 import Coercion ( coercionKind )
47 import TyCon
48 import Unify    ( dataConCannotMatch )
49 import VarSet
50 import BasicTypes
51 import Util
52 import MonadUtils
53 import Outputable
54 import FastString
55
56 import Data.List
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62                 The SimplCont type
63 %*                                                                      *
64 %************************************************************************
65
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.
69
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
76 the comments.
77
78
79 Key points:
80   * A SimplCont describes a *strict* context (just like 
81     evaluation contexts do).  E.g. Just [] is not a SimplCont
82
83   * A SimplCont describes a context that *does not* bind
84     any variables.  E.g. \x. [] is not a SimplCont
85
86 \begin{code}
87 data 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)
92                         -- Specifically:
93                         --     This is an argument of a function that has RULES
94                         --     Inlining the call might allow the rule to fire
95
96   | CoerceIt            -- C `cast` co
97         OutCoercion             -- The coercion simplified
98         SimplCont
99
100   | ApplyTo             -- C arg
101         DupFlag 
102         InExpr StaticEnv                -- The argument and its static env
103         SimplCont
104
105   | Select              -- case C of alts
106         DupFlag 
107         InId [InAlt] StaticEnv  -- The case binder, alts, and subst-env
108         SimplCont
109
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 
114         SimplCont       
115
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
120         SimplCont               
121
122 data ArgInfo 
123   = ArgInfo {
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
127
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
131         
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
137                                 --   Always infinite
138     }
139
140 addArgTo :: ArgInfo -> OutExpr -> ArgInfo
141 addArgTo ai arg = ai { ai_args = arg : ai_args ai }
142
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
152
153 data DupFlag = OkToDup | NoDup
154
155 instance Outputable DupFlag where
156   ppr OkToDup = ptext (sLit "ok")
157   ppr NoDup   = ptext (sLit "nodup")
158
159
160
161 -------------------
162 mkBoringStop :: SimplCont
163 mkBoringStop = Stop BoringCtxt
164
165 mkRhsStop :: SimplCont  -- See Note [RHS of lets] in CoreUnfold
166 mkRhsStop = Stop (ArgCtxt False)
167
168 mkLazyArgStop :: CallCtxt -> SimplCont
169 mkLazyArgStop cci = Stop cci
170
171 -------------------
172 contIsRhsOrArg :: SimplCont -> Bool
173 contIsRhsOrArg (Stop {})       = True
174 contIsRhsOrArg (StrictBind {}) = True
175 contIsRhsOrArg (StrictArg {})  = True
176 contIsRhsOrArg _               = False
177
178 -------------------
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
185
186 -------------------
187 contIsTrivial :: SimplCont -> Bool
188 contIsTrivial (Stop {})                   = True
189 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
190 contIsTrivial (CoerceIt _ cont)           = contIsTrivial cont
191 contIsTrivial _                           = False
192
193 -------------------
194 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
195 contResultType env ty cont
196   = go cont ty
197   where
198     subst_ty se ty = substTy (se `setInScope` env) ty
199
200     go (Stop {})                      ty = 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)
206
207     apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
208     apply_to_arg ty _             _  = funResultTy ty
209
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
213
214 -------------------
215 countValArgs :: SimplCont -> Int
216 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
217 countValArgs (ApplyTo _ _        _ cont) = 1 + countValArgs cont
218 countValArgs _                           = 0
219
220 countArgs :: SimplCont -> Int
221 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
222 countArgs _                    = 0
223
224 contArgs :: SimplCont -> ([OutExpr], SimplCont)
225 -- Uses substitution to turn each arg into an OutExpr
226 contArgs cont = go [] cont
227   where
228     go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
229     go args cont                    = (reverse args, cont)
230
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)
234
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)
239 \end{code}
240
241
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.  
248
249 Previously some_benefit used to return True only if the variable was
250 applied to some value arguments.  This didn't work:
251
252         let x = _coerce_ (T Int) Int (I# 3) in
253         case _coerce_ Int (T Int) x of
254                 I# y -> ....
255
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.
258
259 Another example:
260
261 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
262
263 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
264
265 we'd really like to inline dMonadST here, but we *don't* want to
266 inline if the case expression is just
267
268         case x of y { DEFAULT -> ... }
269
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
273 default case.
274
275
276 \begin{code}
277 interestingCallContext :: SimplCont -> CallCtxt
278 -- See Note [Interesting call context]
279 interestingCallContext cont
280   = interesting cont
281   where
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
287                 
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]
293                                         -- in CoreUnfold
294
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.
302         --      x + (y * z)
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.
306         --
307         -- It's also very important to inline in a strict context for things
308         -- like
309         --              foldr k z (f x)
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.
313
314
315 -------------------
316 mkArgInfo :: Id
317           -> [CoreRule] -- Rules for function
318           -> Int        -- Number of value args
319           -> SimplCont  -- Context of the call
320           -> ArgInfo
321
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
325             , ai_encl = False
326             , ai_strs = vanilla_stricts 
327             , ai_discs = vanilla_discounts }
328   | otherwise
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 }
333   where
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
340
341     vanilla_stricts, arg_stricts :: [Bool]
342     vanilla_stricts  = repeat False
343
344     arg_stricts
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
357                    else
358                         map isStrictDmd demands ++ vanilla_stricts
359                | otherwise
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
363
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
378     add_type_str _ strs
379         = strs
380
381 {- Note [Unsaturated functions]
382   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 Consider (test eyeball/inline4)
384         x = a:as
385         y = f x
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
389 -}
390
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
395 --      g (f x y) 
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
398 --      h (g (f x x))
399 -- where h has rules, then we do want to inline f; hence the
400 -- call_cont argument to interestingArgContext
401 --
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
405 --
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
411   where
412     enclosing_fn_has_rules = go call_cont
413
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
420
421     interesting (ArgCtxt rules) = rules
422     interesting _               = False
423 \end{code}
424
425
426
427 %************************************************************************
428 %*                                                                      *
429 \subsection{Decisions about inlining}
430 %*                                                                      *
431 %************************************************************************
432
433 Inlining is controlled partly by the SimplifierMode switch.  This has two
434 settings
435         
436         SimplGently     (a) Simplifying before specialiser/full laziness
437                         (b) Simplifiying inside InlineRules
438                         (c) Simplifying the LHS of a rule
439                         (d) Simplifying a GHCi expression or Template 
440                                 Haskell splice
441
442         SimplPhase n _   Used at all other times
443
444 Note [Gentle mode]
445 ~~~~~~~~~~~~~~~~~~
446 Gentle mode has a separate boolean flag to control
447         a) inlining (sm_inline flag)
448         b) rules    (sm_rules  flag)
449 A key invariant about Gentle mode is that it is treated as the EARLIEST
450 phase.  Something is inlined if the sm_inline flag is on AND the thing
451 is inlinable in the earliest phase.  This is important. Example
452
453   {-# INLINE [~1] g #-}
454   g = ...
455   
456   {-# INLINE f #-}
457   f x = g (g x)
458
459 If we were to inline g into f's inlining, then an importing module would
460 never be able to do
461         f e --> g (g e) ---> RULE fires
462 because the InlineRule for f has had g inlined into it.
463
464 On the other hand, it is bad not to do ANY inlining into an
465 InlineRule, because then recursive knots in instance declarations
466 don't get unravelled.
467
468 However, *sometimes* SimplGently must do no call-site inlining at all.
469 Before full laziness we must be careful not to inline wrappers,
470 because doing so inhibits floating
471     e.g. ...(case f x of ...)...
472     ==> ...(case (case x of I# x# -> fw x#) of ...)...
473     ==> ...(case x of I# x# -> case fw x# of ...)...
474 and now the redex (f x) isn't floatable any more.
475
476 The no-inlining thing is also important for Template Haskell.  You might be 
477 compiling in one-shot mode with -O2; but when TH compiles a splice before
478 running it, we don't want to use -O2.  Indeed, we don't want to inline
479 anything, because the byte-code interpreter might get confused about 
480 unboxed tuples and suchlike.
481
482 Note [RULEs enabled in SimplGently]
483 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
484 RULES are enabled when doing "gentle" simplification.  Two reasons:
485
486   * We really want the class-op cancellation to happen:
487         op (df d1 d2) --> $cop3 d1 d2
488     because this breaks the mutual recursion between 'op' and 'df'
489
490   * I wanted the RULE
491         lift String ===> ...
492     to work in Template Haskell when simplifying
493     splices, so we get simpler code for literal strings
494
495 Note [Simplifying inside InlineRules]
496 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
497 We must take care with simplification inside InlineRules (which come from
498 INLINE pragmas).  
499
500 First, consider the following example
501         let f = \pq -> BIG
502         in
503         let g = \y -> f y y
504             {-# INLINE g #-}
505         in ...g...g...g...g...g...
506 Now, if that's the ONLY occurrence of f, it might be inlined inside g,
507 and thence copied multiple times when g is inlined. HENCE we treat
508 any occurrence in an InlineRule as a multiple occurrence, not a single
509 one; see OccurAnal.addRuleUsage.
510
511 Second, we do want *do* to some modest rules/inlining stuff in InlineRules,
512 partly to eliminate senseless crap, and partly to break the recursive knots
513 generated by instance declarations.  To keep things simple, we always set 
514 the phase to 'gentle' when processing InlineRules.  OK, so suppose we have
515         {-# INLINE <act> f #-}
516         f = <rhs>
517 meaning "inline f in phases p where activation <act>(p) holds". 
518 Then what inlinings/rules can we apply to the copy of <rhs> captured in
519 f's InlineRule?  Our model is that literally <rhs> is substituted for
520 f when it is inlined.  So our conservative plan (implemented by 
521 updModeForInlineRules) is this:
522
523   -------------------------------------------------------------
524   When simplifying the RHS of an InlineRule,
525   If the InlineRule becomes active in phase p, then
526     if the current phase is *earlier than* p, 
527        make no inlinings or rules active when simplifying the RHS
528     otherwise 
529        set the phase to p when simplifying the RHS
530   -------------------------------------------------------------
531
532 That ensures that
533
534   a) Rules/inlinings that *cease* being active before p will 
535      not apply to the InlineRule rhs, consistent with it being
536      inlined in its *original* form in phase p.
537
538   b) Rules/inlinings that only become active *after* p will
539      not apply to the InlineRule rhs, again to be consistent with
540      inlining the *original* rhs in phase p.
541
542 For example, 
543         {-# INLINE f #-}
544         f x = ...g...
545
546         {-# NOINLINE [1] g #-}
547         g y = ...
548
549         {-# RULE h g = ... #-}
550 Here we must not inline g into f's RHS, even when we get to phase 0,
551 because when f is later inlined into some other module we want the
552 rule for h to fire.
553
554 Similarly, consider
555         {-# INLINE f #-}
556         f x = ...g...
557
558         g y = ...
559 and suppose that there are auto-generated specialisations and a strictness
560 wrapper for g.  The specialisations get activation AlwaysActive, and the
561 strictness wrapper get activation (ActiveAfter 0).  So the strictness
562 wrepper fails the test and won't be inlined into f's InlineRule. That
563 means f can inline, expose the specialised call to g, so the specialisation
564 rules can fire.
565
566 A note about wrappers
567 ~~~~~~~~~~~~~~~~~~~~~
568 It's also important not to inline a worker back into a wrapper.
569 A wrapper looks like
570         wraper = inline_me (\x -> ...worker... )
571 Normally, the inline_me prevents the worker getting inlined into
572 the wrapper (initially, the worker's only call site!).  But,
573 if the wrapper is sure to be called, the strictness analyser will
574 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
575 continuation. 
576
577 \begin{code}
578 simplEnvForGHCi :: SimplEnv
579 simplEnvForGHCi = mkSimplEnv allOffSwitchChecker $
580                   SimplGently { sm_rules = False, sm_inline = False }
581    -- Do not do any inlining, in case we expose some unboxed
582    -- tuple stuff that confuses the bytecode interpreter
583
584 simplEnvForRules :: SimplEnv
585 simplEnvForRules = mkSimplEnv allOffSwitchChecker $
586                    SimplGently { sm_rules = True, sm_inline = False }
587
588 updModeForInlineRules :: Activation -> SimplifierMode -> SimplifierMode
589 -- See Note [Simplifying inside InlineRules]
590 --    Treat Gentle as phase "infinity"
591 --    If current_phase `earlier than` inline_rule_start_phase 
592 --      then no_op
593 --    else 
594 --    if current_phase `same phase` inline_rule_start_phase 
595 --      then current_phase   (keep gentle flags)
596 --      else inline_rule_start_phase
597 updModeForInlineRules inline_rule_act current_mode
598   = case inline_rule_act of
599       NeverActive     -> no_op
600       AlwaysActive    -> mk_gentle current_mode
601       ActiveBefore {} -> mk_gentle current_mode
602       ActiveAfter n   -> mk_phase n current_mode
603   where
604     no_op  = SimplGently { sm_rules = False, sm_inline = False }
605
606     mk_gentle (SimplGently {}) = current_mode
607     mk_gentle _                = SimplGently { sm_rules = True,  sm_inline = True }
608
609     mk_phase n (SimplPhase cp ss) 
610                     | cp > n    = no_op -- Current phase earlier than n
611                     | otherwise = SimplPhase n ss
612     mk_phase _ (SimplGently {}) = no_op
613 \end{code}
614
615
616 preInlineUnconditionally
617 ~~~~~~~~~~~~~~~~~~~~~~~~
618 @preInlineUnconditionally@ examines a bndr to see if it is used just
619 once in a completely safe way, so that it is safe to discard the
620 binding inline its RHS at the (unique) usage site, REGARDLESS of how
621 big the RHS might be.  If this is the case we don't simplify the RHS
622 first, but just inline it un-simplified.
623
624 This is much better than first simplifying a perhaps-huge RHS and then
625 inlining and re-simplifying it.  Indeed, it can be at least quadratically
626 better.  Consider
627
628         x1 = e1
629         x2 = e2[x1]
630         x3 = e3[x2]
631         ...etc...
632         xN = eN[xN-1]
633
634 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
635 This can happen with cascades of functions too:
636
637         f1 = \x1.e1
638         f2 = \xs.e2[f1]
639         f3 = \xs.e3[f3]
640         ...etc...
641
642 THE MAIN INVARIANT is this:
643
644         ----  preInlineUnconditionally invariant -----
645    IF preInlineUnconditionally chooses to inline x = <rhs>
646    THEN doing the inlining should not change the occurrence
647         info for the free vars of <rhs>
648         ----------------------------------------------
649
650 For example, it's tempting to look at trivial binding like
651         x = y
652 and inline it unconditionally.  But suppose x is used many times,
653 but this is the unique occurrence of y.  Then inlining x would change
654 y's occurrence info, which breaks the invariant.  It matters: y
655 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
656
657
658 Even RHSs labelled InlineMe aren't caught here, because there might be
659 no benefit from inlining at the call site.
660
661 [Sept 01] Don't unconditionally inline a top-level thing, because that
662 can simply make a static thing into something built dynamically.  E.g.
663         x = (a,b)
664         main = \s -> h x
665
666 [Remember that we treat \s as a one-shot lambda.]  No point in
667 inlining x unless there is something interesting about the call site.
668
669 But watch out: if you aren't careful, some useful foldr/build fusion
670 can be lost (most notably in spectral/hartel/parstof) because the
671 foldr didn't see the build.  Doing the dynamic allocation isn't a big
672 deal, in fact, but losing the fusion can be.  But the right thing here
673 seems to be to do a callSiteInline based on the fact that there is
674 something interesting about the call site (it's strict).  Hmm.  That
675 seems a bit fragile.
676
677 Conclusion: inline top level things gaily until Phase 0 (the last
678 phase), at which point don't.
679
680 Note [pre/postInlineUnconditionally in gentle mode]
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
682 Even in gentle mode we want to do preInlineUnconditionally.  The
683 reason is that too little clean-up happens if you don't inline
684 use-once things.  Also a bit of inlining is *good* for full laziness;
685 it can expose constant sub-expressions.  Example in
686 spectral/mandel/Mandel.hs, where the mandelset function gets a useful
687 let-float if you inline windowToViewport
688
689 However, as usual for Gentle mode, do not inline things that are
690 inactive in the intial stages.  See Note [Gentle mode].
691
692 Note [Top-level botomming Ids]
693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
694 Don't inline top-level Ids that are bottoming, even if they are used just
695 once, because FloatOut has gone to some trouble to extract them out.
696 Inlining them won't make the program run faster!
697
698 \begin{code}
699 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
700 preInlineUnconditionally env top_lvl bndr rhs
701   | not active                               = False
702   | isTopLevel top_lvl && isBottomingId bndr = False    -- Note [Top-level bottoming Ids]
703   | opt_SimplNoPreInlining                   = False
704   | otherwise = case idOccInfo bndr of
705                   IAmDead                    -> True    -- Happens in ((\x.1) v)
706                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
707                   _                          -> False
708   where
709     phase = getMode env
710     active = case phase of
711                    SimplGently {} -> isEarlyActive act
712                         -- See Note [pre/postInlineUnconditionally in gentle mode]
713                    SimplPhase n _ -> isActive n act
714     act = idInlineActivation bndr
715     try_once in_lam int_cxt     -- There's one textual occurrence
716         | not in_lam = isNotTopLevel top_lvl || early_phase
717         | otherwise  = int_cxt && canInlineInLam rhs
718
719 -- Be very careful before inlining inside a lambda, because (a) we must not 
720 -- invalidate occurrence information, and (b) we want to avoid pushing a
721 -- single allocation (here) into multiple allocations (inside lambda).  
722 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
723 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
724 --      where 
725 --              is_cheap = exprIsCheap rhs
726 --              ok = is_cheap && int_cxt
727
728         --      int_cxt         The context isn't totally boring
729         -- E.g. let f = \ab.BIG in \y. map f xs
730         --      Don't want to substitute for f, because then we allocate
731         --      its closure every time the \y is called
732         -- But: let f = \ab.BIG in \y. map (f y) xs
733         --      Now we do want to substitute for f, even though it's not 
734         --      saturated, because we're going to allocate a closure for 
735         --      (f y) every time round the loop anyhow.
736
737         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
738         -- so substituting rhs inside a lambda doesn't change the occ info.
739         -- Sadly, not quite the same as exprIsHNF.
740     canInlineInLam (Lit _)              = True
741     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
742     canInlineInLam (Note _ e)           = canInlineInLam e
743     canInlineInLam _                    = False
744
745     early_phase = case phase of
746                         SimplPhase 0 _ -> False
747                         _              -> True
748 -- If we don't have this early_phase test, consider
749 --      x = length [1,2,3]
750 -- The full laziness pass carefully floats all the cons cells to
751 -- top level, and preInlineUnconditionally floats them all back in.
752 -- Result is (a) static allocation replaced by dynamic allocation
753 --           (b) many simplifier iterations because this tickles
754 --               a related problem; only one inlining per pass
755 -- 
756 -- On the other hand, I have seen cases where top-level fusion is
757 -- lost if we don't inline top level thing (e.g. string constants)
758 -- Hence the test for phase zero (which is the phase for all the final
759 -- simplifications).  Until phase zero we take no special notice of
760 -- top level things, but then we become more leery about inlining
761 -- them.  
762
763 \end{code}
764
765 postInlineUnconditionally
766 ~~~~~~~~~~~~~~~~~~~~~~~~~
767 @postInlineUnconditionally@ decides whether to unconditionally inline
768 a thing based on the form of its RHS; in particular if it has a
769 trivial RHS.  If so, we can inline and discard the binding altogether.
770
771 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
772 only have *forward* references Hence, it's safe to discard the binding
773         
774 NOTE: This isn't our last opportunity to inline.  We're at the binding
775 site right now, and we'll get another opportunity when we get to the
776 ocurrence(s)
777
778 Note that we do this unconditional inlining only for trival RHSs.
779 Don't inline even WHNFs inside lambdas; doing so may simply increase
780 allocation when the function is called. This isn't the last chance; see
781 NOTE above.
782
783 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
784 Because we don't even want to inline them into the RHS of constructor
785 arguments. See NOTE above
786
787 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
788 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
789 with both a and b marked NOINLINE.  But that seems incompatible with
790 our new view that inlining is like a RULE, so I'm sticking to the 'active'
791 story for now.
792
793 \begin{code}
794 postInlineUnconditionally 
795     :: SimplEnv -> TopLevelFlag
796     -> OutId            -- The binder (an InId would be fine too)
797     -> OccInfo          -- From the InId
798     -> OutExpr
799     -> Unfolding
800     -> Bool
801 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
802   | not active                  = False
803   | isLoopBreaker occ_info      = False -- If it's a loop-breaker of any kind, don't inline
804                                         -- because it might be referred to "earlier"
805   | isExportedId bndr           = False
806   | isStableUnfolding unfolding = False -- Note [InlineRule and postInlineUnconditionally]
807   | exprIsTrivial rhs           = True
808   | isTopLevel top_lvl          = False -- Note [Top level and postInlineUnconditionally]
809   | otherwise
810   = case occ_info of
811         -- The point of examining occ_info here is that for *non-values* 
812         -- that occur outside a lambda, the call-site inliner won't have
813         -- a chance (becuase it doesn't know that the thing
814         -- only occurs once).   The pre-inliner won't have gotten
815         -- it either, if the thing occurs in more than one branch
816         -- So the main target is things like
817         --      let x = f y in
818         --      case v of
819         --         True  -> case x of ...
820         --         False -> case x of ...
821         -- This is very important in practice; e.g. wheel-seive1 doubles 
822         -- in allocation if you miss this out
823       OneOcc in_lam _one_br int_cxt     -- OneOcc => no code-duplication issue
824         ->     smallEnoughToInline unfolding    -- Small enough to dup
825                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
826                         --
827                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
828                         -- Reason: doing so risks exponential behaviour.  We simplify a big
829                         --         expression, inline it, and simplify it again.  But if the
830                         --         very same thing happens in the big expression, we get 
831                         --         exponential cost!
832                         -- PRINCIPLE: when we've already simplified an expression once, 
833                         -- make sure that we only inline it if it's reasonably small.
834
835            && (not in_lam || 
836                         -- Outside a lambda, we want to be reasonably aggressive
837                         -- about inlining into multiple branches of case
838                         -- e.g. let x = <non-value> 
839                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
840                         -- Inlining can be a big win if C3 is the hot-spot, even if
841                         -- the uses in C1, C2 are not 'interesting'
842                         -- An example that gets worse if you add int_cxt here is 'clausify'
843
844                 (isCheapUnfolding unfolding && int_cxt))
845                         -- isCheap => acceptable work duplication; in_lam may be true
846                         -- int_cxt to prevent us inlining inside a lambda without some 
847                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
848
849       IAmDead -> True   -- This happens; for example, the case_bndr during case of
850                         -- known constructor:  case (a,b) of x { (p,q) -> ... }
851                         -- Here x isn't mentioned in the RHS, so we don't want to
852                         -- create the (dead) let-binding  let x = (a,b) in ...
853
854       _ -> False
855
856 -- Here's an example that we don't handle well:
857 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
858 --      in \y. ....case f of {...} ....
859 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
860 -- But
861 --  - We can't preInlineUnconditionally because that woud invalidate
862 --    the occ info for b.
863 --  - We can't postInlineUnconditionally because the RHS is big, and
864 --    that risks exponential behaviour
865 --  - We can't call-site inline, because the rhs is big
866 -- Alas!
867
868   where
869     active = case getMode env of
870                    SimplGently {} -> isEarlyActive act
871                         -- See Note [pre/postInlineUnconditionally in gentle mode]
872                    SimplPhase n _ -> isActive n act
873     act = idInlineActivation bndr
874
875 activeUnfolding :: SimplEnv -> IdUnfoldingFun
876 activeUnfolding env
877   = case getMode env of
878       SimplGently { sm_inline = False } -> active_unfolding_minimal
879       SimplGently { sm_inline = True  } -> active_unfolding_gentle
880       SimplPhase n _                    -> active_unfolding n
881
882 activeUnfInRule :: SimplEnv -> IdUnfoldingFun
883 -- When matching in RULE, we want to "look through" an unfolding
884 -- if *rules* are on, even if *inlinings* are not.  A notable example
885 -- is DFuns, which really we want to match in rules like (op dfun)
886 -- in gentle mode.
887 activeUnfInRule env
888   = case getMode env of
889       SimplGently { sm_rules = False } -> active_unfolding_minimal
890       SimplGently { sm_rules = True  } -> active_unfolding_gentle
891       SimplPhase n _                   -> active_unfolding n
892
893 active_unfolding_minimal :: IdUnfoldingFun
894 -- Compuslory unfoldings only
895 -- Ignore SimplGently, because we want to inline regardless;
896 -- the Id has no top-level binding at all
897 --
898 -- NB: we used to have a second exception, for data con wrappers.
899 -- On the grounds that we use gentle mode for rule LHSs, and 
900 -- they match better when data con wrappers are inlined.
901 -- But that only really applies to the trivial wrappers (like (:)),
902 -- and they are now constructed as Compulsory unfoldings (in MkId)
903 -- so they'll happen anyway.
904 active_unfolding_minimal id
905   | isCompulsoryUnfolding unf = unf
906   | otherwise                 = NoUnfolding
907   where
908     unf = realIdUnfolding id    -- Never a loop breaker
909
910 active_unfolding_gentle :: IdUnfoldingFun
911 -- Anything that is early-active
912 -- See Note [Gentle mode]
913 active_unfolding_gentle id
914   | isEarlyActive (idInlineActivation id) = idUnfolding id
915   | otherwise                             = NoUnfolding
916       -- idUnfolding checks for loop-breakers
917       -- Things with an INLINE pragma may have 
918       -- an unfolding *and* be a loop breaker  
919       -- (maybe the knot is not yet untied)
920
921 active_unfolding :: CompilerPhase -> IdUnfoldingFun
922 active_unfolding n id
923   | isActive n (idInlineActivation id) = idUnfolding id
924   | otherwise                          = NoUnfolding
925
926 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
927 -- Nothing => No rules at all
928 activeRule dflags env
929   | not (dopt Opt_EnableRewriteRules dflags)
930   = Nothing     -- Rewriting is off
931   | otherwise
932   = case getMode env of
933       SimplGently { sm_rules = rules_on } 
934         | rules_on  -> Just isEarlyActive       -- Note [RULEs enabled in SimplGently]
935         | otherwise -> Nothing
936       SimplPhase n _ -> Just (isActive n)
937 \end{code}
938
939 Note [Top level and postInlineUnconditionally]
940 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
941 We don't do postInlineUnconditionally for top-level things (exept ones that
942 are trivial):
943   * There is no point, because the main goal is to get rid of local
944     bindings used in multiple case branches.
945   * Doing so will inline top-level error expressions that have been
946     carefully floated out by FloatOut.  More generally, it might 
947     replace static allocation with dynamic.
948
949 Note [InlineRule and postInlineUnconditionally]
950 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
951 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
952 we lose the unfolding.  Example
953
954      -- f has InlineRule with rhs (e |> co)
955      --   where 'e' is big
956      f = e |> co
957
958 Then there's a danger we'll optimise to
959
960      f' = e
961      f = f' |> co
962
963 and now postInlineUnconditionally, losing the InlineRule on f.  Now f'
964 won't inline because 'e' is too big.
965
966
967 %************************************************************************
968 %*                                                                      *
969         Rebuilding a lambda
970 %*                                                                      *
971 %************************************************************************
972
973 \begin{code}
974 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
975 -- mkLam tries three things
976 --      a) eta reduction, if that gives a trivial expression
977 --      b) eta expansion [only if there are some value lambdas]
978
979 mkLam _b [] body 
980   = return body
981 mkLam env bndrs body
982   = do  { dflags <- getDOptsSmpl
983         ; mkLam' dflags bndrs body }
984   where
985     mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
986     mkLam' dflags bndrs (Cast body co)
987       | not (any bad bndrs)
988         -- Note [Casts and lambdas]
989       = do { lam <- mkLam' dflags bndrs body
990            ; return (mkCoerce (mkPiTypes bndrs co) lam) }
991       where
992         co_vars  = tyVarsOfType co
993         bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars      
994
995     mkLam' dflags bndrs body
996       | dopt Opt_DoEtaReduction dflags,
997         Just etad_lam <- tryEtaReduce bndrs body
998       = do { tick (EtaReduction (head bndrs))
999            ; return etad_lam }
1000
1001       | dopt Opt_DoLambdaEtaExpansion dflags,
1002         not (inGentleMode env),       -- In gentle mode don't eta-expansion
1003         any isRuntimeVar bndrs        -- because it can clutter up the code
1004                                       -- with casts etc that may not be removed
1005       = do { let body' = tryEtaExpansion dflags body
1006            ; return (mkLams bndrs body') }
1007    
1008       | otherwise 
1009       = return (mkLams bndrs body)
1010 \end{code}
1011
1012 Note [Casts and lambdas]
1013 ~~~~~~~~~~~~~~~~~~~~~~~~
1014 Consider 
1015         (\x. (\y. e) `cast` g1) `cast` g2
1016 There is a danger here that the two lambdas look separated, and the 
1017 full laziness pass might float an expression to between the two.
1018
1019 So this equation in mkLam' floats the g1 out, thus:
1020         (\x. e `cast` g1)  -->  (\x.e) `cast` (tx -> g1)
1021 where x:tx.
1022
1023 In general, this floats casts outside lambdas, where (I hope) they
1024 might meet and cancel with some other cast:
1025         \x. e `cast` co   ===>   (\x. e) `cast` (tx -> co)
1026         /\a. e `cast` co  ===>   (/\a. e) `cast` (/\a. co)
1027         /\g. e `cast` co  ===>   (/\g. e) `cast` (/\g. co)
1028                           (if not (g `in` co))
1029
1030 Notice that it works regardless of 'e'.  Originally it worked only
1031 if 'e' was itself a lambda, but in some cases that resulted in 
1032 fruitless iteration in the simplifier.  A good example was when
1033 compiling Text.ParserCombinators.ReadPrec, where we had a definition 
1034 like    (\x. Get `cast` g)
1035 where Get is a constructor with nonzero arity.  Then mkLam eta-expanded
1036 the Get, and the next iteration eta-reduced it, and then eta-expanded 
1037 it again.
1038
1039 Note also the side condition for the case of coercion binders.
1040 It does not make sense to transform
1041         /\g. e `cast` g  ==>  (/\g.e) `cast` (/\g.g)
1042 because the latter is not well-kinded.
1043
1044 --      c) floating lets out through big lambdas 
1045 --              [only if all tyvar lambdas, and only if this lambda
1046 --               is the RHS of a let]
1047
1048 {-      Sept 01: I'm experimenting with getting the
1049         full laziness pass to float out past big lambdsa
1050  | all isTyVar bndrs,   -- Only for big lambdas
1051    contIsRhs cont       -- Only try the rhs type-lambda floating
1052                         -- if this is indeed a right-hand side; otherwise
1053                         -- we end up floating the thing out, only for float-in
1054                         -- to float it right back in again!
1055  = do (floats, body') <- tryRhsTyLam env bndrs body
1056       return (floats, mkLams bndrs body')
1057 -}
1058
1059
1060 %************************************************************************
1061 %*                                                                      *
1062                 Eta reduction
1063 %*                                                                      *
1064 %************************************************************************
1065
1066 Note [Eta reduction conditions]
1067 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1068 We try for eta reduction here, but *only* if we get all the way to an
1069 trivial expression.  We don't want to remove extra lambdas unless we
1070 are going to avoid allocating this thing altogether.
1071
1072 There are some particularly delicate points here:
1073
1074 * Eta reduction is not valid in general:  
1075         \x. bot  /=  bot
1076   This matters, partly for old-fashioned correctness reasons but,
1077   worse, getting it wrong can yield a seg fault. Consider
1078         f = \x.f x
1079         h y = case (case y of { True -> f `seq` True; False -> False }) of
1080                 True -> ...; False -> ...
1081
1082   If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
1083   says f=bottom, and replaces the (f `seq` True) with just
1084   (f `cast` unsafe-co).  BUT, as thing stand, 'f' got arity 1, and it
1085   *keeps* arity 1 (perhaps also wrongly).  So CorePrep eta-expands 
1086   the definition again, so that it does not termninate after all.
1087   Result: seg-fault because the boolean case actually gets a function value.
1088   See Trac #1947.
1089
1090   So it's important to to the right thing.
1091
1092 * Note [Arity care]: we need to be careful if we just look at f's
1093   arity. Currently (Dec07), f's arity is visible in its own RHS (see
1094   Note [Arity robustness] in SimplEnv) so we must *not* trust the
1095   arity when checking that 'f' is a value.  Otherwise we will
1096   eta-reduce
1097       f = \x. f x
1098   to
1099       f = f
1100   Which might change a terminiating program (think (f `seq` e)) to a 
1101   non-terminating one.  So we check for being a loop breaker first.
1102
1103   However for GlobalIds we can look at the arity; and for primops we
1104   must, since they have no unfolding.  
1105
1106 * Regardless of whether 'f' is a value, we always want to 
1107   reduce (/\a -> f a) to f
1108   This came up in a RULE: foldr (build (/\a -> g a))
1109   did not match           foldr (build (/\b -> ...something complex...))
1110   The type checker can insert these eta-expanded versions,
1111   with both type and dictionary lambdas; hence the slightly 
1112   ad-hoc isDictId
1113
1114 * Never *reduce* arity. For example
1115       f = \xy. g x y
1116   Then if h has arity 1 we don't want to eta-reduce because then
1117   f's arity would decrease, and that is bad
1118
1119 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1120 Alas.
1121
1122 \begin{code}
1123 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
1124 tryEtaReduce bndrs body 
1125   = go (reverse bndrs) body
1126   where
1127     incoming_arity = count isId bndrs
1128
1129     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
1130     go []       fun           | ok_fun fun   = Just fun         -- Success!
1131     go _        _                            = Nothing          -- Failure!
1132
1133         -- Note [Eta reduction conditions]
1134     ok_fun (App fun (Type ty)) 
1135         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1136         =  ok_fun fun
1137     ok_fun (Var fun_id)
1138         =  not (fun_id `elem` bndrs)
1139         && (ok_fun_id fun_id || all ok_lam bndrs)
1140     ok_fun _fun = False
1141
1142     ok_fun_id fun = fun_arity fun >= incoming_arity
1143
1144     fun_arity fun             -- See Note [Arity care]
1145        | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1146        | otherwise = idArity fun              
1147
1148     ok_lam v = isTyVar v || isDictId v
1149
1150     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
1151 \end{code}
1152
1153
1154 %************************************************************************
1155 %*                                                                      *
1156                 Eta expansion
1157 %*                                                                      *
1158 %************************************************************************
1159
1160
1161 We go for:
1162    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
1163                                  (n >= 0)
1164
1165 where (in both cases) 
1166
1167         * The xi can include type variables
1168
1169         * The yi are all value variables
1170
1171         * N is a NORMAL FORM (i.e. no redexes anywhere)
1172           wanting a suitable number of extra args.
1173
1174 The biggest reason for doing this is for cases like
1175
1176         f = \x -> case x of
1177                     True  -> \y -> e1
1178                     False -> \y -> e2
1179
1180 Here we want to get the lambdas together.  A good exmaple is the nofib
1181 program fibheaps, which gets 25% more allocation if you don't do this
1182 eta-expansion.
1183
1184 We may have to sandwich some coerces between the lambdas
1185 to make the types work.   exprEtaExpandArity looks through coerces
1186 when computing arity; and etaExpand adds the coerces as necessary when
1187 actually computing the expansion.
1188
1189 \begin{code}
1190 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1191 -- There is at least one runtime binder in the binders
1192 tryEtaExpansion dflags body
1193   = etaExpand fun_arity body
1194   where
1195     fun_arity = exprEtaExpandArity dflags body
1196 \end{code}
1197
1198
1199 %************************************************************************
1200 %*                                                                      *
1201 \subsection{Floating lets out of big lambdas}
1202 %*                                                                      *
1203 %************************************************************************
1204
1205 Note [Floating and type abstraction]
1206 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1207 Consider this:
1208         x = /\a. C e1 e2
1209 We'd like to float this to 
1210         y1 = /\a. e1
1211         y2 = /\a. e2
1212         x  = /\a. C (y1 a) (y2 a)
1213 for the usual reasons: we want to inline x rather vigorously.
1214
1215 You may think that this kind of thing is rare.  But in some programs it is
1216 common.  For example, if you do closure conversion you might get:
1217
1218         data a :-> b = forall e. (e -> a -> b) :$ e
1219
1220         f_cc :: forall a. a :-> a
1221         f_cc = /\a. (\e. id a) :$ ()
1222
1223 Now we really want to inline that f_cc thing so that the
1224 construction of the closure goes away. 
1225
1226 So I have elaborated simplLazyBind to understand right-hand sides that look
1227 like
1228         /\ a1..an. body
1229
1230 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1231 but there is quite a bit of plumbing in simplLazyBind as well.
1232
1233 The same transformation is good when there are lets in the body:
1234
1235         /\abc -> let(rec) x = e in b
1236    ==>
1237         let(rec) x' = /\abc -> let x = x' a b c in e
1238         in 
1239         /\abc -> let x = x' a b c in b
1240
1241 This is good because it can turn things like:
1242
1243         let f = /\a -> letrec g = ... g ... in g
1244 into
1245         letrec g' = /\a -> ... g' a ...
1246         in
1247         let f = /\ a -> g' a
1248
1249 which is better.  In effect, it means that big lambdas don't impede
1250 let-floating.
1251
1252 This optimisation is CRUCIAL in eliminating the junk introduced by
1253 desugaring mutually recursive definitions.  Don't eliminate it lightly!
1254
1255 [May 1999]  If we do this transformation *regardless* then we can
1256 end up with some pretty silly stuff.  For example, 
1257
1258         let 
1259             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1260         in ..
1261 becomes
1262         let y1 = /\s -> r1
1263             y2 = /\s -> r2
1264             st = /\s -> ...[y1 s/x1, y2 s/x2]
1265         in ..
1266
1267 Unless the "..." is a WHNF there is really no point in doing this.
1268 Indeed it can make things worse.  Suppose x1 is used strictly,
1269 and is of the form
1270
1271         x1* = case f y of { (a,b) -> e }
1272
1273 If we abstract this wrt the tyvar we then can't do the case inline
1274 as we would normally do.
1275
1276 That's why the whole transformation is part of the same process that
1277 floats let-bindings and constructor arguments out of RHSs.  In particular,
1278 it is guarded by the doFloatFromRhs call in simplLazyBind.
1279
1280
1281 \begin{code}
1282 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1283 abstractFloats main_tvs body_env body
1284   = ASSERT( notNull body_floats )
1285     do  { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1286         ; return (float_binds, CoreSubst.substExpr subst body) }
1287   where
1288     main_tv_set = mkVarSet main_tvs
1289     body_floats = getFloats body_env
1290     empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1291
1292     abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1293     abstract subst (NonRec id rhs)
1294       = do { (poly_id, poly_app) <- mk_poly tvs_here id
1295            ; let poly_rhs = mkLams tvs_here rhs'
1296                  subst'   = CoreSubst.extendIdSubst subst id poly_app
1297            ; return (subst', (NonRec poly_id poly_rhs)) }
1298       where
1299         rhs' = CoreSubst.substExpr subst rhs
1300         tvs_here | any isCoVar main_tvs = main_tvs      -- Note [Abstract over coercions]
1301                  | otherwise 
1302                  = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1303         
1304                 -- Abstract only over the type variables free in the rhs
1305                 -- wrt which the new binding is abstracted.  But the naive
1306                 -- approach of abstract wrt the tyvars free in the Id's type
1307                 -- fails. Consider:
1308                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1309                 --                    x :: a     = fst t
1310                 --                in ...
1311                 -- Here, b isn't free in x's type, but we must nevertheless
1312                 -- abstract wrt b as well, because t's type mentions b.
1313                 -- Since t is floated too, we'd end up with the bogus:
1314                 --      poly_t = /\ a b -> (e1, e2)
1315                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1316                 -- So for now we adopt the even more naive approach of
1317                 -- abstracting wrt *all* the tyvars.  We'll see if that
1318                 -- gives rise to problems.   SLPJ June 98
1319
1320     abstract subst (Rec prs)
1321        = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1322             ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1323                   poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1324             ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1325        where
1326          (ids,rhss) = unzip prs
1327                 -- For a recursive group, it's a bit of a pain to work out the minimal
1328                 -- set of tyvars over which to abstract:
1329                 --      /\ a b c.  let x = ...a... in
1330                 --                 letrec { p = ...x...q...
1331                 --                          q = .....p...b... } in
1332                 --                 ...
1333                 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1334                 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.  
1335                 -- Since it's a pain, we just use the whole set, which is always safe
1336                 -- 
1337                 -- If you ever want to be more selective, remember this bizarre case too:
1338                 --      x::a = x
1339                 -- Here, we must abstract 'x' over 'a'.
1340          tvs_here = main_tvs
1341
1342     mk_poly tvs_here var
1343       = do { uniq <- getUniqueM
1344            ; let  poly_name = setNameUnique (idName var) uniq           -- Keep same name
1345                   poly_ty   = mkForAllTys tvs_here (idType var) -- But new type of course
1346                   poly_id   = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1347                               mkLocalId poly_name poly_ty 
1348            ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1349                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1350                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1351                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1352                 -- at already simplified code, so it doesn't matter
1353                 -- 
1354                 -- It's even right to retain single-occurrence or dead-var info:
1355                 -- Suppose we started with  /\a -> let x = E in B
1356                 -- where x occurs once in B. Then we transform to:
1357                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1358                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1359                 -- the occurrences of x' will be just the occurrences originally
1360                 -- pinned on x.
1361 \end{code}
1362
1363 Note [Abstract over coercions]
1364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1365 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1366 type variable a.  Rather than sort this mess out, we simply bale out and abstract
1367 wrt all the type variables if any of them are coercion variables.
1368
1369
1370 Historical note: if you use let-bindings instead of a substitution, beware of this:
1371
1372                 -- Suppose we start with:
1373                 --
1374                 --      x = /\ a -> let g = G in E
1375                 --
1376                 -- Then we'll float to get
1377                 --
1378                 --      x = let poly_g = /\ a -> G
1379                 --          in /\ a -> let g = poly_g a in E
1380                 --
1381                 -- But now the occurrence analyser will see just one occurrence
1382                 -- of poly_g, not inside a lambda, so the simplifier will
1383                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1384                 -- (I used to think that the "don't inline lone occurrences" stuff
1385                 --  would stop this happening, but since it's the *only* occurrence,
1386                 --  PreInlineUnconditionally kicks in first!)
1387                 --
1388                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1389                 --           to appear many times.  (NB: mkInlineMe eliminates
1390                 --           such notes on trivial RHSs, so do it manually.)
1391
1392 %************************************************************************
1393 %*                                                                      *
1394                 prepareAlts
1395 %*                                                                      *
1396 %************************************************************************
1397
1398 prepareAlts tries these things:
1399
1400 1.  Eliminate alternatives that cannot match, including the
1401     DEFAULT alternative.
1402
1403 2.  If the DEFAULT alternative can match only one possible constructor,
1404     then make that constructor explicit.
1405     e.g.
1406         case e of x { DEFAULT -> rhs }
1407      ===>
1408         case e of x { (a,b) -> rhs }
1409     where the type is a single constructor type.  This gives better code
1410     when rhs also scrutinises x or e.
1411
1412 3. Returns a list of the constructors that cannot holds in the
1413    DEFAULT alternative (if there is one)
1414
1415 Here "cannot match" includes knowledge from GADTs
1416
1417 It's a good idea do do this stuff before simplifying the alternatives, to
1418 avoid simplifying alternatives we know can't happen, and to come up with
1419 the list of constructors that are handled, to put into the IdInfo of the
1420 case binder, for use when simplifying the alternatives.
1421
1422 Eliminating the default alternative in (1) isn't so obvious, but it can
1423 happen:
1424
1425 data Colour = Red | Green | Blue
1426
1427 f x = case x of
1428         Red -> ..
1429         Green -> ..
1430         DEFAULT -> h x
1431
1432 h y = case y of
1433         Blue -> ..
1434         DEFAULT -> [ case y of ... ]
1435
1436 If we inline h into f, the default case of the inlined h can't happen.
1437 If we don't notice this, we may end up filtering out *all* the cases
1438 of the inner case y, which give us nowhere to go!
1439
1440 \begin{code}
1441 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1442 prepareAlts scrut case_bndr' alts
1443   = do  { let (alts_wo_default, maybe_deflt) = findDefault alts
1444               alt_cons = [con | (con,_,_) <- alts_wo_default]
1445               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1446                 -- "imposs_deflt_cons" are handled 
1447                 --   EITHER by the context, 
1448                 --   OR by a non-DEFAULT branch in this case expression.
1449
1450         ; default_alts <- prepareDefault case_bndr' mb_tc_app 
1451                                          imposs_deflt_cons maybe_deflt
1452
1453         ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1454               merged_alts  = mergeAlts trimmed_alts default_alts
1455                 -- We need the mergeAlts in case the new default_alt 
1456                 -- has turned into a constructor alternative.
1457                 -- The merge keeps the inner DEFAULT at the front, if there is one
1458                 -- and interleaves the alternatives in the right order
1459
1460         ; return (imposs_deflt_cons, merged_alts) }
1461   where
1462     mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1463     Just (_, inst_tys) = mb_tc_app 
1464
1465     imposs_cons = case scrut of
1466                     Var v -> otherCons (idUnfolding v)
1467                     _     -> []
1468
1469     impossible_alt :: CoreAlt -> Bool
1470     impossible_alt (con, _, _) | con `elem` imposs_cons = True
1471     impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1472     impossible_alt _                   = False
1473
1474
1475 prepareDefault :: OutId         -- Case binder; need just for its type. Note that as an
1476                                 --   OutId, it has maximum information; this is important.
1477                                 --   Test simpl013 is an example
1478                -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1479                -> [AltCon]      -- These cons can't happen when matching the default
1480                -> Maybe InExpr  -- Rhs
1481                -> SimplM [InAlt]        -- Still unsimplified
1482                                         -- We use a list because it's what mergeAlts expects,
1483
1484 --------- Fill in known constructor -----------
1485 prepareDefault case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1486   |     -- This branch handles the case where we are 
1487         -- scrutinisng an algebraic data type
1488     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1489   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1490                                 --      case x of { DEFAULT -> e }
1491                                 -- and we don't want to fill in a default for them!
1492   , Just all_cons <- tyConDataCons_maybe tycon
1493   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1494                                 -- which GHC allows, then the case expression will have at most a default
1495                                 -- alternative.  We don't want to eliminate that alternative, because the
1496                                 -- invariant is that there's always one alternative.  It's more convenient
1497                                 -- to leave     
1498                                 --      case x of { DEFAULT -> e }     
1499                                 -- as it is, rather than transform it to
1500                                 --      error "case cant match"
1501                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1502                                 -- not worth wasting code on.
1503   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1504         impossible con   = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1505   = case filterOut impossible all_cons of
1506         []    -> return []      -- Eliminate the default alternative
1507                                 -- altogether if it can't match
1508
1509         [con] ->        -- It matches exactly one constructor, so fill it in
1510                  do { tick (FillInCaseDefault case_bndr)
1511                     ; us <- getUniquesM
1512                     ; let (ex_tvs, co_tvs, arg_ids) =
1513                               dataConRepInstPat us con inst_tys
1514                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1515
1516         _ -> return [(DEFAULT, [], deflt_rhs)]
1517
1518   | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1519         -- Check for no data constructors
1520         -- This can legitimately happen for type families, so don't report that
1521   = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1522         $ return [(DEFAULT, [], deflt_rhs)]
1523
1524 --------- Catch-all cases -----------
1525 prepareDefault _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1526   = return [(DEFAULT, [], deflt_rhs)]
1527
1528 prepareDefault _case_bndr _bndr_ty _imposs_cons Nothing
1529   = return []   -- No default branch
1530 \end{code}
1531
1532
1533
1534 %************************************************************************
1535 %*                                                                      *
1536                 mkCase
1537 %*                                                                      *
1538 %************************************************************************
1539
1540 mkCase tries these things
1541
1542 1.  Merge Nested Cases
1543
1544        case e of b {             ==>   case e of b {
1545          p1 -> rhs1                      p1 -> rhs1
1546          ...                             ...
1547          pm -> rhsm                      pm -> rhsm
1548          _  -> case b of b' {            pn -> let b'=b in rhsn
1549                      pn -> rhsn          ...
1550                      ...                 po -> let b'=b in rhso
1551                      po -> rhso          _  -> let b'=b in rhsd
1552                      _  -> rhsd
1553        }  
1554     
1555     which merges two cases in one case when -- the default alternative of
1556     the outer case scrutises the same variable as the outer case. This
1557     transformation is called Case Merging.  It avoids that the same
1558     variable is scrutinised multiple times.
1559
1560 2.  Eliminate Identity Case
1561
1562         case e of               ===> e
1563                 True  -> True;
1564                 False -> False
1565
1566     and similar friends.
1567
1568 3.  Merge identical alternatives.
1569     If several alternatives are identical, merge them into
1570     a single DEFAULT alternative.  I've occasionally seen this 
1571     making a big difference:
1572
1573         case e of               =====>     case e of
1574           C _ -> f x                         D v -> ....v....
1575           D v -> ....v....                   DEFAULT -> f x
1576           DEFAULT -> f x
1577
1578    The point is that we merge common RHSs, at least for the DEFAULT case.
1579    [One could do something more elaborate but I've never seen it needed.]
1580    To avoid an expensive test, we just merge branches equal to the *first*
1581    alternative; this picks up the common cases
1582         a) all branches equal
1583         b) some branches equal to the DEFAULT (which occurs first)
1584
1585 The case where Merge Identical Alternatives transformation showed up
1586 was like this (base/Foreign/C/Err/Error.lhs):
1587
1588         x | p `is` 1 -> e1
1589           | p `is` 2 -> e2
1590         ...etc...
1591
1592 where @is@ was something like
1593         
1594         p `is` n = p /= (-1) && p == n
1595
1596 This gave rise to a horrible sequence of cases
1597
1598         case p of
1599           (-1) -> $j p
1600           1    -> e1
1601           DEFAULT -> $j p
1602
1603 and similarly in cascade for all the join points!
1604
1605
1606 \begin{code}
1607 mkCase, mkCase1, mkCase2 
1608    :: DynFlags 
1609    -> OutExpr -> OutId
1610    -> [OutAlt]          -- Alternatives in standard (increasing) order
1611    -> SimplM OutExpr
1612
1613 --------------------------------------------------
1614 --      1. Merge Nested Cases
1615 --------------------------------------------------
1616
1617 mkCase dflags scrut outer_bndr ((DEFAULT, _, deflt_rhs) : outer_alts)
1618   | dopt Opt_CaseMerge dflags
1619   , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1620   , inner_scrut_var == outer_bndr
1621   = do  { tick (CaseMerge outer_bndr)
1622
1623         ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args )
1624                                           (con, args, wrap_rhs rhs)
1625                 -- Simplifier's no-shadowing invariant should ensure
1626                 -- that outer_bndr is not shadowed by the inner patterns
1627               wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs
1628                 -- The let is OK even for unboxed binders, 
1629
1630               wrapped_alts | isDeadBinder inner_bndr = inner_alts
1631                            | otherwise               = map wrap_alt inner_alts
1632
1633               merged_alts = mergeAlts outer_alts wrapped_alts
1634                 -- NB: mergeAlts gives priority to the left
1635                 --      case x of 
1636                 --        A -> e1
1637                 --        DEFAULT -> case x of 
1638                 --                      A -> e2
1639                 --                      B -> e3
1640                 -- When we merge, we must ensure that e1 takes 
1641                 -- precedence over e2 as the value for A!  
1642
1643         ; mkCase1 dflags scrut outer_bndr merged_alts
1644         }
1645         -- Warning: don't call mkCase recursively!
1646         -- Firstly, there's no point, because inner alts have already had
1647         -- mkCase applied to them, so they won't have a case in their default
1648         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1649         -- in munge_rhs may put a case into the DEFAULT branch!
1650
1651 mkCase dflags scrut bndr alts = mkCase1 dflags scrut bndr alts
1652
1653 --------------------------------------------------
1654 --      2. Eliminate Identity Case
1655 --------------------------------------------------
1656
1657 mkCase1 _dflags scrut case_bndr alts    -- Identity case
1658   | all identity_alt alts
1659   = do { tick (CaseIdentity case_bndr)
1660        ; return (re_cast scrut) }
1661   where
1662     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1663
1664     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1665     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1666     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1667                                          || rhs `cheapEqExpr` Var case_bndr
1668     check_eq _ _ _ = False
1669
1670     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1671
1672         -- We've seen this:
1673         --      case e of x { _ -> x `cast` c }
1674         -- And we definitely want to eliminate this case, to give
1675         --      e `cast` c
1676         -- So we throw away the cast from the RHS, and reconstruct
1677         -- it at the other end.  All the RHS casts must be the same
1678         -- if (all identity_alt alts) holds.
1679         -- 
1680         -- Don't worry about nested casts, because the simplifier combines them
1681     de_cast (Cast e _) = e
1682     de_cast e          = e
1683
1684     re_cast scrut = case head alts of
1685                         (_,_,Cast _ co) -> Cast scrut co
1686                         _               -> scrut
1687
1688 --------------------------------------------------
1689 --      3. Merge Identical Alternatives
1690 --------------------------------------------------
1691 mkCase1 dflags scrut case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1692   | all isDeadBinder bndrs1                     -- Remember the default 
1693   , length filtered_alts < length con_alts      -- alternative comes first
1694         -- Also Note [Dead binders]
1695   = do  { tick (AltMerge case_bndr)
1696         ; mkCase2 dflags scrut case_bndr alts' }
1697   where
1698     alts' = (DEFAULT, [], rhs1) : filtered_alts
1699     filtered_alts         = filter keep con_alts
1700     keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1701
1702 mkCase1 dflags scrut bndr alts = mkCase2 dflags scrut bndr alts
1703
1704 --------------------------------------------------
1705 --      Catch-all
1706 --------------------------------------------------
1707 mkCase2 _dflags scrut bndr alts 
1708   = return (Case scrut bndr (coreAltsType alts) alts)
1709 \end{code}
1710
1711 Note [Dead binders]
1712 ~~~~~~~~~~~~~~~~~~~~
1713 Note that dead-ness is maintained by the simplifier, so that it is
1714 accurate after simplification as well as before.
1715
1716
1717 Note [Cascading case merge]
1718 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1719 Case merging should cascade in one sweep, because it
1720 happens bottom-up
1721
1722       case e of a {
1723         DEFAULT -> case a of b 
1724                       DEFAULT -> case b of c {
1725                                      DEFAULT -> e
1726                                      A -> ea
1727                       B -> eb
1728         C -> ec
1729 ==>
1730       case e of a {
1731         DEFAULT -> case a of b 
1732                       DEFAULT -> let c = b in e
1733                       A -> let c = b in ea
1734                       B -> eb
1735         C -> ec
1736 ==>
1737       case e of a {
1738         DEFAULT -> let b = a in let c = b in e
1739         A -> let b = a in let c = b in ea
1740         B -> let b = a in eb
1741         C -> ec
1742
1743
1744 However here's a tricky case that we still don't catch, and I don't
1745 see how to catch it in one pass:
1746
1747   case x of c1 { I# a1 ->
1748   case a1 of c2 ->
1749     0 -> ...
1750     DEFAULT -> case x of c3 { I# a2 ->
1751                case a2 of ...
1752
1753 After occurrence analysis (and its binder-swap) we get this
1754  
1755   case x of c1 { I# a1 -> 
1756   let x = c1 in         -- Binder-swap addition
1757   case a1 of c2 -> 
1758     0 -> ...
1759     DEFAULT -> case x of c3 { I# a2 ->
1760                case a2 of ...
1761
1762 When we simplify the inner case x, we'll see that
1763 x=c1=I# a1.  So we'll bind a2 to a1, and get
1764
1765   case x of c1 { I# a1 -> 
1766   case a1 of c2 -> 
1767     0 -> ...
1768     DEFAULT -> case a1 of ...
1769
1770 This is corect, but we can't do a case merge in this sweep
1771 because c2 /= a1.  Reason: the binding c1=I# a1 went inwards
1772 without getting changed to c1=I# c2.  
1773
1774 I don't think this is worth fixing, even if I knew how. It'll
1775 all come out in the next pass anyway.
1776
1777