Make -frewrite-rules into a dynamic flag; off for -O0
[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 Unify    ( dataConCannotMatch )
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)) $$ 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 :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
778 -- Nothing => No rules at all
779 activeRule dflags env
780   | not (dopt Opt_RewriteRules dflags)
781   = Nothing     -- Rewriting is off
782   | otherwise
783   = case getMode env of
784         SimplGently  -> Just isAlwaysActive
785                         -- Used to be Nothing (no rules in gentle mode)
786                         -- Main motivation for changing is that I wanted
787                         --      lift String ===> ...
788                         -- to work in Template Haskell when simplifying
789                         -- splices, so we get simpler code for literal strings
790         SimplPhase n -> Just (isActive n)
791 \end{code}
792
793
794 %************************************************************************
795 %*                                                                      *
796         Rebuilding a lambda
797 %*                                                                      *
798 %************************************************************************
799
800 \begin{code}
801 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
802 -- mkLam tries three things
803 --      a) eta reduction, if that gives a trivial expression
804 --      b) eta expansion [only if there are some value lambdas]
805
806 mkLam bndrs body
807   = do  { dflags <- getDOptsSmpl
808         ; mkLam' dflags bndrs body }
809   where
810     mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
811     mkLam' dflags bndrs (Cast body@(Lam _ _) co)
812         -- Note [Casts and lambdas]
813       = do { lam <- mkLam' dflags (bndrs ++ bndrs') body'
814            ; return (mkCoerce (mkPiTypes bndrs co) lam) }
815       where     
816         (bndrs',body') = collectBinders body
817
818     mkLam' dflags bndrs body
819       | dopt Opt_DoEtaReduction dflags,
820         Just etad_lam <- tryEtaReduce bndrs body
821       = do { tick (EtaReduction (head bndrs))
822            ; return etad_lam }
823
824       | dopt Opt_DoLambdaEtaExpansion dflags,
825         any isRuntimeVar bndrs
826       = do { body' <- tryEtaExpansion dflags body
827            ; return (mkLams bndrs body') }
828    
829       | otherwise 
830       = returnSmpl (mkLams bndrs body)
831 \end{code}
832
833 Note [Casts and lambdas]
834 ~~~~~~~~~~~~~~~~~~~~~~~~
835 Consider 
836         (\x. (\y. e) `cast` g1) `cast` g2
837 There is a danger here that the two lambdas look separated, and the 
838 full laziness pass might float an expression to between the two.
839
840 So this equation in mkLam' floats the g1 out, thus:
841         (\x. e `cast` g1)  -->  (\x.e) `cast` (tx -> g1)
842 where x:tx.
843
844 In general, this floats casts outside lambdas, where (I hope) they might meet
845 and cancel with some other cast.
846
847
848 --      c) floating lets out through big lambdas 
849 --              [only if all tyvar lambdas, and only if this lambda
850 --               is the RHS of a let]
851
852 {-      Sept 01: I'm experimenting with getting the
853         full laziness pass to float out past big lambdsa
854  | all isTyVar bndrs,   -- Only for big lambdas
855    contIsRhs cont       -- Only try the rhs type-lambda floating
856                         -- if this is indeed a right-hand side; otherwise
857                         -- we end up floating the thing out, only for float-in
858                         -- to float it right back in again!
859  = tryRhsTyLam env bndrs body           `thenSmpl` \ (floats, body') ->
860    returnSmpl (floats, mkLams bndrs body')
861 -}
862
863
864 %************************************************************************
865 %*                                                                      *
866 \subsection{Eta expansion and reduction}
867 %*                                                                      *
868 %************************************************************************
869
870 We try for eta reduction here, but *only* if we get all the 
871 way to an exprIsTrivial expression.    
872 We don't want to remove extra lambdas unless we are going 
873 to avoid allocating this thing altogether
874
875 \begin{code}
876 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
877 tryEtaReduce bndrs body 
878         -- We don't use CoreUtils.etaReduce, because we can be more
879         -- efficient here:
880         --  (a) we already have the binders
881         --  (b) we can do the triviality test before computing the free vars
882   = go (reverse bndrs) body
883   where
884     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
885     go []       fun           | ok_fun fun   = Just fun         -- Success!
886     go _        _                            = Nothing          -- Failure!
887
888     ok_fun fun =  exprIsTrivial fun
889                && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
890                && (exprIsHNF fun || all ok_lam bndrs)
891     ok_lam v = isTyVar v || isDictId v
892         -- The exprIsHNF is because eta reduction is not 
893         -- valid in general:  \x. bot  /=  bot
894         -- So we need to be sure that the "fun" is a value.
895         --
896         -- However, we always want to reduce (/\a -> f a) to f
897         -- This came up in a RULE: foldr (build (/\a -> g a))
898         --      did not match      foldr (build (/\b -> ...something complex...))
899         -- The type checker can insert these eta-expanded versions,
900         -- with both type and dictionary lambdas; hence the slightly 
901         -- ad-hoc isDictTy
902
903     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
904 \end{code}
905
906
907         Try eta expansion for RHSs
908
909 We go for:
910    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
911                                  (n >= 0)
912
913 where (in both cases) 
914
915         * The xi can include type variables
916
917         * The yi are all value variables
918
919         * N is a NORMAL FORM (i.e. no redexes anywhere)
920           wanting a suitable number of extra args.
921
922 We may have to sandwich some coerces between the lambdas
923 to make the types work.   exprEtaExpandArity looks through coerces
924 when computing arity; and etaExpand adds the coerces as necessary when
925 actually computing the expansion.
926
927 \begin{code}
928 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
929 -- There is at least one runtime binder in the binders
930 tryEtaExpansion dflags body
931   = getUniquesSmpl                      `thenSmpl` \ us ->
932     returnSmpl (etaExpand fun_arity us body (exprType body))
933   where
934     fun_arity = exprEtaExpandArity dflags body
935 \end{code}
936
937
938 %************************************************************************
939 %*                                                                      *
940 \subsection{Floating lets out of big lambdas}
941 %*                                                                      *
942 %************************************************************************
943
944 tryRhsTyLam tries this transformation, when the big lambda appears as
945 the RHS of a let(rec) binding:
946
947         /\abc -> let(rec) x = e in b
948    ==>
949         let(rec) x' = /\abc -> let x = x' a b c in e
950         in 
951         /\abc -> let x = x' a b c in b
952
953 This is good because it can turn things like:
954
955         let f = /\a -> letrec g = ... g ... in g
956 into
957         letrec g' = /\a -> ... g' a ...
958         in
959         let f = /\ a -> g' a
960
961 which is better.  In effect, it means that big lambdas don't impede
962 let-floating.
963
964 This optimisation is CRUCIAL in eliminating the junk introduced by
965 desugaring mutually recursive definitions.  Don't eliminate it lightly!
966
967 So far as the implementation is concerned:
968
969         Invariant: go F e = /\tvs -> F e
970         
971         Equalities:
972                 go F (Let x=e in b)
973                 = Let x' = /\tvs -> F e 
974                   in 
975                   go G b
976                 where
977                     G = F . Let x = x' tvs
978         
979                 go F (Letrec xi=ei in b)
980                 = Letrec {xi' = /\tvs -> G ei} 
981                   in
982                   go G b
983                 where
984                   G = F . Let {xi = xi' tvs}
985
986 [May 1999]  If we do this transformation *regardless* then we can
987 end up with some pretty silly stuff.  For example, 
988
989         let 
990             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
991         in ..
992 becomes
993         let y1 = /\s -> r1
994             y2 = /\s -> r2
995             st = /\s -> ...[y1 s/x1, y2 s/x2]
996         in ..
997
998 Unless the "..." is a WHNF there is really no point in doing this.
999 Indeed it can make things worse.  Suppose x1 is used strictly,
1000 and is of the form
1001
1002         x1* = case f y of { (a,b) -> e }
1003
1004 If we abstract this wrt the tyvar we then can't do the case inline
1005 as we would normally do.
1006
1007
1008 \begin{code}
1009 {-      Trying to do this in full laziness
1010
1011 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
1012 -- Call ensures that all the binders are type variables
1013
1014 tryRhsTyLam env tyvars body             -- Only does something if there's a let
1015   |  not (all isTyVar tyvars)
1016   || not (worth_it body)                -- inside a type lambda, 
1017   = returnSmpl (emptyFloats env, body)  -- and a WHNF inside that
1018
1019   | otherwise
1020   = go env (\x -> x) body
1021
1022   where
1023     worth_it e@(Let _ _) = whnf_in_middle e
1024     worth_it e           = False
1025
1026     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
1027     whnf_in_middle (Let _ e) = whnf_in_middle e
1028     whnf_in_middle e         = exprIsCheap e
1029
1030     main_tyvar_set = mkVarSet tyvars
1031
1032     go env fn (Let bind@(NonRec var rhs) body)
1033       | exprIsTrivial rhs
1034       = go env (fn . Let bind) body
1035
1036     go env fn (Let (NonRec var rhs) body)
1037       = mk_poly tyvars_here var                                                 `thenSmpl` \ (var', rhs') ->
1038         addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs)))        $ \ env -> 
1039         go env (fn . Let (mk_silly_bind var rhs')) body
1040
1041       where
1042
1043         tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1044                 -- Abstract only over the type variables free in the rhs
1045                 -- wrt which the new binding is abstracted.  But the naive
1046                 -- approach of abstract wrt the tyvars free in the Id's type
1047                 -- fails. Consider:
1048                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1049                 --                    x :: a     = fst t
1050                 --                in ...
1051                 -- Here, b isn't free in x's type, but we must nevertheless
1052                 -- abstract wrt b as well, because t's type mentions b.
1053                 -- Since t is floated too, we'd end up with the bogus:
1054                 --      poly_t = /\ a b -> (e1, e2)
1055                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1056                 -- So for now we adopt the even more naive approach of
1057                 -- abstracting wrt *all* the tyvars.  We'll see if that
1058                 -- gives rise to problems.   SLPJ June 98
1059
1060     go env fn (Let (Rec prs) body)
1061        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
1062          let
1063             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1064             pairs   = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1065          in
1066          addAuxiliaryBind env (Rec pairs)               $ \ env ->
1067          go env gn body 
1068        where
1069          (vars,rhss) = unzip prs
1070          tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1071                 -- See notes with tyvars_here above
1072
1073     go env fn body = returnSmpl (emptyFloats env, fn body)
1074
1075     mk_poly tyvars_here var
1076       = getUniqueSmpl           `thenSmpl` \ uniq ->
1077         let
1078             poly_name = setNameUnique (idName var) uniq         -- Keep same name
1079             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
1080             poly_id   = mkLocalId poly_name poly_ty 
1081
1082                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1083                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1084                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1085                 -- at already simplified code, so it doesn't matter
1086                 -- 
1087                 -- It's even right to retain single-occurrence or dead-var info:
1088                 -- Suppose we started with  /\a -> let x = E in B
1089                 -- where x occurs once in B. Then we transform to:
1090                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1091                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1092                 -- the occurrences of x' will be just the occurrences originally
1093                 -- pinned on x.
1094         in
1095         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1096
1097     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1098                 -- Suppose we start with:
1099                 --
1100                 --      x = /\ a -> let g = G in E
1101                 --
1102                 -- Then we'll float to get
1103                 --
1104                 --      x = let poly_g = /\ a -> G
1105                 --          in /\ a -> let g = poly_g a in E
1106                 --
1107                 -- But now the occurrence analyser will see just one occurrence
1108                 -- of poly_g, not inside a lambda, so the simplifier will
1109                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1110                 -- (I used to think that the "don't inline lone occurrences" stuff
1111                 --  would stop this happening, but since it's the *only* occurrence,
1112                 --  PreInlineUnconditionally kicks in first!)
1113                 --
1114                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1115                 --           to appear many times.  (NB: mkInlineMe eliminates
1116                 --           such notes on trivial RHSs, so do it manually.)
1117 -}
1118 \end{code}
1119
1120 %************************************************************************
1121 %*                                                                      *
1122                 prepareAlts
1123 %*                                                                      *
1124 %************************************************************************
1125
1126 prepareAlts tries these things:
1127
1128 1.  If several alternatives are identical, merge them into
1129     a single DEFAULT alternative.  I've occasionally seen this 
1130     making a big difference:
1131
1132         case e of               =====>     case e of
1133           C _ -> f x                         D v -> ....v....
1134           D v -> ....v....                   DEFAULT -> f x
1135           DEFAULT -> f x
1136
1137    The point is that we merge common RHSs, at least for the DEFAULT case.
1138    [One could do something more elaborate but I've never seen it needed.]
1139    To avoid an expensive test, we just merge branches equal to the *first*
1140    alternative; this picks up the common cases
1141         a) all branches equal
1142         b) some branches equal to the DEFAULT (which occurs first)
1143
1144 2.  Case merging:
1145        case e of b {             ==>   case e of b {
1146          p1 -> rhs1                      p1 -> rhs1
1147          ...                             ...
1148          pm -> rhsm                      pm -> rhsm
1149          _  -> case b of b' {            pn -> let b'=b in rhsn
1150                      pn -> rhsn          ...
1151                      ...                 po -> let b'=b in rhso
1152                      po -> rhso          _  -> let b'=b in rhsd
1153                      _  -> rhsd
1154        }  
1155     
1156     which merges two cases in one case when -- the default alternative of
1157     the outer case scrutises the same variable as the outer case This
1158     transformation is called Case Merging.  It avoids that the same
1159     variable is scrutinised multiple times.
1160
1161
1162 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1163
1164         x | p `is` 1 -> e1
1165           | p `is` 2 -> e2
1166         ...etc...
1167
1168 where @is@ was something like
1169         
1170         p `is` n = p /= (-1) && p == n
1171
1172 This gave rise to a horrible sequence of cases
1173
1174         case p of
1175           (-1) -> $j p
1176           1    -> e1
1177           DEFAULT -> $j p
1178
1179 and similarly in cascade for all the join points!
1180
1181 Note [Dead binders]
1182 ~~~~~~~~~~~~~~~~~~~~
1183 We do this *here*, looking at un-simplified alternatives, because we
1184 have to check that r doesn't mention the variables bound by the
1185 pattern in each alternative, so the binder-info is rather useful.
1186
1187 \begin{code}
1188 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1189 prepareAlts scrut case_bndr' alts
1190   = do  { dflags <- getDOptsSmpl
1191         ; alts <- combineIdenticalAlts case_bndr' alts
1192
1193         ; let (alts_wo_default, maybe_deflt) = findDefault alts
1194               alt_cons = [con | (con,_,_) <- alts_wo_default]
1195               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1196                 -- "imposs_deflt_cons" are handled 
1197                 --   EITHER by the context, 
1198                 --   OR by a non-DEFAULT branch in this case expression.
1199
1200         ; default_alts <- prepareDefault dflags scrut case_bndr' mb_tc_app 
1201                                          imposs_deflt_cons maybe_deflt
1202
1203         ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1204               merged_alts = mergeAlts trimmed_alts default_alts
1205                 -- We need the mergeAlts in case the new default_alt 
1206                 -- has turned into a constructor alternative.
1207                 -- The merge keeps the inner DEFAULT at the front, if there is one
1208                 -- and interleaves the alternatives in the right order
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     impossible_alt :: CoreAlt -> Bool
1220     impossible_alt (con, _, _) | con `elem` imposs_cons = True
1221     impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1222     impossible_alt alt                 = False
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                                                not (con `elem` imposs_cons) ]
1267                 -- NB: filter out any imposs_cons.  Example:
1268                 --      case x of 
1269                 --        A -> e1
1270                 --        DEFAULT -> case x of 
1271                 --                      A -> e2
1272                 --                      B -> e3
1273                 -- When we merge, we must ensure that e1 takes 
1274                 -- precedence over e2 as the value for A!  
1275         }
1276         -- Warning: don't call prepareAlts recursively!
1277         -- Firstly, there's no point, because inner alts have already had
1278         -- mkCase applied to them, so they won't have a case in their default
1279         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1280         -- in munge_rhs may put a case into the DEFAULT branch!
1281   where
1282         -- We are scrutinising the same variable if it's
1283         -- the outer case-binder, or if the outer case scrutinises a variable
1284         -- (and it's the same).  Testing both allows us not to replace the
1285         -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1286     scruting_same_var = case scrut of
1287                           Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1288                           other           -> \ v -> v == outer_bndr
1289
1290 --------- Fill in known constructor -----------
1291 prepareDefault dflags scrut case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1292   |     -- This branch handles the case where we are 
1293         -- scrutinisng an algebraic data type
1294     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1295   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1296                                 --      case x of { DEFAULT -> e }
1297                                 -- and we don't want to fill in a default for them!
1298   , Just all_cons <- tyConDataCons_maybe tycon
1299   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1300                                 -- which GHC allows, then the case expression will have at most a default
1301                                 -- alternative.  We don't want to eliminate that alternative, because the
1302                                 -- invariant is that there's always one alternative.  It's more convenient
1303                                 -- to leave     
1304                                 --      case x of { DEFAULT -> e }     
1305                                 -- as it is, rather than transform it to
1306                                 --      error "case cant match"
1307                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1308                                 -- not worth wasting code on.
1309   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1310         impossible con  = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1311   = case filterOut impossible all_cons of
1312         []    -> return []      -- Eliminate the default alternative
1313                                 -- altogether if it can't match
1314
1315         [con] ->        -- It matches exactly one constructor, so fill it in
1316                  do { tick (FillInCaseDefault case_bndr)
1317                     ; us <- getUniquesSmpl
1318                     ; let (ex_tvs, co_tvs, arg_ids) =
1319                               dataConRepInstPat us con inst_tys
1320                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1321
1322         two_or_more -> return [(DEFAULT, [], deflt_rhs)]
1323
1324 --------- Catch-all cases -----------
1325 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons (Just deflt_rhs)
1326   = return [(DEFAULT, [], deflt_rhs)]
1327
1328 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons Nothing
1329   = return []   -- No default branch
1330 \end{code}
1331
1332
1333
1334 =================================================================================
1335
1336 mkCase tries these things
1337
1338 1.  Eliminate the case altogether if possible
1339
1340 2.  Case-identity:
1341
1342         case e of               ===> e
1343                 True  -> True;
1344                 False -> False
1345
1346     and similar friends.
1347
1348
1349 \begin{code}
1350 mkCase :: OutExpr -> OutId -> OutType
1351        -> [OutAlt]              -- Increasing order
1352        -> SimplM OutExpr
1353
1354 --------------------------------------------------
1355 --      1. Check for empty alternatives
1356 --------------------------------------------------
1357
1358 -- This isn't strictly an error.  It's possible that the simplifer might "see"
1359 -- that an inner case has no accessible alternatives before it "sees" that the
1360 -- entire branch of an outer case is inaccessible.  So we simply
1361 -- put an error case here insteadd
1362 mkCase scrut case_bndr ty []
1363   = pprTrace "mkCase: null alts" (ppr case_bndr <+> ppr scrut) $
1364     return (mkApps (Var rUNTIME_ERROR_ID)
1365                    [Type ty, Lit (mkStringLit "Impossible alternative")])
1366
1367
1368 --------------------------------------------------
1369 --      2. Identity case
1370 --------------------------------------------------
1371
1372 mkCase scrut case_bndr ty alts  -- Identity case
1373   | all identity_alt alts
1374   = tick (CaseIdentity case_bndr)               `thenSmpl_`
1375     returnSmpl (re_cast scrut)
1376   where
1377     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1378
1379     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1380     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1381     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1382                                          || rhs `cheapEqExpr` Var case_bndr
1383     check_eq con args rhs = False
1384
1385     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1386
1387         -- We've seen this:
1388         --      case e of x { _ -> x `cast` c }
1389         -- And we definitely want to eliminate this case, to give
1390         --      e `cast` c
1391         -- So we throw away the cast from the RHS, and reconstruct
1392         -- it at the other end.  All the RHS casts must be the same
1393         -- if (all identity_alt alts) holds.
1394         -- 
1395         -- Don't worry about nested casts, because the simplifier combines them
1396     de_cast (Cast e _) = e
1397     de_cast e          = e
1398
1399     re_cast scrut = case head alts of
1400                         (_,_,Cast _ co) -> Cast scrut co
1401                         other           -> scrut
1402
1403
1404
1405 --------------------------------------------------
1406 --      Catch-all
1407 --------------------------------------------------
1408 mkCase scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1409 \end{code}
1410
1411
1412 When adding auxiliary bindings for the case binder, it's worth checking if
1413 its dead, because it often is, and occasionally these mkCase transformations
1414 cascade rather nicely.
1415
1416 \begin{code}
1417 bindCaseBndr bndr rhs body
1418   | isDeadBinder bndr = body
1419   | otherwise         = bindNonRec bndr rhs body
1420 \end{code}