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