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