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