Refactor the simplifier's treatment of case expressions
[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, bindCaseBndr,
10
11         -- Inlining,
12         preInlineUnconditionally, postInlineUnconditionally, 
13         activeInline, activeRule, inlineMode,
14
15         -- The continuation type
16         SimplCont(..), DupFlag(..), LetRhsFlag(..), 
17         contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs, 
18         countValArgs, countArgs,
19         mkBoringStop, mkLazyArgStop, mkRhsStop, contIsRhsOrArg,
20         interestingCallContext, interestingArgContext,
21
22         interestingArg, mkArgInfo
23     ) where
24
25 #include "HsVersions.h"
26
27 import SimplEnv
28 import DynFlags
29 import StaticFlags
30 import CoreSyn
31 import PprCore
32 import CoreFVs
33 import CoreUtils
34 import Literal  
35 import CoreUnfold
36 import MkId
37 import Id
38 import NewDemand
39 import SimplMonad
40 import Type
41 import TyCon
42 import DataCon
43 import TcGadt   ( dataConCanMatch )
44 import VarSet
45 import BasicTypes
46 import Util
47 import Outputable
48 import List( nub )
49 \end{code}
50
51
52 %************************************************************************
53 %*                                                                      *
54                 The SimplCont type
55 %*                                                                      *
56 %************************************************************************
57
58 A SimplCont allows the simplifier to traverse the expression in a 
59 zipper-like fashion.  The SimplCont represents the rest of the expression,
60 "above" the point of interest.
61
62 You can also think of a SimplCont as an "evaluation context", using
63 that term in the way it is used for operational semantics. This is the
64 way I usually think of it, For example you'll often see a syntax for
65 evaluation context looking like
66         C ::= []  |  C e   |  case C of alts  |  C `cast` co
67 That's the kind of thing we are doing here, and I use that syntax in
68 the comments.
69
70
71 Key points:
72   * A SimplCont describes a *strict* context (just like 
73     evaluation contexts do).  E.g. Just [] is not a SimplCont
74
75   * A SimplCont describes a context that *does not* bind
76     any variables.  E.g. \x. [] is not a SimplCont
77
78 \begin{code}
79 data SimplCont  
80   = Stop                -- An empty context, or hole, []     
81         OutType         -- Type of the result
82         LetRhsFlag
83         Bool            -- True <=> There is something interesting about
84                         --          the context, and hence the inliner
85                         --          should be a bit keener (see interestingCallContext)
86                         -- Two cases:
87                         -- (a) This is the RHS of a thunk whose type suggests
88                         --     that update-in-place would be possible
89                         -- (b) This is an argument of a function that has RULES
90                         --     Inlining the call might allow the rule to fire
91
92   | CoerceIt            -- C `cast` co
93         OutCoercion             -- The coercion simplified
94         SimplCont
95
96   | ApplyTo             -- C arg
97         DupFlag 
98         InExpr SimplEnv         -- The argument and its static env
99         SimplCont
100
101   | Select              -- case C of alts
102         DupFlag 
103         InId [InAlt] SimplEnv   -- The case binder, alts, and subst-env
104         SimplCont
105
106   -- The two strict forms have no DupFlag, because we never duplicate them
107   | StrictBind          -- (\x* \xs. e) C
108         InId [InBndr]           -- let x* = [] in e     
109         InExpr SimplEnv         --      is a special case 
110         SimplCont       
111
112   | StrictArg           -- e C
113         OutExpr OutType         -- e and its type
114         (Bool,[Bool])           -- Whether the function at the head of e has rules,
115         SimplCont               --     plus strictness flags for further args
116
117 data LetRhsFlag = AnArg         -- It's just an argument not a let RHS
118                 | AnRhs         -- It's the RHS of a let (so please float lets out of big lambdas)
119
120 instance Outputable LetRhsFlag where
121   ppr AnArg = ptext SLIT("arg")
122   ppr AnRhs = ptext SLIT("rhs")
123
124 instance Outputable SimplCont where
125   ppr (Stop ty is_rhs _)             = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
126   ppr (ApplyTo dup arg se cont)      = ((ptext SLIT("ApplyTo") <+> ppr dup <+> pprParendExpr arg) $$ 
127                                           nest 2 (pprSimplEnv se)) $$ ppr cont
128   ppr (StrictBind b _ _ _ cont)      = (ptext SLIT("StrictBind") <+> ppr b) $$ ppr cont
129   ppr (StrictArg f _ _ cont)         = (ptext SLIT("StrictArg") <+> ppr f) $$ ppr cont
130   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
131                                        (nest 4 (ppr alts $$ pprSimplEnv se)) $$ ppr cont
132   ppr (CoerceIt co cont)             = (ptext SLIT("CoerceIt") <+> ppr co) $$ ppr cont
133
134 data DupFlag = OkToDup | NoDup
135
136 instance Outputable DupFlag where
137   ppr OkToDup = ptext SLIT("ok")
138   ppr NoDup   = ptext SLIT("nodup")
139
140
141
142 -------------------
143 mkBoringStop :: OutType -> SimplCont
144 mkBoringStop ty = Stop ty AnArg False
145
146 mkLazyArgStop :: OutType -> Bool -> SimplCont
147 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
148
149 mkRhsStop :: OutType -> SimplCont
150 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
151
152 contIsRhsOrArg (Stop _ _ _)    = True
153 contIsRhsOrArg (StrictBind {}) = True
154 contIsRhsOrArg (StrictArg {})  = True
155 contIsRhsOrArg other           = False
156
157 -------------------
158 contIsDupable :: SimplCont -> Bool
159 contIsDupable (Stop _ _ _)               = True
160 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
161 contIsDupable (Select   OkToDup _ _ _ _) = True
162 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
163 contIsDupable other                      = False
164
165 -------------------
166 contIsTrivial :: SimplCont -> Bool
167 contIsTrivial (Stop _ _ _)                = True
168 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
169 contIsTrivial (CoerceIt _ cont)           = contIsTrivial cont
170 contIsTrivial other                       = False
171
172 -------------------
173 contResultType :: SimplCont -> OutType
174 contResultType (Stop to_ty _ _)          = to_ty
175 contResultType (StrictArg _ _ _ cont)    = contResultType cont
176 contResultType (StrictBind _ _ _ _ cont) = contResultType cont
177 contResultType (ApplyTo _ _ _ cont)      = contResultType cont
178 contResultType (CoerceIt _ cont)         = contResultType cont
179 contResultType (Select _ _ _ _ cont)     = contResultType cont
180
181 -------------------
182 countValArgs :: SimplCont -> Int
183 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
184 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
185 countValArgs other                         = 0
186
187 countArgs :: SimplCont -> Int
188 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
189 countArgs other                   = 0
190
191 contArgs :: SimplCont -> ([OutExpr], SimplCont)
192 -- Uses substitution to turn each arg into an OutExpr
193 contArgs cont = go [] cont
194   where
195     go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
196     go args cont                    = (reverse args, cont)
197
198 dropArgs :: Int -> SimplCont -> SimplCont
199 dropArgs 0 cont = cont
200 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
201 dropArgs n other                = pprPanic "dropArgs" (ppr n <+> ppr other)
202 \end{code}
203
204
205 \begin{code}
206 interestingArg :: OutExpr -> Bool
207         -- An argument is interesting if it has *some* structure
208         -- We are here trying to avoid unfolding a function that
209         -- is applied only to variables that have no unfolding
210         -- (i.e. they are probably lambda bound): f x y z
211         -- There is little point in inlining f here.
212 interestingArg (Var v)           = hasSomeUnfolding (idUnfolding v)
213                                         -- Was: isValueUnfolding (idUnfolding v')
214                                         -- But that seems over-pessimistic
215                                  || isDataConWorkId v
216                                         -- This accounts for an argument like
217                                         -- () or [], which is definitely interesting
218 interestingArg (Type _)          = False
219 interestingArg (App fn (Type _)) = interestingArg fn
220 interestingArg (Note _ a)        = interestingArg a
221
222 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
223 -- interestingArg expr | isUnLiftedType (exprType expr)
224 --        -- Unlifted args are only ever interesting if we know what they are
225 --  =                  case expr of
226 --                        Lit lit -> True
227 --                        _       -> False
228
229 interestingArg other             = True
230         -- Consider     let x = 3 in f x
231         -- The substitution will contain (x -> ContEx 3), and we want to
232         -- to say that x is an interesting argument.
233         -- But consider also (\x. f x y) y
234         -- The substitution will contain (x -> ContEx y), and we want to say
235         -- that x is not interesting (assuming y has no unfolding)
236 \end{code}
237
238
239 Comment about interestingCallContext
240 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
241 We want to avoid inlining an expression where there can't possibly be
242 any gain, such as in an argument position.  Hence, if the continuation
243 is interesting (eg. a case scrutinee, application etc.) then we
244 inline, otherwise we don't.  
245
246 Previously some_benefit used to return True only if the variable was
247 applied to some value arguments.  This didn't work:
248
249         let x = _coerce_ (T Int) Int (I# 3) in
250         case _coerce_ Int (T Int) x of
251                 I# y -> ....
252
253 we want to inline x, but can't see that it's a constructor in a case
254 scrutinee position, and some_benefit is False.
255
256 Another example:
257
258 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
259
260 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
261
262 we'd really like to inline dMonadST here, but we *don't* want to
263 inline if the case expression is just
264
265         case x of y { DEFAULT -> ... }
266
267 since we can just eliminate this case instead (x is in WHNF).  Similar
268 applies when x is bound to a lambda expression.  Hence
269 contIsInteresting looks for case expressions with just a single
270 default case.
271
272 \begin{code}
273 interestingCallContext :: Bool          -- False <=> no args at all
274                        -> Bool          -- False <=> no value args
275                        -> SimplCont -> Bool
276         -- The "lone-variable" case is important.  I spent ages
277         -- messing about with unsatisfactory varaints, but this is nice.
278         -- The idea is that if a variable appear all alone
279         --      as an arg of lazy fn, or rhs    Stop
280         --      as scrutinee of a case          Select
281         --      as arg of a strict fn           ArgOf
282         -- then we should not inline it (unless there is some other reason,
283         -- e.g. is is the sole occurrence).  We achieve this by making
284         -- interestingCallContext return False for a lone variable.
285         --
286         -- Why?  At least in the case-scrutinee situation, turning
287         --      let x = (a,b) in case x of y -> ...
288         -- into
289         --      let x = (a,b) in case (a,b) of y -> ...
290         -- and thence to 
291         --      let x = (a,b) in let y = (a,b) in ...
292         -- is bad if the binding for x will remain.
293         --
294         -- Another example: I discovered that strings
295         -- were getting inlined straight back into applications of 'error'
296         -- because the latter is strict.
297         --      s = "foo"
298         --      f = \x -> ...(error s)...
299
300         -- Fundamentally such contexts should not ecourage inlining because
301         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
302         -- so there's no gain.
303         --
304         -- However, even a type application or coercion isn't a lone variable.
305         -- Consider
306         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
307         -- We had better inline that sucker!  The case won't see through it.
308         --
309         -- For now, I'm treating treating a variable applied to types 
310         -- in a *lazy* context "lone". The motivating example was
311         --      f = /\a. \x. BIG
312         --      g = /\a. \y.  h (f a)
313         -- There's no advantage in inlining f here, and perhaps
314         -- a significant disadvantage.  Hence some_val_args in the Stop case
315
316 interestingCallContext some_args some_val_args cont
317   = interesting cont
318   where
319     interesting (Select {})              = some_args
320     interesting (ApplyTo {})             = True -- Can happen if we have (coerce t (f x)) y
321                                                 -- Perhaps True is a bit over-keen, but I've
322                                                 -- seen (coerce f) x, where f has an INLINE prag,
323                                                 -- So we have to give some motivaiton for inlining it
324     interesting (StrictArg {})           = some_val_args
325     interesting (StrictBind {})          = some_val_args        -- ??
326     interesting (Stop ty _ interesting)  = some_val_args && interesting
327     interesting (CoerceIt _ cont)        = interesting cont
328         -- If this call is the arg of a strict function, the context
329         -- is a bit interesting.  If we inline here, we may get useful
330         -- evaluation information to avoid repeated evals: e.g.
331         --      x + (y * z)
332         -- Here the contIsInteresting makes the '*' keener to inline,
333         -- which in turn exposes a constructor which makes the '+' inline.
334         -- Assuming that +,* aren't small enough to inline regardless.
335         --
336         -- It's also very important to inline in a strict context for things
337         -- like
338         --              foldr k z (f x)
339         -- Here, the context of (f x) is strict, and if f's unfolding is
340         -- a build it's *great* to inline it here.  So we must ensure that
341         -- the context for (f x) is not totally uninteresting.
342
343
344 -------------------
345 mkArgInfo :: Id
346           -> Int        -- Number of value args
347           -> SimplCont  -- Context of the cal
348           -> (Bool, [Bool])     -- Arg info
349 -- The arg info consists of
350 --  * A Bool indicating if the function has rules (recursively)
351 --  * A [Bool] indicating strictness for each arg
352 -- The [Bool] is usually infinite, but if it is finite it 
353 -- guarantees that the function diverges after being given
354 -- that number of args
355
356 mkArgInfo fun n_val_args call_cont
357   = (interestingArgContext fun call_cont, fun_stricts)
358   where
359     vanilla_stricts, fun_stricts :: [Bool]
360     vanilla_stricts  = repeat False
361
362     fun_stricts
363       = case splitStrictSig (idNewStrictness fun) of
364           (demands, result_info)
365                 | not (demands `lengthExceeds` n_val_args)
366                 ->      -- Enough args, use the strictness given.
367                         -- For bottoming functions we used to pretend that the arg
368                         -- is lazy, so that we don't treat the arg as an
369                         -- interesting context.  This avoids substituting
370                         -- top-level bindings for (say) strings into 
371                         -- calls to error.  But now we are more careful about
372                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
373                    if isBotRes result_info then
374                         map isStrictDmd demands         -- Finite => result is bottom
375                    else
376                         map isStrictDmd demands ++ vanilla_stricts
377
378           other -> vanilla_stricts      -- Not enough args, or no strictness
379
380 interestingArgContext :: Id -> SimplCont -> Bool
381 -- If the argument has form (f x y), where x,y are boring,
382 -- and f is marked INLINE, then we don't want to inline f.
383 -- But if the context of the argument is
384 --      g (f x y) 
385 -- where g has rules, then we *do* want to inline f, in case it
386 -- exposes a rule that might fire.  Similarly, if the context is
387 --      h (g (f x x))
388 -- where h has rules, then we do want to inline f.
389 -- The interesting_arg_ctxt flag makes this happen; if it's
390 -- set, the inliner gets just enough keener to inline f 
391 -- regardless of how boring f's arguments are, if it's marked INLINE
392 --
393 -- The alternative would be to *always* inline an INLINE function,
394 -- regardless of how boring its context is; but that seems overkill
395 -- For example, it'd mean that wrapper functions were always inlined
396 interestingArgContext fn cont
397   = idHasRules fn || go cont
398   where
399     go (Select {})            = False
400     go (ApplyTo {})           = False
401     go (StrictArg {})         = True
402     go (StrictBind {})        = False   -- ??
403     go (CoerceIt _ c)         = go c
404     go (Stop _ _ interesting) = interesting
405
406 -------------------
407 canUpdateInPlace :: Type -> Bool
408 -- Consider   let x = <wurble> in ...
409 -- If <wurble> returns an explicit constructor, we might be able
410 -- to do update in place.  So we treat even a thunk RHS context
411 -- as interesting if update in place is possible.  We approximate
412 -- this by seeing if the type has a single constructor with a
413 -- small arity.  But arity zero isn't good -- we share the single copy
414 -- for that case, so no point in sharing.
415
416 canUpdateInPlace ty 
417   | not opt_UF_UpdateInPlace = False
418   | otherwise
419   = case splitTyConApp_maybe ty of 
420         Nothing         -> False 
421         Just (tycon, _) -> case tyConDataCons_maybe tycon of
422                                 Just [dc]  -> arity == 1 || arity == 2
423                                            where
424                                               arity = dataConRepArity dc
425                                 other -> False
426 \end{code}
427
428
429
430 %************************************************************************
431 %*                                                                      *
432 \subsection{Decisions about inlining}
433 %*                                                                      *
434 %************************************************************************
435
436 Inlining is controlled partly by the SimplifierMode switch.  This has two
437 settings:
438
439         SimplGently     (a) Simplifying before specialiser/full laziness
440                         (b) Simplifiying inside INLINE pragma
441                         (c) Simplifying the LHS of a rule
442                         (d) Simplifying a GHCi expression or Template 
443                                 Haskell splice
444
445         SimplPhase n    Used at all other times
446
447 The key thing about SimplGently is that it does no call-site inlining.
448 Before full laziness we must be careful not to inline wrappers,
449 because doing so inhibits floating
450     e.g. ...(case f x of ...)...
451     ==> ...(case (case x of I# x# -> fw x#) of ...)...
452     ==> ...(case x of I# x# -> case fw x# of ...)...
453 and now the redex (f x) isn't floatable any more.
454
455 The no-inlining thing is also important for Template Haskell.  You might be 
456 compiling in one-shot mode with -O2; but when TH compiles a splice before
457 running it, we don't want to use -O2.  Indeed, we don't want to inline
458 anything, because the byte-code interpreter might get confused about 
459 unboxed tuples and suchlike.
460
461 INLINE pragmas
462 ~~~~~~~~~~~~~~
463 SimplGently is also used as the mode to simplify inside an InlineMe note.
464
465 \begin{code}
466 inlineMode :: SimplifierMode
467 inlineMode = SimplGently
468 \end{code}
469
470 It really is important to switch off inlinings inside such
471 expressions.  Consider the following example 
472
473         let f = \pq -> BIG
474         in
475         let g = \y -> f y y
476             {-# INLINE g #-}
477         in ...g...g...g...g...g...
478
479 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
480 and thence copied multiple times when g is inlined.
481
482
483 This function may be inlinined in other modules, so we
484 don't want to remove (by inlining) calls to functions that have
485 specialisations, or that may have transformation rules in an importing
486 scope.
487
488 E.g.    {-# INLINE f #-}
489                 f x = ...g...
490
491 and suppose that g is strict *and* has specialisations.  If we inline
492 g's wrapper, we deny f the chance of getting the specialised version
493 of g when f is inlined at some call site (perhaps in some other
494 module).
495
496 It's also important not to inline a worker back into a wrapper.
497 A wrapper looks like
498         wraper = inline_me (\x -> ...worker... )
499 Normally, the inline_me prevents the worker getting inlined into
500 the wrapper (initially, the worker's only call site!).  But,
501 if the wrapper is sure to be called, the strictness analyser will
502 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
503 continuation.  That's why the keep_inline predicate returns True for
504 ArgOf continuations.  It shouldn't do any harm not to dissolve the
505 inline-me note under these circumstances.
506
507 Note that the result is that we do very little simplification
508 inside an InlineMe.  
509
510         all xs = foldr (&&) True xs
511         any p = all . map p  {-# INLINE any #-}
512
513 Problem: any won't get deforested, and so if it's exported and the
514 importer doesn't use the inlining, (eg passes it as an arg) then we
515 won't get deforestation at all.  We havn't solved this problem yet!
516
517
518 preInlineUnconditionally
519 ~~~~~~~~~~~~~~~~~~~~~~~~
520 @preInlineUnconditionally@ examines a bndr to see if it is used just
521 once in a completely safe way, so that it is safe to discard the
522 binding inline its RHS at the (unique) usage site, REGARDLESS of how
523 big the RHS might be.  If this is the case we don't simplify the RHS
524 first, but just inline it un-simplified.
525
526 This is much better than first simplifying a perhaps-huge RHS and then
527 inlining and re-simplifying it.  Indeed, it can be at least quadratically
528 better.  Consider
529
530         x1 = e1
531         x2 = e2[x1]
532         x3 = e3[x2]
533         ...etc...
534         xN = eN[xN-1]
535
536 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
537 This can happen with cascades of functions too:
538
539         f1 = \x1.e1
540         f2 = \xs.e2[f1]
541         f3 = \xs.e3[f3]
542         ...etc...
543
544 THE MAIN INVARIANT is this:
545
546         ----  preInlineUnconditionally invariant -----
547    IF preInlineUnconditionally chooses to inline x = <rhs>
548    THEN doing the inlining should not change the occurrence
549         info for the free vars of <rhs>
550         ----------------------------------------------
551
552 For example, it's tempting to look at trivial binding like
553         x = y
554 and inline it unconditionally.  But suppose x is used many times,
555 but this is the unique occurrence of y.  Then inlining x would change
556 y's occurrence info, which breaks the invariant.  It matters: y
557 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
558
559
560 Evne RHSs labelled InlineMe aren't caught here, because there might be
561 no benefit from inlining at the call site.
562
563 [Sept 01] Don't unconditionally inline a top-level thing, because that
564 can simply make a static thing into something built dynamically.  E.g.
565         x = (a,b)
566         main = \s -> h x
567
568 [Remember that we treat \s as a one-shot lambda.]  No point in
569 inlining x unless there is something interesting about the call site.
570
571 But watch out: if you aren't careful, some useful foldr/build fusion
572 can be lost (most notably in spectral/hartel/parstof) because the
573 foldr didn't see the build.  Doing the dynamic allocation isn't a big
574 deal, in fact, but losing the fusion can be.  But the right thing here
575 seems to be to do a callSiteInline based on the fact that there is
576 something interesting about the call site (it's strict).  Hmm.  That
577 seems a bit fragile.
578
579 Conclusion: inline top level things gaily until Phase 0 (the last
580 phase), at which point don't.
581
582 \begin{code}
583 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
584 preInlineUnconditionally env top_lvl bndr rhs
585   | not active             = False
586   | opt_SimplNoPreInlining = False
587   | otherwise = case idOccInfo bndr of
588                   IAmDead                    -> True    -- Happens in ((\x.1) v)
589                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
590                   other                      -> False
591   where
592     phase = getMode env
593     active = case phase of
594                    SimplGently  -> isAlwaysActive prag
595                    SimplPhase n -> isActive n prag
596     prag = idInlinePragma bndr
597
598     try_once in_lam int_cxt     -- There's one textual occurrence
599         | not in_lam = isNotTopLevel top_lvl || early_phase
600         | otherwise  = int_cxt && canInlineInLam rhs
601
602 -- Be very careful before inlining inside a lambda, becuase (a) we must not 
603 -- invalidate occurrence information, and (b) we want to avoid pushing a
604 -- single allocation (here) into multiple allocations (inside lambda).  
605 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
606 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
607 --      where 
608 --              is_cheap = exprIsCheap rhs
609 --              ok = is_cheap && int_cxt
610
611         --      int_cxt         The context isn't totally boring
612         -- E.g. let f = \ab.BIG in \y. map f xs
613         --      Don't want to substitute for f, because then we allocate
614         --      its closure every time the \y is called
615         -- But: let f = \ab.BIG in \y. map (f y) xs
616         --      Now we do want to substitute for f, even though it's not 
617         --      saturated, because we're going to allocate a closure for 
618         --      (f y) every time round the loop anyhow.
619
620         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
621         -- so substituting rhs inside a lambda doesn't change the occ info.
622         -- Sadly, not quite the same as exprIsHNF.
623     canInlineInLam (Lit l)              = True
624     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
625     canInlineInLam (Note _ e)           = canInlineInLam e
626     canInlineInLam _                    = False
627
628     early_phase = case phase of
629                         SimplPhase 0 -> False
630                         other        -> True
631 -- If we don't have this early_phase test, consider
632 --      x = length [1,2,3]
633 -- The full laziness pass carefully floats all the cons cells to
634 -- top level, and preInlineUnconditionally floats them all back in.
635 -- Result is (a) static allocation replaced by dynamic allocation
636 --           (b) many simplifier iterations because this tickles
637 --               a related problem; only one inlining per pass
638 -- 
639 -- On the other hand, I have seen cases where top-level fusion is
640 -- lost if we don't inline top level thing (e.g. string constants)
641 -- Hence the test for phase zero (which is the phase for all the final
642 -- simplifications).  Until phase zero we take no special notice of
643 -- top level things, but then we become more leery about inlining
644 -- them.  
645
646 \end{code}
647
648 postInlineUnconditionally
649 ~~~~~~~~~~~~~~~~~~~~~~~~~
650 @postInlineUnconditionally@ decides whether to unconditionally inline
651 a thing based on the form of its RHS; in particular if it has a
652 trivial RHS.  If so, we can inline and discard the binding altogether.
653
654 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
655 only have *forward* references Hence, it's safe to discard the binding
656         
657 NOTE: This isn't our last opportunity to inline.  We're at the binding
658 site right now, and we'll get another opportunity when we get to the
659 ocurrence(s)
660
661 Note that we do this unconditional inlining only for trival RHSs.
662 Don't inline even WHNFs inside lambdas; doing so may simply increase
663 allocation when the function is called. This isn't the last chance; see
664 NOTE above.
665
666 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
667 Because we don't even want to inline them into the RHS of constructor
668 arguments. See NOTE above
669
670 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
671 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
672 with both a and b marked NOINLINE.  But that seems incompatible with
673 our new view that inlining is like a RULE, so I'm sticking to the 'active'
674 story for now.
675
676 \begin{code}
677 postInlineUnconditionally 
678     :: SimplEnv -> TopLevelFlag
679     -> InId             -- The binder (an OutId would be fine too)
680     -> OccInfo          -- From the InId
681     -> OutExpr
682     -> Unfolding
683     -> Bool
684 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
685   | not active             = False
686   | isLoopBreaker occ_info = False      -- If it's a loop-breaker of any kind, dont' inline
687                                         -- because it might be referred to "earlier"
688   | isExportedId bndr      = False
689   | exprIsTrivial rhs      = True
690   | otherwise
691   = case occ_info of
692         -- The point of examining occ_info here is that for *non-values* 
693         -- that occur outside a lambda, the call-site inliner won't have
694         -- a chance (becuase it doesn't know that the thing
695         -- only occurs once).   The pre-inliner won't have gotten
696         -- it either, if the thing occurs in more than one branch
697         -- So the main target is things like
698         --      let x = f y in
699         --      case v of
700         --         True  -> case x of ...
701         --         False -> case x of ...
702         -- I'm not sure how important this is in practice
703       OneOcc in_lam one_br int_cxt      -- OneOcc => no code-duplication issue
704         ->     smallEnoughToInline unfolding    -- Small enough to dup
705                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
706                         --
707                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
708                         -- Reason: doing so risks exponential behaviour.  We simplify a big
709                         --         expression, inline it, and simplify it again.  But if the
710                         --         very same thing happens in the big expression, we get 
711                         --         exponential cost!
712                         -- PRINCIPLE: when we've already simplified an expression once, 
713                         -- make sure that we only inline it if it's reasonably small.
714
715            &&  ((isNotTopLevel top_lvl && not in_lam) || 
716                         -- But outside a lambda, we want to be reasonably aggressive
717                         -- about inlining into multiple branches of case
718                         -- e.g. let x = <non-value> 
719                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
720                         -- Inlining can be a big win if C3 is the hot-spot, even if
721                         -- the uses in C1, C2 are not 'interesting'
722                         -- An example that gets worse if you add int_cxt here is 'clausify'
723
724                 (isCheapUnfolding unfolding && int_cxt))
725                         -- isCheap => acceptable work duplication; in_lam may be true
726                         -- int_cxt to prevent us inlining inside a lambda without some 
727                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
728
729       IAmDead -> True   -- This happens; for example, the case_bndr during case of
730                         -- known constructor:  case (a,b) of x { (p,q) -> ... }
731                         -- Here x isn't mentioned in the RHS, so we don't want to
732                         -- create the (dead) let-binding  let x = (a,b) in ...
733
734       other -> False
735
736 -- Here's an example that we don't handle well:
737 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
738 --      in \y. ....case f of {...} ....
739 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
740 -- But
741 -- * We can't preInlineUnconditionally because that woud invalidate
742 --   the occ info for b.  
743 -- * We can't postInlineUnconditionally because the RHS is big, and
744 --   that risks exponential behaviour
745 -- * We can't call-site inline, because the rhs is big
746 -- Alas!
747
748   where
749     active = case getMode env of
750                    SimplGently  -> isAlwaysActive prag
751                    SimplPhase n -> isActive n prag
752     prag = idInlinePragma bndr
753
754 activeInline :: SimplEnv -> OutId -> Bool
755 activeInline env id
756   = case getMode env of
757       SimplGently -> False
758         -- No inlining at all when doing gentle stuff,
759         -- except for local things that occur once
760         -- The reason is that too little clean-up happens if you 
761         -- don't inline use-once things.   Also a bit of inlining is *good* for
762         -- full laziness; it can expose constant sub-expressions.
763         -- Example in spectral/mandel/Mandel.hs, where the mandelset 
764         -- function gets a useful let-float if you inline windowToViewport
765
766         -- NB: we used to have a second exception, for data con wrappers.
767         -- On the grounds that we use gentle mode for rule LHSs, and 
768         -- they match better when data con wrappers are inlined.
769         -- But that only really applies to the trivial wrappers (like (:)),
770         -- and they are now constructed as Compulsory unfoldings (in MkId)
771         -- so they'll happen anyway.
772
773       SimplPhase n -> isActive n prag
774   where
775     prag = idInlinePragma id
776
777 activeRule :: SimplEnv -> Maybe (Activation -> Bool)
778 -- Nothing => No rules at all
779 activeRule env
780   | opt_RulesOff = Nothing
781   | otherwise
782   = case getMode env of
783         SimplGently  -> Just isAlwaysActive
784                         -- Used to be Nothing (no rules in gentle mode)
785                         -- Main motivation for changing is that I wanted
786                         --      lift String ===> ...
787                         -- to work in Template Haskell when simplifying
788                         -- splices, so we get simpler code for literal strings
789         SimplPhase n -> Just (isActive n)
790 \end{code}
791
792
793 %************************************************************************
794 %*                                                                      *
795         Rebuilding a lambda
796 %*                                                                      *
797 %************************************************************************
798
799 \begin{code}
800 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
801 -- mkLam tries three things
802 --      a) eta reduction, if that gives a trivial expression
803 --      b) eta expansion [only if there are some value lambdas]
804
805 mkLam bndrs body
806   = do  { dflags <- getDOptsSmpl
807         ; mkLam' dflags bndrs body }
808   where
809     mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
810     mkLam' dflags bndrs (Cast body@(Lam _ _) co)
811         -- Note [Casts and lambdas]
812       = do { lam <- mkLam' dflags (bndrs ++ bndrs') body'
813            ; return (mkCoerce (mkPiTypes bndrs co) lam) }
814       where     
815         (bndrs',body') = collectBinders body
816
817     mkLam' dflags bndrs body
818       | dopt Opt_DoEtaReduction dflags,
819         Just etad_lam <- tryEtaReduce bndrs body
820       = do { tick (EtaReduction (head bndrs))
821            ; return etad_lam }
822
823       | dopt Opt_DoLambdaEtaExpansion dflags,
824         any isRuntimeVar bndrs
825       = do { body' <- tryEtaExpansion dflags body
826            ; return (mkLams bndrs body') }
827    
828       | otherwise 
829       = returnSmpl (mkLams bndrs body)
830 \end{code}
831
832 Note [Casts and lambdas]
833 ~~~~~~~~~~~~~~~~~~~~~~~~
834 Consider 
835         (\x. (\y. e) `cast` g1) `cast` g2
836 There is a danger here that the two lambdas look separated, and the 
837 full laziness pass might float an expression to between the two.
838
839 So this equation in mkLam' floats the g1 out, thus:
840         (\x. e `cast` g1)  -->  (\x.e) `cast` (tx -> g1)
841 where x:tx.
842
843 In general, this floats casts outside lambdas, where (I hope) they might meet
844 and cancel with some other cast.
845
846
847 --      c) floating lets out through big lambdas 
848 --              [only if all tyvar lambdas, and only if this lambda
849 --               is the RHS of a let]
850
851 {-      Sept 01: I'm experimenting with getting the
852         full laziness pass to float out past big lambdsa
853  | all isTyVar bndrs,   -- Only for big lambdas
854    contIsRhs cont       -- Only try the rhs type-lambda floating
855                         -- if this is indeed a right-hand side; otherwise
856                         -- we end up floating the thing out, only for float-in
857                         -- to float it right back in again!
858  = tryRhsTyLam env bndrs body           `thenSmpl` \ (floats, body') ->
859    returnSmpl (floats, mkLams bndrs body')
860 -}
861
862
863 %************************************************************************
864 %*                                                                      *
865 \subsection{Eta expansion and reduction}
866 %*                                                                      *
867 %************************************************************************
868
869 We try for eta reduction here, but *only* if we get all the 
870 way to an exprIsTrivial expression.    
871 We don't want to remove extra lambdas unless we are going 
872 to avoid allocating this thing altogether
873
874 \begin{code}
875 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
876 tryEtaReduce bndrs body 
877         -- We don't use CoreUtils.etaReduce, because we can be more
878         -- efficient here:
879         --  (a) we already have the binders
880         --  (b) we can do the triviality test before computing the free vars
881   = go (reverse bndrs) body
882   where
883     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
884     go []       fun           | ok_fun fun   = Just fun         -- Success!
885     go _        _                            = Nothing          -- Failure!
886
887     ok_fun fun =  exprIsTrivial fun
888                && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
889                && (exprIsHNF fun || all ok_lam bndrs)
890     ok_lam v = isTyVar v || isDictId v
891         -- The exprIsHNF is because eta reduction is not 
892         -- valid in general:  \x. bot  /=  bot
893         -- So we need to be sure that the "fun" is a value.
894         --
895         -- However, we always want to reduce (/\a -> f a) to f
896         -- This came up in a RULE: foldr (build (/\a -> g a))
897         --      did not match      foldr (build (/\b -> ...something complex...))
898         -- The type checker can insert these eta-expanded versions,
899         -- with both type and dictionary lambdas; hence the slightly 
900         -- ad-hoc isDictTy
901
902     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
903 \end{code}
904
905
906         Try eta expansion for RHSs
907
908 We go for:
909    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
910                                  (n >= 0)
911
912 where (in both cases) 
913
914         * The xi can include type variables
915
916         * The yi are all value variables
917
918         * N is a NORMAL FORM (i.e. no redexes anywhere)
919           wanting a suitable number of extra args.
920
921 We may have to sandwich some coerces between the lambdas
922 to make the types work.   exprEtaExpandArity looks through coerces
923 when computing arity; and etaExpand adds the coerces as necessary when
924 actually computing the expansion.
925
926 \begin{code}
927 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
928 -- There is at least one runtime binder in the binders
929 tryEtaExpansion dflags body
930   = getUniquesSmpl                      `thenSmpl` \ us ->
931     returnSmpl (etaExpand fun_arity us body (exprType body))
932   where
933     fun_arity = exprEtaExpandArity dflags body
934 \end{code}
935
936
937 %************************************************************************
938 %*                                                                      *
939 \subsection{Floating lets out of big lambdas}
940 %*                                                                      *
941 %************************************************************************
942
943 tryRhsTyLam tries this transformation, when the big lambda appears as
944 the RHS of a let(rec) binding:
945
946         /\abc -> let(rec) x = e in b
947    ==>
948         let(rec) x' = /\abc -> let x = x' a b c in e
949         in 
950         /\abc -> let x = x' a b c in b
951
952 This is good because it can turn things like:
953
954         let f = /\a -> letrec g = ... g ... in g
955 into
956         letrec g' = /\a -> ... g' a ...
957         in
958         let f = /\ a -> g' a
959
960 which is better.  In effect, it means that big lambdas don't impede
961 let-floating.
962
963 This optimisation is CRUCIAL in eliminating the junk introduced by
964 desugaring mutually recursive definitions.  Don't eliminate it lightly!
965
966 So far as the implementation is concerned:
967
968         Invariant: go F e = /\tvs -> F e
969         
970         Equalities:
971                 go F (Let x=e in b)
972                 = Let x' = /\tvs -> F e 
973                   in 
974                   go G b
975                 where
976                     G = F . Let x = x' tvs
977         
978                 go F (Letrec xi=ei in b)
979                 = Letrec {xi' = /\tvs -> G ei} 
980                   in
981                   go G b
982                 where
983                   G = F . Let {xi = xi' tvs}
984
985 [May 1999]  If we do this transformation *regardless* then we can
986 end up with some pretty silly stuff.  For example, 
987
988         let 
989             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
990         in ..
991 becomes
992         let y1 = /\s -> r1
993             y2 = /\s -> r2
994             st = /\s -> ...[y1 s/x1, y2 s/x2]
995         in ..
996
997 Unless the "..." is a WHNF there is really no point in doing this.
998 Indeed it can make things worse.  Suppose x1 is used strictly,
999 and is of the form
1000
1001         x1* = case f y of { (a,b) -> e }
1002
1003 If we abstract this wrt the tyvar we then can't do the case inline
1004 as we would normally do.
1005
1006
1007 \begin{code}
1008 {-      Trying to do this in full laziness
1009
1010 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
1011 -- Call ensures that all the binders are type variables
1012
1013 tryRhsTyLam env tyvars body             -- Only does something if there's a let
1014   |  not (all isTyVar tyvars)
1015   || not (worth_it body)                -- inside a type lambda, 
1016   = returnSmpl (emptyFloats env, body)  -- and a WHNF inside that
1017
1018   | otherwise
1019   = go env (\x -> x) body
1020
1021   where
1022     worth_it e@(Let _ _) = whnf_in_middle e
1023     worth_it e           = False
1024
1025     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
1026     whnf_in_middle (Let _ e) = whnf_in_middle e
1027     whnf_in_middle e         = exprIsCheap e
1028
1029     main_tyvar_set = mkVarSet tyvars
1030
1031     go env fn (Let bind@(NonRec var rhs) body)
1032       | exprIsTrivial rhs
1033       = go env (fn . Let bind) body
1034
1035     go env fn (Let (NonRec var rhs) body)
1036       = mk_poly tyvars_here var                                                 `thenSmpl` \ (var', rhs') ->
1037         addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs)))        $ \ env -> 
1038         go env (fn . Let (mk_silly_bind var rhs')) body
1039
1040       where
1041
1042         tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1043                 -- Abstract only over the type variables free in the rhs
1044                 -- wrt which the new binding is abstracted.  But the naive
1045                 -- approach of abstract wrt the tyvars free in the Id's type
1046                 -- fails. Consider:
1047                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1048                 --                    x :: a     = fst t
1049                 --                in ...
1050                 -- Here, b isn't free in x's type, but we must nevertheless
1051                 -- abstract wrt b as well, because t's type mentions b.
1052                 -- Since t is floated too, we'd end up with the bogus:
1053                 --      poly_t = /\ a b -> (e1, e2)
1054                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1055                 -- So for now we adopt the even more naive approach of
1056                 -- abstracting wrt *all* the tyvars.  We'll see if that
1057                 -- gives rise to problems.   SLPJ June 98
1058
1059     go env fn (Let (Rec prs) body)
1060        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
1061          let
1062             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1063             pairs   = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1064          in
1065          addAuxiliaryBind env (Rec pairs)               $ \ env ->
1066          go env gn body 
1067        where
1068          (vars,rhss) = unzip prs
1069          tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1070                 -- See notes with tyvars_here above
1071
1072     go env fn body = returnSmpl (emptyFloats env, fn body)
1073
1074     mk_poly tyvars_here var
1075       = getUniqueSmpl           `thenSmpl` \ uniq ->
1076         let
1077             poly_name = setNameUnique (idName var) uniq         -- Keep same name
1078             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
1079             poly_id   = mkLocalId poly_name poly_ty 
1080
1081                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1082                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1083                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1084                 -- at already simplified code, so it doesn't matter
1085                 -- 
1086                 -- It's even right to retain single-occurrence or dead-var info:
1087                 -- Suppose we started with  /\a -> let x = E in B
1088                 -- where x occurs once in B. Then we transform to:
1089                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1090                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1091                 -- the occurrences of x' will be just the occurrences originally
1092                 -- pinned on x.
1093         in
1094         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1095
1096     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1097                 -- Suppose we start with:
1098                 --
1099                 --      x = /\ a -> let g = G in E
1100                 --
1101                 -- Then we'll float to get
1102                 --
1103                 --      x = let poly_g = /\ a -> G
1104                 --          in /\ a -> let g = poly_g a in E
1105                 --
1106                 -- But now the occurrence analyser will see just one occurrence
1107                 -- of poly_g, not inside a lambda, so the simplifier will
1108                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1109                 -- (I used to think that the "don't inline lone occurrences" stuff
1110                 --  would stop this happening, but since it's the *only* occurrence,
1111                 --  PreInlineUnconditionally kicks in first!)
1112                 --
1113                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1114                 --           to appear many times.  (NB: mkInlineMe eliminates
1115                 --           such notes on trivial RHSs, so do it manually.)
1116 -}
1117 \end{code}
1118
1119 %************************************************************************
1120 %*                                                                      *
1121                 prepareAlts
1122 %*                                                                      *
1123 %************************************************************************
1124
1125 prepareAlts tries these things:
1126
1127 1.  If several alternatives are identical, merge them into
1128     a single DEFAULT alternative.  I've occasionally seen this 
1129     making a big difference:
1130
1131         case e of               =====>     case e of
1132           C _ -> f x                         D v -> ....v....
1133           D v -> ....v....                   DEFAULT -> f x
1134           DEFAULT -> f x
1135
1136    The point is that we merge common RHSs, at least for the DEFAULT case.
1137    [One could do something more elaborate but I've never seen it needed.]
1138    To avoid an expensive test, we just merge branches equal to the *first*
1139    alternative; this picks up the common cases
1140         a) all branches equal
1141         b) some branches equal to the DEFAULT (which occurs first)
1142
1143 2.  Case merging:
1144        case e of b {             ==>   case e of b {
1145          p1 -> rhs1                      p1 -> rhs1
1146          ...                             ...
1147          pm -> rhsm                      pm -> rhsm
1148          _  -> case b of b' {            pn -> let b'=b in rhsn
1149                      pn -> rhsn          ...
1150                      ...                 po -> let b'=b in rhso
1151                      po -> rhso          _  -> let b'=b in rhsd
1152                      _  -> rhsd
1153        }  
1154     
1155     which merges two cases in one case when -- the default alternative of
1156     the outer case scrutises the same variable as the outer case This
1157     transformation is called Case Merging.  It avoids that the same
1158     variable is scrutinised multiple times.
1159
1160
1161 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1162
1163         x | p `is` 1 -> e1
1164           | p `is` 2 -> e2
1165         ...etc...
1166
1167 where @is@ was something like
1168         
1169         p `is` n = p /= (-1) && p == n
1170
1171 This gave rise to a horrible sequence of cases
1172
1173         case p of
1174           (-1) -> $j p
1175           1    -> e1
1176           DEFAULT -> $j p
1177
1178 and similarly in cascade for all the join points!
1179
1180 Note [Dead binders]
1181 ~~~~~~~~~~~~~~~~~~~~
1182 We do this *here*, looking at un-simplified alternatives, because we
1183 have to check that r doesn't mention the variables bound by the
1184 pattern in each alternative, so the binder-info is rather useful.
1185
1186 \begin{code}
1187 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1188 prepareAlts scrut case_bndr' alts
1189   = do  { dflags <- getDOptsSmpl
1190         ; alts <- combineIdenticalAlts case_bndr' alts
1191
1192         ; let (alts_wo_default, maybe_deflt) = findDefault alts
1193               alt_cons = [con | (con,_,_) <- alts_wo_default]
1194               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1195                 -- "imposs_deflt_cons" are handled either by the context, 
1196                 -- OR by a branch in this case expression.
1197                 -- Don't include DEFAULT!!
1198
1199         ; default_alts <- prepareDefault dflags scrut case_bndr' mb_tc_app 
1200                                          imposs_deflt_cons maybe_deflt
1201
1202         ; let trimmed_alts = filter possible_alt alts_wo_default
1203               merged_alts = mergeAlts default_alts trimmed_alts
1204                 -- We need the mergeAlts in case the new default_alt 
1205                 -- has turned into a constructor alternative.
1206                 -- The merge keeps the inner DEFAULT at the front, if there is one
1207                 -- and eliminates any inner_alts that are shadowed by the outer_alts
1208
1209
1210         ; return (imposs_deflt_cons, merged_alts) }
1211   where
1212     mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1213     Just (_, inst_tys) = mb_tc_app 
1214
1215     imposs_cons = case scrut of
1216                     Var v -> otherCons (idUnfolding v)
1217                     other -> []
1218
1219     possible_alt :: CoreAlt -> Bool
1220     possible_alt (con, _, _) | con `elem` imposs_cons = False
1221     possible_alt (DataAlt con, _, _) = dataConCanMatch inst_tys con
1222     possible_alt alt                = True
1223
1224
1225 --------------------------------------------------
1226 --      1. Merge identical branches
1227 --------------------------------------------------
1228 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1229
1230 combineIdenticalAlts case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1231   | all isDeadBinder bndrs1,                    -- Remember the default 
1232     length filtered_alts < length con_alts      -- alternative comes first
1233         -- Also Note [Dead binders]
1234   = do  { tick (AltMerge case_bndr)
1235         ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1236   where
1237     filtered_alts        = filter keep con_alts
1238     keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1239
1240 combineIdenticalAlts case_bndr alts = return alts
1241
1242 -------------------------------------------------------------------------
1243 --                      Prepare the default alternative
1244 -------------------------------------------------------------------------
1245 prepareDefault :: DynFlags
1246                -> OutExpr       -- Scrutinee
1247                -> OutId         -- Case binder; need just for its type. Note that as an
1248                                 --   OutId, it has maximum information; this is important.
1249                                 --   Test simpl013 is an example
1250                -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1251                -> [AltCon]      -- These cons can't happen when matching the default
1252                -> Maybe InExpr  -- Rhs
1253                -> SimplM [InAlt]        -- Still unsimplified
1254                                         -- We use a list because it's what mergeAlts expects,
1255                                         -- And becuase case-merging can cause many to show up
1256
1257 ------- Merge nested cases ----------
1258 prepareDefault dflags scrut outer_bndr bndr_ty imposs_cons (Just deflt_rhs)
1259   | dopt Opt_CaseMerge dflags
1260   , Case (Var scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1261   , scruting_same_var scrut_var
1262   = do  { tick (CaseMerge outer_bndr)
1263
1264         ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1265         ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts] }
1266         -- Warning: don't call prepareAlts recursively!
1267         -- Firstly, there's no point, because inner alts have already had
1268         -- mkCase applied to them, so they won't have a case in their default
1269         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1270         -- in munge_rhs may put a case into the DEFAULT branch!
1271   where
1272         -- We are scrutinising the same variable if it's
1273         -- the outer case-binder, or if the outer case scrutinises a variable
1274         -- (and it's the same).  Testing both allows us not to replace the
1275         -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1276     scruting_same_var = case scrut of
1277                           Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1278                           other           -> \ v -> v == outer_bndr
1279
1280 --------- Fill in known constructor -----------
1281 prepareDefault dflags scrut case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1282   |     -- This branch handles the case where we are 
1283         -- scrutinisng an algebraic data type
1284     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1285   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1286                                 --      case x of { DEFAULT -> e }
1287                                 -- and we don't want to fill in a default for them!
1288   , Just all_cons <- tyConDataCons_maybe tycon
1289   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1290                                 -- which GHC allows, then the case expression will have at most a default
1291                                 -- alternative.  We don't want to eliminate that alternative, because the
1292                                 -- invariant is that there's always one alternative.  It's more convenient
1293                                 -- to leave     
1294                                 --      case x of { DEFAULT -> e }     
1295                                 -- as it is, rather than transform it to
1296                                 --      error "case cant match"
1297                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1298                                 -- not worth wasting code on.
1299   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1300         is_possible con  = not (con `elem` imposs_data_cons)
1301                            && dataConCanMatch inst_tys con
1302   = case filter is_possible all_cons of
1303         []    -> return []      -- Eliminate the default alternative
1304                                 -- altogether if it can't match
1305
1306         [con] ->        -- It matches exactly one constructor, so fill it in
1307                  do { tick (FillInCaseDefault case_bndr)
1308                     ; us <- getUniquesSmpl
1309                     ; let (ex_tvs, co_tvs, arg_ids) =
1310                               dataConRepInstPat us con inst_tys
1311                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1312
1313         two_or_more -> return [(DEFAULT, [], deflt_rhs)]
1314
1315 --------- Catch-all cases -----------
1316 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons (Just deflt_rhs)
1317   = return [(DEFAULT, [], deflt_rhs)]
1318
1319 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons Nothing
1320   = return []   -- No default branch
1321 \end{code}
1322
1323
1324
1325 =================================================================================
1326
1327 mkCase tries these things
1328
1329 1.  Eliminate the case altogether if possible
1330
1331 2.  Case-identity:
1332
1333         case e of               ===> e
1334                 True  -> True;
1335                 False -> False
1336
1337     and similar friends.
1338
1339
1340 \begin{code}
1341 mkCase :: OutExpr -> OutId -> OutType
1342        -> [OutAlt]              -- Increasing order
1343        -> SimplM OutExpr
1344
1345 --------------------------------------------------
1346 --      1. Check for empty alternatives
1347 --------------------------------------------------
1348
1349 -- This isn't strictly an error.  It's possible that the simplifer might "see"
1350 -- that an inner case has no accessible alternatives before it "sees" that the
1351 -- entire branch of an outer case is inaccessible.  So we simply
1352 -- put an error case here insteadd
1353 mkCase scrut case_bndr ty []
1354   = pprTrace "mkCase: null alts" (ppr case_bndr <+> ppr scrut) $
1355     return (mkApps (Var eRROR_ID)
1356                    [Type ty, Lit (mkStringLit "Impossible alternative")])
1357
1358
1359 --------------------------------------------------
1360 --      2. Identity case
1361 --------------------------------------------------
1362
1363 mkCase scrut case_bndr ty alts  -- Identity case
1364   | all identity_alt alts
1365   = tick (CaseIdentity case_bndr)               `thenSmpl_`
1366     returnSmpl (re_cast scrut)
1367   where
1368     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1369
1370     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1371     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1372     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1373                                          || rhs `cheapEqExpr` Var case_bndr
1374     check_eq con args rhs = False
1375
1376     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1377
1378         -- We've seen this:
1379         --      case e of x { _ -> x `cast` c }
1380         -- And we definitely want to eliminate this case, to give
1381         --      e `cast` c
1382         -- So we throw away the cast from the RHS, and reconstruct
1383         -- it at the other end.  All the RHS casts must be the same
1384         -- if (all identity_alt alts) holds.
1385         -- 
1386         -- Don't worry about nested casts, because the simplifier combines them
1387     de_cast (Cast e _) = e
1388     de_cast e          = e
1389
1390     re_cast scrut = case head alts of
1391                         (_,_,Cast _ co) -> Cast scrut co
1392                         other           -> scrut
1393
1394
1395
1396 --------------------------------------------------
1397 --      Catch-all
1398 --------------------------------------------------
1399 mkCase scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1400 \end{code}
1401
1402
1403 When adding auxiliary bindings for the case binder, it's worth checking if
1404 its dead, because it often is, and occasionally these mkCase transformations
1405 cascade rather nicely.
1406
1407 \begin{code}
1408 bindCaseBndr bndr rhs body
1409   | isDeadBinder bndr = body
1410   | otherwise         = bindNonRec bndr rhs body
1411 \end{code}