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