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