Use MD5 checksums for recompilation checking (fixes #1372, #1959)
[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     interestingCtxt = ArgCtxt False 2   -- Give *some* incentive!
312
313     interesting (Select _ bndr _ _ _)
314         | isDeadBinder bndr       = CaseCtxt
315         | otherwise               = interestingCtxt
316                 
317     interesting (ApplyTo {})      = interestingCtxt
318                                 -- Can happen if we have (coerce t (f x)) y
319                                 -- Perhaps interestingCtxt is a bit over-keen, but I've
320                                 -- seen (coerce f) x, where f has an INLINE prag,
321                                 -- So we have to give some motivation for inlining it
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_RewriteRules 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 * We need to be careful if we just look at f's arity. Currently (Dec07),
938   f's arity is visible in its own RHS (see Note [Arity robustness] in 
939   SimplEnv) so we must *not* trust the arity when checking that 'f' is
940   a value.  Instead, look at the unfolding. 
941
942   However for GlobalIds we can look at the arity; and for primops we
943   must, since they have no unfolding.  
944
945 * Regardless of whether 'f' is a value, we always want to 
946   reduce (/\a -> f a) to f
947   This came up in a RULE: foldr (build (/\a -> g a))
948   did not match           foldr (build (/\b -> ...something complex...))
949   The type checker can insert these eta-expanded versions,
950   with both type and dictionary lambdas; hence the slightly 
951   ad-hoc isDictId
952
953 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
954 Alas.
955
956 \begin{code}
957 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
958 tryEtaReduce bndrs body 
959   = go (reverse bndrs) body
960   where
961     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
962     go []       fun           | ok_fun fun   = Just fun         -- Success!
963     go _        _                            = Nothing          -- Failure!
964
965         -- Note [Eta reduction conditions]
966     ok_fun (App fun (Type ty)) 
967         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
968         =  ok_fun fun
969     ok_fun (Var fun_id)
970         =  not (fun_id `elem` bndrs)
971         && (ok_fun_id fun_id || all ok_lam bndrs)
972     ok_fun _fun = False
973
974     ok_fun_id fun
975         | isLocalId fun       = isEvaldUnfolding (idUnfolding fun)
976         | isDataConWorkId fun = True
977         | isGlobalId fun      = idArity fun > 0
978         | otherwise           = panic "tryEtaReduce/ok_fun_id"
979
980     ok_lam v = isTyVar v || isDictId v
981
982     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
983 \end{code}
984
985
986 %************************************************************************
987 %*                                                                      *
988                 Eta expansion
989 %*                                                                      *
990 %************************************************************************
991
992
993 We go for:
994    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
995                                  (n >= 0)
996
997 where (in both cases) 
998
999         * The xi can include type variables
1000
1001         * The yi are all value variables
1002
1003         * N is a NORMAL FORM (i.e. no redexes anywhere)
1004           wanting a suitable number of extra args.
1005
1006 The biggest reason for doing this is for cases like
1007
1008         f = \x -> case x of
1009                     True  -> \y -> e1
1010                     False -> \y -> e2
1011
1012 Here we want to get the lambdas together.  A good exmaple is the nofib
1013 program fibheaps, which gets 25% more allocation if you don't do this
1014 eta-expansion.
1015
1016 We may have to sandwich some coerces between the lambdas
1017 to make the types work.   exprEtaExpandArity looks through coerces
1018 when computing arity; and etaExpand adds the coerces as necessary when
1019 actually computing the expansion.
1020
1021 \begin{code}
1022 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
1023 -- There is at least one runtime binder in the binders
1024 tryEtaExpansion dflags body = do
1025     us <- getUniquesM
1026     return (etaExpand fun_arity us body (exprType body))
1027   where
1028     fun_arity = exprEtaExpandArity dflags body
1029 \end{code}
1030
1031
1032 %************************************************************************
1033 %*                                                                      *
1034 \subsection{Floating lets out of big lambdas}
1035 %*                                                                      *
1036 %************************************************************************
1037
1038 Note [Floating and type abstraction]
1039 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1040 Consider this:
1041         x = /\a. C e1 e2
1042 We'd like to float this to 
1043         y1 = /\a. e1
1044         y2 = /\a. e2
1045         x  = /\a. C (y1 a) (y2 a)
1046 for the usual reasons: we want to inline x rather vigorously.
1047
1048 You may think that this kind of thing is rare.  But in some programs it is
1049 common.  For example, if you do closure conversion you might get:
1050
1051         data a :-> b = forall e. (e -> a -> b) :$ e
1052
1053         f_cc :: forall a. a :-> a
1054         f_cc = /\a. (\e. id a) :$ ()
1055
1056 Now we really want to inline that f_cc thing so that the
1057 construction of the closure goes away. 
1058
1059 So I have elaborated simplLazyBind to understand right-hand sides that look
1060 like
1061         /\ a1..an. body
1062
1063 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1064 but there is quite a bit of plumbing in simplLazyBind as well.
1065
1066 The same transformation is good when there are lets in the body:
1067
1068         /\abc -> let(rec) x = e in b
1069    ==>
1070         let(rec) x' = /\abc -> let x = x' a b c in e
1071         in 
1072         /\abc -> let x = x' a b c in b
1073
1074 This is good because it can turn things like:
1075
1076         let f = /\a -> letrec g = ... g ... in g
1077 into
1078         letrec g' = /\a -> ... g' a ...
1079         in
1080         let f = /\ a -> g' a
1081
1082 which is better.  In effect, it means that big lambdas don't impede
1083 let-floating.
1084
1085 This optimisation is CRUCIAL in eliminating the junk introduced by
1086 desugaring mutually recursive definitions.  Don't eliminate it lightly!
1087
1088 [May 1999]  If we do this transformation *regardless* then we can
1089 end up with some pretty silly stuff.  For example, 
1090
1091         let 
1092             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1093         in ..
1094 becomes
1095         let y1 = /\s -> r1
1096             y2 = /\s -> r2
1097             st = /\s -> ...[y1 s/x1, y2 s/x2]
1098         in ..
1099
1100 Unless the "..." is a WHNF there is really no point in doing this.
1101 Indeed it can make things worse.  Suppose x1 is used strictly,
1102 and is of the form
1103
1104         x1* = case f y of { (a,b) -> e }
1105
1106 If we abstract this wrt the tyvar we then can't do the case inline
1107 as we would normally do.
1108
1109 That's why the whole transformation is part of the same process that
1110 floats let-bindings and constructor arguments out of RHSs.  In particular,
1111 it is guarded by the doFloatFromRhs call in simplLazyBind.
1112
1113
1114 \begin{code}
1115 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1116 abstractFloats main_tvs body_env body
1117   = ASSERT( notNull body_floats )
1118     do  { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1119         ; return (float_binds, CoreSubst.substExpr subst body) }
1120   where
1121     main_tv_set = mkVarSet main_tvs
1122     body_floats = getFloats body_env
1123     empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1124
1125     abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1126     abstract subst (NonRec id rhs)
1127       = do { (poly_id, poly_app) <- mk_poly tvs_here id
1128            ; let poly_rhs = mkLams tvs_here rhs'
1129                  subst'   = CoreSubst.extendIdSubst subst id poly_app
1130            ; return (subst', (NonRec poly_id poly_rhs)) }
1131       where
1132         rhs' = CoreSubst.substExpr subst rhs
1133         tvs_here | any isCoVar main_tvs = main_tvs      -- Note [Abstract over coercions]
1134                  | otherwise 
1135                  = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1136         
1137                 -- Abstract only over the type variables free in the rhs
1138                 -- wrt which the new binding is abstracted.  But the naive
1139                 -- approach of abstract wrt the tyvars free in the Id's type
1140                 -- fails. Consider:
1141                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1142                 --                    x :: a     = fst t
1143                 --                in ...
1144                 -- Here, b isn't free in x's type, but we must nevertheless
1145                 -- abstract wrt b as well, because t's type mentions b.
1146                 -- Since t is floated too, we'd end up with the bogus:
1147                 --      poly_t = /\ a b -> (e1, e2)
1148                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1149                 -- So for now we adopt the even more naive approach of
1150                 -- abstracting wrt *all* the tyvars.  We'll see if that
1151                 -- gives rise to problems.   SLPJ June 98
1152
1153     abstract subst (Rec prs)
1154        = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1155             ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1156                   poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1157             ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1158        where
1159          (ids,rhss) = unzip prs
1160                 -- For a recursive group, it's a bit of a pain to work out the minimal
1161                 -- set of tyvars over which to abstract:
1162                 --      /\ a b c.  let x = ...a... in
1163                 --                 letrec { p = ...x...q...
1164                 --                          q = .....p...b... } in
1165                 --                 ...
1166                 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1167                 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.  
1168                 -- Since it's a pain, we just use the whole set, which is always safe
1169                 -- 
1170                 -- If you ever want to be more selective, remember this bizarre case too:
1171                 --      x::a = x
1172                 -- Here, we must abstract 'x' over 'a'.
1173          tvs_here = main_tvs
1174
1175     mk_poly tvs_here var
1176       = do { uniq <- getUniqueM
1177            ; let  poly_name = setNameUnique (idName var) uniq           -- Keep same name
1178                   poly_ty   = mkForAllTys tvs_here (idType var) -- But new type of course
1179                   poly_id   = transferPolyIdInfo var $  -- Note [transferPolyIdInfo] in Id.lhs
1180                               mkLocalId poly_name poly_ty 
1181            ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1182                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1183                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1184                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1185                 -- at already simplified code, so it doesn't matter
1186                 -- 
1187                 -- It's even right to retain single-occurrence or dead-var info:
1188                 -- Suppose we started with  /\a -> let x = E in B
1189                 -- where x occurs once in B. Then we transform to:
1190                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1191                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1192                 -- the occurrences of x' will be just the occurrences originally
1193                 -- pinned on x.
1194 \end{code}
1195
1196 Note [Abstract over coercions]
1197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1198 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1199 type variable a.  Rather than sort this mess out, we simply bale out and abstract
1200 wrt all the type variables if any of them are coercion variables.
1201
1202
1203 Historical note: if you use let-bindings instead of a substitution, beware of this:
1204
1205                 -- Suppose we start with:
1206                 --
1207                 --      x = /\ a -> let g = G in E
1208                 --
1209                 -- Then we'll float to get
1210                 --
1211                 --      x = let poly_g = /\ a -> G
1212                 --          in /\ a -> let g = poly_g a in E
1213                 --
1214                 -- But now the occurrence analyser will see just one occurrence
1215                 -- of poly_g, not inside a lambda, so the simplifier will
1216                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1217                 -- (I used to think that the "don't inline lone occurrences" stuff
1218                 --  would stop this happening, but since it's the *only* occurrence,
1219                 --  PreInlineUnconditionally kicks in first!)
1220                 --
1221                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1222                 --           to appear many times.  (NB: mkInlineMe eliminates
1223                 --           such notes on trivial RHSs, so do it manually.)
1224
1225 %************************************************************************
1226 %*                                                                      *
1227                 prepareAlts
1228 %*                                                                      *
1229 %************************************************************************
1230
1231 prepareAlts tries these things:
1232
1233 1.  If several alternatives are identical, merge them into
1234     a single DEFAULT alternative.  I've occasionally seen this 
1235     making a big difference:
1236
1237         case e of               =====>     case e of
1238           C _ -> f x                         D v -> ....v....
1239           D v -> ....v....                   DEFAULT -> f x
1240           DEFAULT -> f x
1241
1242    The point is that we merge common RHSs, at least for the DEFAULT case.
1243    [One could do something more elaborate but I've never seen it needed.]
1244    To avoid an expensive test, we just merge branches equal to the *first*
1245    alternative; this picks up the common cases
1246         a) all branches equal
1247         b) some branches equal to the DEFAULT (which occurs first)
1248
1249 2.  Case merging:
1250        case e of b {             ==>   case e of b {
1251          p1 -> rhs1                      p1 -> rhs1
1252          ...                             ...
1253          pm -> rhsm                      pm -> rhsm
1254          _  -> case b of b' {            pn -> let b'=b in rhsn
1255                      pn -> rhsn          ...
1256                      ...                 po -> let b'=b in rhso
1257                      po -> rhso          _  -> let b'=b in rhsd
1258                      _  -> rhsd
1259        }  
1260     
1261     which merges two cases in one case when -- the default alternative of
1262     the outer case scrutises the same variable as the outer case This
1263     transformation is called Case Merging.  It avoids that the same
1264     variable is scrutinised multiple times.
1265
1266
1267 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1268
1269         x | p `is` 1 -> e1
1270           | p `is` 2 -> e2
1271         ...etc...
1272
1273 where @is@ was something like
1274         
1275         p `is` n = p /= (-1) && p == n
1276
1277 This gave rise to a horrible sequence of cases
1278
1279         case p of
1280           (-1) -> $j p
1281           1    -> e1
1282           DEFAULT -> $j p
1283
1284 and similarly in cascade for all the join points!
1285
1286 Note [Dead binders]
1287 ~~~~~~~~~~~~~~~~~~~~
1288 We do this *here*, looking at un-simplified alternatives, because we
1289 have to check that r doesn't mention the variables bound by the
1290 pattern in each alternative, so the binder-info is rather useful.
1291
1292 \begin{code}
1293 prepareAlts :: SimplEnv -> OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1294 prepareAlts env scrut case_bndr' alts
1295   = do  { dflags <- getDOptsSmpl
1296         ; alts <- combineIdenticalAlts case_bndr' alts
1297
1298         ; let (alts_wo_default, maybe_deflt) = findDefault alts
1299               alt_cons = [con | (con,_,_) <- alts_wo_default]
1300               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1301                 -- "imposs_deflt_cons" are handled 
1302                 --   EITHER by the context, 
1303                 --   OR by a non-DEFAULT branch in this case expression.
1304
1305         ; default_alts <- prepareDefault dflags env case_bndr' mb_tc_app 
1306                                          imposs_deflt_cons maybe_deflt
1307
1308         ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1309               merged_alts = mergeAlts trimmed_alts default_alts
1310                 -- We need the mergeAlts in case the new default_alt 
1311                 -- has turned into a constructor alternative.
1312                 -- The merge keeps the inner DEFAULT at the front, if there is one
1313                 -- and interleaves the alternatives in the right order
1314
1315         ; return (imposs_deflt_cons, merged_alts) }
1316   where
1317     mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1318     Just (_, inst_tys) = mb_tc_app 
1319
1320     imposs_cons = case scrut of
1321                     Var v -> otherCons (idUnfolding v)
1322                     _     -> []
1323
1324     impossible_alt :: CoreAlt -> Bool
1325     impossible_alt (con, _, _) | con `elem` imposs_cons = True
1326     impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1327     impossible_alt _                   = False
1328
1329
1330 --------------------------------------------------
1331 --      1. Merge identical branches
1332 --------------------------------------------------
1333 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1334
1335 combineIdenticalAlts case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1336   | all isDeadBinder bndrs1,                    -- Remember the default 
1337     length filtered_alts < length con_alts      -- alternative comes first
1338         -- Also Note [Dead binders]
1339   = do  { tick (AltMerge case_bndr)
1340         ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1341   where
1342     filtered_alts        = filter keep con_alts
1343     keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1344
1345 combineIdenticalAlts _ alts = return alts
1346
1347 -------------------------------------------------------------------------
1348 --                      Prepare the default alternative
1349 -------------------------------------------------------------------------
1350 prepareDefault :: DynFlags
1351                -> SimplEnv
1352                -> OutId         -- Case binder; need just for its type. Note that as an
1353                                 --   OutId, it has maximum information; this is important.
1354                                 --   Test simpl013 is an example
1355                -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1356                -> [AltCon]      -- These cons can't happen when matching the default
1357                -> Maybe InExpr  -- Rhs
1358                -> SimplM [InAlt]        -- Still unsimplified
1359                                         -- We use a list because it's what mergeAlts expects,
1360                                         -- And becuase case-merging can cause many to show up
1361
1362 ------- Merge nested cases ----------
1363 prepareDefault dflags env outer_bndr _bndr_ty imposs_cons (Just deflt_rhs)
1364   | dopt Opt_CaseMerge dflags
1365   , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1366   , DoneId inner_scrut_var' <- substId env inner_scrut_var
1367         -- Remember, inner_scrut_var is an InId, but outer_bndr is an OutId
1368   , inner_scrut_var' == outer_bndr
1369         -- NB: the substId means that if the outer scrutinee was a 
1370         --     variable, and inner scrutinee is the same variable, 
1371         --     then inner_scrut_var' will be outer_bndr
1372         --     via the magic of simplCaseBinder
1373   = do  { tick (CaseMerge outer_bndr)
1374
1375         ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1376         ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1377                                                not (con `elem` imposs_cons) ]
1378                 -- NB: filter out any imposs_cons.  Example:
1379                 --      case x of 
1380                 --        A -> e1
1381                 --        DEFAULT -> case x of 
1382                 --                      A -> e2
1383                 --                      B -> e3
1384                 -- When we merge, we must ensure that e1 takes 
1385                 -- precedence over e2 as the value for A!  
1386         }
1387         -- Warning: don't call prepareAlts recursively!
1388         -- Firstly, there's no point, because inner alts have already had
1389         -- mkCase applied to them, so they won't have a case in their default
1390         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1391         -- in munge_rhs may put a case into the DEFAULT branch!
1392
1393
1394 --------- Fill in known constructor -----------
1395 prepareDefault _ _ case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1396   |     -- This branch handles the case where we are 
1397         -- scrutinisng an algebraic data type
1398     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1399   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1400                                 --      case x of { DEFAULT -> e }
1401                                 -- and we don't want to fill in a default for them!
1402   , Just all_cons <- tyConDataCons_maybe tycon
1403   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1404                                 -- which GHC allows, then the case expression will have at most a default
1405                                 -- alternative.  We don't want to eliminate that alternative, because the
1406                                 -- invariant is that there's always one alternative.  It's more convenient
1407                                 -- to leave     
1408                                 --      case x of { DEFAULT -> e }     
1409                                 -- as it is, rather than transform it to
1410                                 --      error "case cant match"
1411                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1412                                 -- not worth wasting code on.
1413   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1414         impossible con  = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1415   = case filterOut impossible all_cons of
1416         []    -> return []      -- Eliminate the default alternative
1417                                 -- altogether if it can't match
1418
1419         [con] ->        -- It matches exactly one constructor, so fill it in
1420                  do { tick (FillInCaseDefault case_bndr)
1421                     ; us <- getUniquesM
1422                     ; let (ex_tvs, co_tvs, arg_ids) =
1423                               dataConRepInstPat us con inst_tys
1424                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1425
1426         _ -> return [(DEFAULT, [], deflt_rhs)]
1427
1428   | debugIsOn, isAlgTyCon tycon, [] <- tyConDataCons tycon
1429   = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon <+> ppr deflt_rhs)
1430         $ return [(DEFAULT, [], deflt_rhs)]
1431
1432 --------- Catch-all cases -----------
1433 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1434   = return [(DEFAULT, [], deflt_rhs)]
1435
1436 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons Nothing
1437   = return []   -- No default branch
1438 \end{code}
1439
1440
1441
1442 =================================================================================
1443
1444 mkCase tries these things
1445
1446 1.  Eliminate the case altogether if possible
1447
1448 2.  Case-identity:
1449
1450         case e of               ===> e
1451                 True  -> True;
1452                 False -> False
1453
1454     and similar friends.
1455
1456
1457 \begin{code}
1458 mkCase :: OutExpr -> OutId -> [OutAlt]  -- Increasing order
1459        -> SimplM OutExpr
1460
1461 --------------------------------------------------
1462 --      2. Identity case
1463 --------------------------------------------------
1464
1465 mkCase scrut case_bndr alts     -- Identity case
1466   | all identity_alt alts
1467   = do tick (CaseIdentity case_bndr)
1468        return (re_cast scrut)
1469   where
1470     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1471
1472     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1473     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1474     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1475                                          || rhs `cheapEqExpr` Var case_bndr
1476     check_eq _ _ _ = False
1477
1478     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1479
1480         -- We've seen this:
1481         --      case e of x { _ -> x `cast` c }
1482         -- And we definitely want to eliminate this case, to give
1483         --      e `cast` c
1484         -- So we throw away the cast from the RHS, and reconstruct
1485         -- it at the other end.  All the RHS casts must be the same
1486         -- if (all identity_alt alts) holds.
1487         -- 
1488         -- Don't worry about nested casts, because the simplifier combines them
1489     de_cast (Cast e _) = e
1490     de_cast e          = e
1491
1492     re_cast scrut = case head alts of
1493                         (_,_,Cast _ co) -> Cast scrut co
1494                         _               -> scrut
1495
1496
1497
1498 --------------------------------------------------
1499 --      Catch-all
1500 --------------------------------------------------
1501 mkCase scrut bndr alts = return (Case scrut bndr (coreAltsType alts) alts)
1502 \end{code}
1503
1504
1505 When adding auxiliary bindings for the case binder, it's worth checking if
1506 its dead, because it often is, and occasionally these mkCase transformations
1507 cascade rather nicely.
1508
1509 \begin{code}
1510 bindCaseBndr :: Id -> CoreExpr -> CoreExpr -> CoreExpr
1511 bindCaseBndr bndr rhs body
1512   | isDeadBinder bndr = body
1513   | otherwise         = bindNonRec bndr rhs body
1514 \end{code}