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