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