[project @ 2001-07-23 10:54:46 by simonpj]
[ghc-hetmet.git] / ghc / 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         simplBinder, simplBinders, simplRecIds, simplLetId,
9         tryRhsTyLam, tryEtaExpansion,
10         mkCase,
11
12         -- The continuation type
13         SimplCont(..), DupFlag(..), contIsDupable, contResultType,
14         countValArgs, countArgs, mkRhsStop, mkStop,
15         getContArgs, interestingCallContext, interestingArg, isStrictType, discardInline
16
17     ) where
18
19 #include "HsVersions.h"
20
21 import CmdLineOpts      ( switchIsOn, SimplifierSwitch(..),
22                           opt_SimplDoLambdaEtaExpansion, opt_SimplCaseMerge, 
23                           opt_UF_UpdateInPlace
24                         )
25 import CoreSyn
26 import CoreUtils        ( exprIsTrivial, cheapEqExpr, exprType, exprIsCheap, 
27                           etaExpand, exprEtaExpandArity, bindNonRec, mkCoerce,
28                           findDefault
29                         )
30 import Subst            ( InScopeSet, mkSubst, substExpr )
31 import qualified Subst  ( simplBndrs, simplBndr, simplLetId )
32 import Id               ( idType, idName, 
33                           idUnfolding, idNewStrictness,
34                           mkLocalId, idInfo
35                         )
36 import IdInfo           ( StrictnessInfo(..) )
37 import Maybes           ( maybeToBool, catMaybes )
38 import Name             ( setNameUnique )
39 import NewDemand        ( isStrictDmd, isBotRes, splitStrictSig )
40 import SimplMonad
41 import Type             ( Type, mkForAllTys, seqType, 
42                           splitTyConApp_maybe, tyConAppArgs, mkTyVarTys,
43                           isUnLiftedType,
44                           splitRepFunTys
45                         )
46 import TcType           ( isStrictType )
47 import TyCon            ( tyConDataConsIfAvailable )
48 import DataCon          ( dataConRepArity )
49 import VarEnv           ( SubstEnv )
50 import Util             ( lengthExceeds, mapAccumL )
51 import Outputable
52 \end{code}
53
54
55 %************************************************************************
56 %*                                                                      *
57 \subsection{The continuation data type}
58 %*                                                                      *
59 %************************************************************************
60
61 \begin{code}
62 data SimplCont          -- Strict contexts
63   = Stop     OutType            -- Type of the result
64              Bool               -- True => This is the RHS of a thunk whose type suggests
65                                 --         that update-in-place would be possible
66                                 --         (This makes the inliner a little keener.)
67
68   | CoerceIt OutType                    -- The To-type, simplified
69              SimplCont
70
71   | InlinePlease                        -- This continuation makes a function very
72              SimplCont                  -- keen to inline itelf
73
74   | ApplyTo  DupFlag 
75              InExpr SubstEnv            -- The argument, as yet unsimplified, 
76              SimplCont                  -- and its subst-env
77
78   | Select   DupFlag 
79              InId [InAlt] SubstEnv      -- The case binder, alts, and subst-env
80              SimplCont
81
82   | ArgOf    DupFlag            -- An arbitrary strict context: the argument 
83                                 --      of a strict function, or a primitive-arg fn
84                                 --      or a PrimOp
85              OutType            -- cont_ty: the type of the expression being sought by the context
86                                 --      f (error "foo") ==> coerce t (error "foo")
87                                 -- when f is strict
88                                 -- We need to know the type t, to which to coerce.
89              (OutExpr -> SimplM OutExprStuff)   -- What to do with the result
90                                 -- The result expression in the OutExprStuff has type cont_ty
91
92 instance Outputable SimplCont where
93   ppr (Stop _ _)                     = ptext SLIT("Stop")
94   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
95   ppr (ArgOf   dup _ _)              = ptext SLIT("ArgOf...") <+> ppr dup
96   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
97                                        (nest 4 (ppr alts)) $$ ppr cont
98   ppr (CoerceIt ty cont)             = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
99   ppr (InlinePlease cont)            = ptext SLIT("InlinePlease") $$ ppr cont
100
101 data DupFlag = OkToDup | NoDup
102
103 instance Outputable DupFlag where
104   ppr OkToDup = ptext SLIT("ok")
105   ppr NoDup   = ptext SLIT("nodup")
106
107
108 -------------------
109 mkRhsStop, mkStop :: OutType -> SimplCont
110 mkStop    ty = Stop ty False
111 mkRhsStop ty = Stop ty (canUpdateInPlace ty)
112
113
114 -------------------
115 contIsDupable :: SimplCont -> Bool
116 contIsDupable (Stop _ _)                 = True
117 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
118 contIsDupable (ArgOf    OkToDup _ _)     = True
119 contIsDupable (Select   OkToDup _ _ _ _) = True
120 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
121 contIsDupable (InlinePlease cont)        = contIsDupable cont
122 contIsDupable other                      = False
123
124 -------------------
125 discardInline :: SimplCont -> SimplCont
126 discardInline (InlinePlease cont)  = cont
127 discardInline (ApplyTo d e s cont) = ApplyTo d e s (discardInline cont)
128 discardInline cont                 = cont
129
130 -------------------
131 discardableCont :: SimplCont -> Bool
132 discardableCont (Stop _ _)          = False
133 discardableCont (CoerceIt _ cont)   = discardableCont cont
134 discardableCont (InlinePlease cont) = discardableCont cont
135 discardableCont other               = True
136
137 discardCont :: SimplCont        -- A continuation, expecting
138             -> SimplCont        -- Replace the continuation with a suitable coerce
139 discardCont cont = case cont of
140                      Stop to_ty _ -> cont
141                      other        -> CoerceIt to_ty (mkStop to_ty)
142                  where
143                    to_ty = contResultType cont
144
145 -------------------
146 contResultType :: SimplCont -> OutType
147 contResultType (Stop to_ty _)        = to_ty
148 contResultType (ArgOf _ to_ty _)     = to_ty
149 contResultType (ApplyTo _ _ _ cont)  = contResultType cont
150 contResultType (CoerceIt _ cont)     = contResultType cont
151 contResultType (InlinePlease cont)   = contResultType cont
152 contResultType (Select _ _ _ _ cont) = contResultType cont
153
154 -------------------
155 countValArgs :: SimplCont -> Int
156 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
157 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
158 countValArgs other                         = 0
159
160 countArgs :: SimplCont -> Int
161 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
162 countArgs other                   = 0
163 \end{code}
164
165
166 \begin{code}
167 getContArgs :: OutId -> SimplCont 
168             -> SimplM ([(InExpr, SubstEnv, Bool)],      -- Arguments; the Bool is true for strict args
169                         SimplCont,                      -- Remaining continuation
170                         Bool)                           -- Whether we came across an InlineCall
171 -- getContArgs id k = (args, k', inl)
172 --      args are the leading ApplyTo items in k
173 --      (i.e. outermost comes first)
174 --      augmented with demand info from the functionn
175 getContArgs fun orig_cont
176   = getSwitchChecker    `thenSmpl` \ chkr ->
177     let
178                 -- Ignore strictness info if the no-case-of-case
179                 -- flag is on.  Strictness changes evaluation order
180                 -- and that can change full laziness
181         stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
182                 | otherwise                    = computed_stricts
183     in
184     go [] stricts False orig_cont
185   where
186     ----------------------------
187
188         -- Type argument
189     go acc ss inl (ApplyTo _ arg@(Type _) se cont)
190         = go ((arg,se,False) : acc) ss inl cont
191                 -- NB: don't bother to instantiate the function type
192
193         -- Value argument
194     go acc (s:ss) inl (ApplyTo _ arg se cont)
195         = go ((arg,se,s) : acc) ss inl cont
196
197         -- An Inline continuation
198     go acc ss inl (InlinePlease cont)
199         = go acc ss True cont
200
201         -- We're run out of arguments, or else we've run out of demands
202         -- The latter only happens if the result is guaranteed bottom
203         -- This is the case for
204         --      * case (error "hello") of { ... }
205         --      * (error "Hello") arg
206         --      * f (error "Hello") where f is strict
207         --      etc
208     go acc ss inl cont 
209         | null ss && discardableCont cont = tick BottomFound    `thenSmpl_`
210                                             returnSmpl (reverse acc, discardCont cont, inl)
211         | otherwise                       = returnSmpl (reverse acc, cont,             inl)
212
213     ----------------------------
214     vanilla_stricts, computed_stricts :: [Bool]
215     vanilla_stricts  = repeat False
216     computed_stricts = zipWith (||) fun_stricts arg_stricts
217
218     ----------------------------
219     (val_arg_tys, _) = splitRepFunTys (idType fun)
220     arg_stricts      = map isStrictType val_arg_tys ++ repeat False
221         -- These argument types are used as a cheap and cheerful way to find
222         -- unboxed arguments, which must be strict.  But it's an InType
223         -- and so there might be a type variable where we expect a function
224         -- type (the substitution hasn't happened yet).  And we don't bother
225         -- doing the type applications for a polymorphic function.
226         -- Hence the split*Rep*FunTys
227
228     ----------------------------
229         -- If fun_stricts is finite, it means the function returns bottom
230         -- after that number of value args have been consumed
231         -- Otherwise it's infinite, extended with False
232     fun_stricts
233       = case splitStrictSig (idNewStrictness fun) of
234           (demands, result_info)
235                 | not (demands `lengthExceeds` countValArgs orig_cont)
236                 ->      -- Enough args, use the strictness given.
237                         -- For bottoming functions we used to pretend that the arg
238                         -- is lazy, so that we don't treat the arg as an
239                         -- interesting context.  This avoids substituting
240                         -- top-level bindings for (say) strings into 
241                         -- calls to error.  But now we are more careful about
242                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
243                    if isBotRes result_info then
244                         map isStrictDmd demands         -- Finite => result is bottom
245                    else
246                         map isStrictDmd demands ++ vanilla_stricts
247
248           other -> vanilla_stricts      -- Not enough args, or no strictness
249
250 -------------------
251 interestingArg :: InScopeSet -> InExpr -> SubstEnv -> Bool
252         -- An argument is interesting if it has *some* structure
253         -- We are here trying to avoid unfolding a function that
254         -- is applied only to variables that have no unfolding
255         -- (i.e. they are probably lambda bound): f x y z
256         -- There is little point in inlining f here.
257 interestingArg in_scope arg subst
258   = analyse (substExpr (mkSubst in_scope subst) arg)
259         -- 'analyse' only looks at the top part of the result
260         -- and substExpr is lazy, so this isn't nearly as brutal
261         -- as it looks.
262   where
263     analyse (Var v)           = hasSomeUnfolding (idUnfolding v)
264                                 -- Was: isValueUnfolding (idUnfolding v')
265                                 -- But that seems over-pessimistic
266     analyse (Type _)          = False
267     analyse (App fn (Type _)) = analyse fn
268     analyse (Note _ a)        = analyse a
269     analyse other             = True
270         -- Consider     let x = 3 in f x
271         -- The substitution will contain (x -> ContEx 3), and we want to
272         -- to say that x is an interesting argument.
273         -- But consider also (\x. f x y) y
274         -- The substitution will contain (x -> ContEx y), and we want to say
275         -- that x is not interesting (assuming y has no unfolding)
276 \end{code}
277
278 Comment about interestingCallContext
279 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
280 We want to avoid inlining an expression where there can't possibly be
281 any gain, such as in an argument position.  Hence, if the continuation
282 is interesting (eg. a case scrutinee, application etc.) then we
283 inline, otherwise we don't.  
284
285 Previously some_benefit used to return True only if the variable was
286 applied to some value arguments.  This didn't work:
287
288         let x = _coerce_ (T Int) Int (I# 3) in
289         case _coerce_ Int (T Int) x of
290                 I# y -> ....
291
292 we want to inline x, but can't see that it's a constructor in a case
293 scrutinee position, and some_benefit is False.
294
295 Another example:
296
297 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
298
299 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
300
301 we'd really like to inline dMonadST here, but we *don't* want to
302 inline if the case expression is just
303
304         case x of y { DEFAULT -> ... }
305
306 since we can just eliminate this case instead (x is in WHNF).  Similar
307 applies when x is bound to a lambda expression.  Hence
308 contIsInteresting looks for case expressions with just a single
309 default case.
310
311 \begin{code}
312 interestingCallContext :: Bool          -- False <=> no args at all
313                        -> Bool          -- False <=> no value args
314                        -> SimplCont -> Bool
315         -- The "lone-variable" case is important.  I spent ages
316         -- messing about with unsatisfactory varaints, but this is nice.
317         -- The idea is that if a variable appear all alone
318         --      as an arg of lazy fn, or rhs    Stop
319         --      as scrutinee of a case          Select
320         --      as arg of a strict fn           ArgOf
321         -- then we should not inline it (unless there is some other reason,
322         -- e.g. is is the sole occurrence).  We achieve this by making
323         -- interestingCallContext return False for a lone variable.
324         --
325         -- Why?  At least in the case-scrutinee situation, turning
326         --      let x = (a,b) in case x of y -> ...
327         -- into
328         --      let x = (a,b) in case (a,b) of y -> ...
329         -- and thence to 
330         --      let x = (a,b) in let y = (a,b) in ...
331         -- is bad if the binding for x will remain.
332         --
333         -- Another example: I discovered that strings
334         -- were getting inlined straight back into applications of 'error'
335         -- because the latter is strict.
336         --      s = "foo"
337         --      f = \x -> ...(error s)...
338
339         -- Fundamentally such contexts should not ecourage inlining becuase
340         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
341         -- so there's no gain.
342         --
343         -- However, even a type application or coercion isn't a lone variable.
344         -- Consider
345         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
346         -- We had better inline that sucker!  The case won't see through it.
347         --
348         -- For now, I'm treating treating a variable applied to types 
349         -- in a *lazy* context "lone". The motivating example was
350         --      f = /\a. \x. BIG
351         --      g = /\a. \y.  h (f a)
352         -- There's no advantage in inlining f here, and perhaps
353         -- a significant disadvantage.  Hence some_val_args in the Stop case
354
355 interestingCallContext some_args some_val_args cont
356   = interesting cont
357   where
358     interesting (InlinePlease _)       = True
359     interesting (Select _ _ _ _ _)     = some_args
360     interesting (ApplyTo _ _ _ _)      = True   -- Can happen if we have (coerce t (f x)) y
361                                                 -- Perhaps True is a bit over-keen, but I've
362                                                 -- seen (coerce f) x, where f has an INLINE prag,
363                                                 -- So we have to give some motivaiton for inlining it
364     interesting (ArgOf _ _ _)          = some_val_args
365     interesting (Stop ty upd_in_place) = some_val_args && upd_in_place
366     interesting (CoerceIt _ cont)      = interesting cont
367         -- If this call is the arg of a strict function, the context
368         -- is a bit interesting.  If we inline here, we may get useful
369         -- evaluation information to avoid repeated evals: e.g.
370         --      x + (y * z)
371         -- Here the contIsInteresting makes the '*' keener to inline,
372         -- which in turn exposes a constructor which makes the '+' inline.
373         -- Assuming that +,* aren't small enough to inline regardless.
374         --
375         -- It's also very important to inline in a strict context for things
376         -- like
377         --              foldr k z (f x)
378         -- Here, the context of (f x) is strict, and if f's unfolding is
379         -- a build it's *great* to inline it here.  So we must ensure that
380         -- the context for (f x) is not totally uninteresting.
381
382
383 -------------------
384 canUpdateInPlace :: Type -> Bool
385 -- Consider   let x = <wurble> in ...
386 -- If <wurble> returns an explicit constructor, we might be able
387 -- to do update in place.  So we treat even a thunk RHS context
388 -- as interesting if update in place is possible.  We approximate
389 -- this by seeing if the type has a single constructor with a
390 -- small arity.  But arity zero isn't good -- we share the single copy
391 -- for that case, so no point in sharing.
392
393 canUpdateInPlace ty 
394   | not opt_UF_UpdateInPlace = False
395   | otherwise
396   = case splitTyConApp_maybe ty of 
397         Nothing         -> False 
398         Just (tycon, _) -> case tyConDataConsIfAvailable tycon of
399                                 [dc]  -> arity == 1 || arity == 2
400                                       where
401                                          arity = dataConRepArity dc
402                                 other -> False
403 \end{code}
404
405
406
407 %************************************************************************
408 %*                                                                      *
409 \section{Dealing with a single binder}
410 %*                                                                      *
411 %************************************************************************
412
413 \begin{code}
414 simplBinders :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
415 simplBinders bndrs thing_inside
416   = getSubst            `thenSmpl` \ subst ->
417     let
418         (subst', bndrs') = Subst.simplBndrs subst bndrs
419     in
420     seqBndrs bndrs'     `seq`
421     setSubst subst' (thing_inside bndrs')
422
423 simplBinder :: InBinder -> (OutBinder -> SimplM a) -> SimplM a
424 simplBinder bndr thing_inside
425   = getSubst            `thenSmpl` \ subst ->
426     let
427         (subst', bndr') = Subst.simplBndr subst bndr
428     in
429     seqBndr bndr'       `seq`
430     setSubst subst' (thing_inside bndr')
431
432
433 simplRecIds :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
434 simplRecIds ids thing_inside
435   = getSubst            `thenSmpl` \ subst ->
436     let
437         (subst', ids') = mapAccumL Subst.simplLetId subst ids
438     in
439     seqBndrs ids'       `seq`
440     setSubst subst' (thing_inside ids')
441
442 simplLetId :: InBinder -> (OutBinder -> SimplM a) -> SimplM a
443 simplLetId id thing_inside
444   = getSubst            `thenSmpl` \ subst ->
445     let
446         (subst', id') = Subst.simplLetId subst id
447     in
448     seqBndr id' `seq`
449     setSubst subst' (thing_inside id')
450
451 seqBndrs [] = ()
452 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
453
454 seqBndr b | isTyVar b = b `seq` ()
455           | otherwise = seqType (idType b)      `seq`
456                         idInfo b                `seq`
457                         ()
458 \end{code}
459
460
461 %************************************************************************
462 %*                                                                      *
463 \subsection{Local tyvar-lifting}
464 %*                                                                      *
465 %************************************************************************
466
467 mkRhsTyLam tries this transformation, when the big lambda appears as
468 the RHS of a let(rec) binding:
469
470         /\abc -> let(rec) x = e in b
471    ==>
472         let(rec) x' = /\abc -> let x = x' a b c in e
473         in 
474         /\abc -> let x = x' a b c in b
475
476 This is good because it can turn things like:
477
478         let f = /\a -> letrec g = ... g ... in g
479 into
480         letrec g' = /\a -> ... g' a ...
481         in
482         let f = /\ a -> g' a
483
484 which is better.  In effect, it means that big lambdas don't impede
485 let-floating.
486
487 This optimisation is CRUCIAL in eliminating the junk introduced by
488 desugaring mutually recursive definitions.  Don't eliminate it lightly!
489
490 So far as the implementation is concerned:
491
492         Invariant: go F e = /\tvs -> F e
493         
494         Equalities:
495                 go F (Let x=e in b)
496                 = Let x' = /\tvs -> F e 
497                   in 
498                   go G b
499                 where
500                     G = F . Let x = x' tvs
501         
502                 go F (Letrec xi=ei in b)
503                 = Letrec {xi' = /\tvs -> G ei} 
504                   in
505                   go G b
506                 where
507                   G = F . Let {xi = xi' tvs}
508
509 [May 1999]  If we do this transformation *regardless* then we can
510 end up with some pretty silly stuff.  For example, 
511
512         let 
513             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
514         in ..
515 becomes
516         let y1 = /\s -> r1
517             y2 = /\s -> r2
518             st = /\s -> ...[y1 s/x1, y2 s/x2]
519         in ..
520
521 Unless the "..." is a WHNF there is really no point in doing this.
522 Indeed it can make things worse.  Suppose x1 is used strictly,
523 and is of the form
524
525         x1* = case f y of { (a,b) -> e }
526
527 If we abstract this wrt the tyvar we then can't do the case inline
528 as we would normally do.
529
530
531 \begin{code}
532 tryRhsTyLam :: OutExpr -> SimplM ([OutBind], OutExpr)
533
534 tryRhsTyLam rhs                         -- Only does something if there's a let
535   | null tyvars || not (worth_it body)  -- inside a type lambda, 
536   = returnSmpl ([], rhs)                -- and a WHNF inside that
537
538   | otherwise
539   = go (\x -> x) body           `thenSmpl` \ (binds, body') ->
540     returnSmpl (binds,  mkLams tyvars body')
541
542   where
543     (tyvars, body) = collectTyBinders rhs
544
545     worth_it e@(Let _ _) = whnf_in_middle e
546     worth_it e           = False
547
548     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
549     whnf_in_middle (Let _ e) = whnf_in_middle e
550     whnf_in_middle e         = exprIsCheap e
551
552     go fn (Let bind@(NonRec var rhs) body)
553       | exprIsTrivial rhs
554       = go (fn . Let bind) body
555
556     go fn (Let (NonRec var rhs) body)
557       = mk_poly tyvars_here var                         `thenSmpl` \ (var', rhs') ->
558         go (fn . Let (mk_silly_bind var rhs')) body     `thenSmpl` \ (binds, body') ->
559         returnSmpl (NonRec var' (mkLams tyvars_here (fn rhs)) : binds, body')
560
561       where
562         tyvars_here = tyvars
563                 --      main_tyvar_set = mkVarSet tyvars
564                 --      var_ty = idType var
565                 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfType var_ty)
566                 -- tyvars_here was an attempt to reduce the number of tyvars
567                 -- wrt which the new binding is abstracted.  But the naive
568                 -- approach of abstract wrt the tyvars free in the Id's type
569                 -- fails. Consider:
570                 --      /\ a b -> let t :: (a,b) = (e1, e2)
571                 --                    x :: a     = fst t
572                 --                in ...
573                 -- Here, b isn't free in x's type, but we must nevertheless
574                 -- abstract wrt b as well, because t's type mentions b.
575                 -- Since t is floated too, we'd end up with the bogus:
576                 --      poly_t = /\ a b -> (e1, e2)
577                 --      poly_x = /\ a   -> fst (poly_t a *b*)
578                 -- So for now we adopt the even more naive approach of
579                 -- abstracting wrt *all* the tyvars.  We'll see if that
580                 -- gives rise to problems.   SLPJ June 98
581
582     go fn (Let (Rec prs) body)
583        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
584          let
585             gn body  = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
586             new_bind = Rec (vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss])
587          in
588          go gn body                             `thenSmpl` \ (binds, body') -> 
589          returnSmpl (new_bind : binds, body')
590        where
591          (vars,rhss) = unzip prs
592          tyvars_here = tyvars
593                 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfTypes var_tys)
594                 --       var_tys     = map idType vars
595                 -- See notes with tyvars_here above
596
597     go fn body = returnSmpl ([], fn body)
598
599     mk_poly tyvars_here var
600       = getUniqueSmpl           `thenSmpl` \ uniq ->
601         let
602             poly_name = setNameUnique (idName var) uniq         -- Keep same name
603             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
604             poly_id   = mkLocalId poly_name poly_ty 
605
606                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
607                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
608                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
609                 -- at already simplified code, so it doesn't matter
610                 -- 
611                 -- It's even right to retain single-occurrence or dead-var info:
612                 -- Suppose we started with  /\a -> let x = E in B
613                 -- where x occurs once in B. Then we transform to:
614                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
615                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
616                 -- the occurrences of x' will be just the occurrences originally
617                 -- pinned on x.
618         in
619         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
620
621     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
622                 -- Suppose we start with:
623                 --
624                 --      x = /\ a -> let g = G in E
625                 --
626                 -- Then we'll float to get
627                 --
628                 --      x = let poly_g = /\ a -> G
629                 --          in /\ a -> let g = poly_g a in E
630                 --
631                 -- But now the occurrence analyser will see just one occurrence
632                 -- of poly_g, not inside a lambda, so the simplifier will
633                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
634                 -- (I used to think that the "don't inline lone occurrences" stuff
635                 --  would stop this happening, but since it's the *only* occurrence,
636                 --  PreInlineUnconditionally kicks in first!)
637                 --
638                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
639                 --           to appear many times.  (NB: mkInlineMe eliminates
640                 --           such notes on trivial RHSs, so do it manually.)
641 \end{code}
642
643
644 %************************************************************************
645 %*                                                                      *
646 \subsection{Eta expansion}
647 %*                                                                      *
648 %************************************************************************
649
650         Try eta expansion for RHSs
651
652 We go for:
653    Case 1    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
654                  (n >= 0)
655      OR         
656    Case 2    f = N E1..En      ==>   z1=E1
657                  (n > 0)                 .. 
658                                      zn=En
659                                      f = \y1..ym -> N z1..zn y1..ym
660
661 where (in both cases) 
662
663         * The xi can include type variables
664
665         * The yi are all value variables
666
667         * N is a NORMAL FORM (i.e. no redexes anywhere)
668           wanting a suitable number of extra args.
669
670         * the Ei must not have unlifted type
671
672 There is no point in looking for a combination of the two, because
673 that would leave use with some lets sandwiched between lambdas; that's
674 what the final test in the first equation is for.
675
676 In Case 1, we may have to sandwich some coerces between the lambdas
677 to make the types work.   exprEtaExpandArity looks through coerces
678 when computing arity; and etaExpand adds the coerces as necessary when
679 actually computing the expansion.
680
681 \begin{code}
682 tryEtaExpansion :: OutExpr -> OutType -> SimplM ([OutBind], OutExpr)
683 tryEtaExpansion rhs rhs_ty
684   |  not opt_SimplDoLambdaEtaExpansion          -- Not if switched off
685   || exprIsTrivial rhs                          -- Not if RHS is trivial
686   || final_arity == 0                           -- Not if arity is zero
687   = returnSmpl ([], rhs)
688
689   | n_val_args == 0 && not arity_is_manifest
690   =     -- Some lambdas but not enough: case 1
691     getUniqSupplySmpl                           `thenSmpl` \ us ->
692     returnSmpl ([], etaExpand final_arity us rhs rhs_ty)
693
694   | n_val_args > 0 && not (any cant_bind arg_infos)
695   =     -- Partial application: case 2
696     mapAndUnzipSmpl bind_z_arg arg_infos        `thenSmpl` \ (maybe_z_binds, z_args) ->
697     getUniqSupplySmpl                           `thenSmpl` \ us ->
698     returnSmpl (catMaybes maybe_z_binds, 
699                 etaExpand final_arity us (mkApps fun z_args) rhs_ty)
700
701   | otherwise
702   = returnSmpl ([], rhs)
703   where
704     (fun, args)                    = collectArgs rhs
705     n_val_args                     = valArgCount args
706     (fun_arity, arity_is_manifest) = exprEtaExpandArity fun
707     final_arity                    = 0 `max` (fun_arity - n_val_args)
708     arg_infos                      = [(arg, exprType arg, exprIsTrivial arg) | arg <- args]
709     cant_bind (_, ty, triv)        = not triv && isUnLiftedType ty
710
711     bind_z_arg (arg, arg_ty, trivial_arg) 
712         | trivial_arg = returnSmpl (Nothing, arg)
713         | otherwise   = newId SLIT("z") arg_ty  $ \ z ->
714                         returnSmpl (Just (NonRec z arg), Var z)
715 \end{code}
716
717
718 %************************************************************************
719 %*                                                                      *
720 \subsection{Case absorption and identity-case elimination}
721 %*                                                                      *
722 %************************************************************************
723
724 \begin{code}
725 mkCase :: OutExpr -> OutId -> [OutAlt] -> SimplM OutExpr
726 \end{code}
727
728 @mkCase@ tries the following transformation (if possible):
729
730 case e of b {             ==>   case e of b {
731   p1 -> rhs1                      p1 -> rhs1
732   ...                             ...
733   pm -> rhsm                      pm -> rhsm
734   _  -> case b of b' {            pn -> rhsn[b/b'] {or (alg)  let b=b' in rhsn}
735                                                    {or (prim) case b of b' { _ -> rhsn}}
736               pn -> rhsn          ...
737               ...                 po -> rhso[b/b']
738               po -> rhso          _  -> rhsd[b/b'] {or let b'=b in rhsd}
739               _  -> rhsd
740 }
741
742 which merges two cases in one case when -- the default alternative of
743 the outer case scrutises the same variable as the outer case This
744 transformation is called Case Merging.  It avoids that the same
745 variable is scrutinised multiple times.
746
747 \begin{code}
748 mkCase scrut outer_bndr outer_alts
749   |  opt_SimplCaseMerge
750   && maybeToBool maybe_case_in_default
751      
752   = tick (CaseMerge outer_bndr)         `thenSmpl_`
753     returnSmpl (Case scrut outer_bndr new_alts)
754         -- Warning: don't call mkCase recursively!
755         -- Firstly, there's no point, because inner alts have already had
756         -- mkCase applied to them, so they won't have a case in their default
757         -- Secondly, if you do, you get an infinite loop, because the bindNonRec
758         -- in munge_rhs puts a case into the DEFAULT branch!
759   where
760     new_alts = add_default maybe_inner_default
761                            (outer_alts_without_deflt ++ inner_con_alts)
762
763     maybe_case_in_default = case findDefault outer_alts of
764                                 (outer_alts_without_default,
765                                  Just (Case (Var scrut_var) inner_bndr inner_alts))
766                                    | outer_bndr == scrut_var
767                                    -> Just (outer_alts_without_default, inner_bndr, inner_alts)
768                                 other -> Nothing
769
770     Just (outer_alts_without_deflt, inner_bndr, inner_alts) = maybe_case_in_default
771
772                 --  Eliminate any inner alts which are shadowed by the outer ones
773     outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
774
775     munged_inner_alts = [ (con, args, munge_rhs rhs) 
776                         | (con, args, rhs) <- inner_alts, 
777                            not (con `elem` outer_cons)  -- Eliminate shadowed inner alts
778                         ]
779     munge_rhs rhs = bindNonRec inner_bndr (Var outer_bndr) rhs
780
781     (inner_con_alts, maybe_inner_default) = findDefault munged_inner_alts
782
783     add_default (Just rhs) alts = (DEFAULT,[],rhs) : alts
784     add_default Nothing    alts = alts
785 \end{code}
786
787 Now the identity-case transformation:
788
789         case e of               ===> e
790                 True  -> True;
791                 False -> False
792
793 and similar friends.
794
795 \begin{code}
796 mkCase scrut case_bndr alts
797   | all identity_alt alts
798   = tick (CaseIdentity case_bndr)               `thenSmpl_`
799     returnSmpl (re_note scrut)
800   where
801     identity_alt (con, args, rhs) = de_note rhs `cheapEqExpr` identity_rhs con args
802
803     identity_rhs (DataAlt con) args = mkConApp con (arg_tys ++ map varToCoreExpr args)
804     identity_rhs (LitAlt lit)  _    = Lit lit
805     identity_rhs DEFAULT       _    = Var case_bndr
806
807     arg_tys = map Type (tyConAppArgs (idType case_bndr))
808
809         -- We've seen this:
810         --      case coerce T e of x { _ -> coerce T' x }
811         -- And we definitely want to eliminate this case!
812         -- So we throw away notes from the RHS, and reconstruct
813         -- (at least an approximation) at the other end
814     de_note (Note _ e) = de_note e
815     de_note e          = e
816
817         -- re_note wraps a coerce if it might be necessary
818     re_note scrut = case head alts of
819                         (_,_,rhs1@(Note _ _)) -> mkCoerce (exprType rhs1) (idType case_bndr) scrut
820                         other                 -> scrut
821 \end{code}
822
823 The catch-all case.  We do a final transformation that I've
824 occasionally seen making a big difference:
825
826         case e of               =====>     case e of
827           C _ -> f x                         D v -> ....v....
828           D v -> ....v....                   DEFAULT -> f x
829           DEFAULT -> f x
830
831 The point is that we merge common RHSs, at least for the DEFAULT case.
832 [One could do something more elaborate but I've never seen it needed.]
833 The case where this came up was like this (lib/std/PrelCError.lhs):
834
835         x | p `is` 1 -> e1
836           | p `is` 2 -> e2
837         ...etc...
838
839 where @is@ was something like
840         
841         p `is` n = p /= (-1) && p == n
842
843 This gave rise to a horrible sequence of cases
844
845         case p of
846           (-1) -> $j p
847           1    -> e1
848           DEFAULT -> $j p
849
850 and similarly in cascade for all the join points!
851           
852 \begin{code}
853 mkCase other_scrut case_bndr other_alts
854   = returnSmpl (Case other_scrut case_bndr (mergeDefault other_alts))
855
856 mergeDefault (deflt_alt@(DEFAULT,_,deflt_rhs) : con_alts)
857   = deflt_alt : [alt | alt@(con,_,rhs) <- con_alts, not (rhs `cheapEqExpr` deflt_rhs)]
858         -- NB: we can neglect the binders because we won't get equality if the
859         -- binders are mentioned in rhs (no shadowing)
860 mergeDefault other_alts
861   = other_alts
862 \end{code}