[project @ 2001-09-26 16:19:28 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, simplLamBinders,
9         tryEtaExpansion,
10         newId, mkLam, mkCase,
11
12         -- The continuation type
13         SimplCont(..), DupFlag(..), LetRhsFlag(..), 
14         contIsDupable, contResultType,
15         countValArgs, countArgs, 
16         mkBoringStop, mkStop, contIsRhs, contIsRhsOrArg,
17         getContArgs, interestingCallContext, interestingArg, isStrictType, discardInline
18
19     ) where
20
21 #include "HsVersions.h"
22
23 import CmdLineOpts      ( SimplifierSwitch(..),
24                           opt_SimplDoLambdaEtaExpansion, opt_SimplDoEtaReduction,
25                           opt_SimplCaseMerge, opt_UF_UpdateInPlace
26                         )
27 import CoreSyn
28 import CoreFVs          ( exprSomeFreeVars, exprsSomeFreeVars )
29 import CoreUtils        ( exprIsTrivial, cheapEqExpr, exprType, exprIsCheap, 
30                           etaExpand, exprEtaExpandArity, bindNonRec, mkCoerce,
31                           findDefault, exprOkForSpeculation, exprIsValue
32                         )
33 import Subst            ( InScopeSet, mkSubst, substExpr )
34 import qualified Subst  ( simplBndrs, simplBndr, simplLetId, simplLamBndr )
35 import Id               ( Id, idType, idName, 
36                           mkSysLocal, hasNoBinding, isDeadBinder, idNewDemandInfo,
37                           idUnfolding, idNewStrictness,
38                           mkLocalId, idInfo
39                         )
40 import Name             ( setNameUnique )
41 import NewDemand        ( isStrictDmd, isBotRes, splitStrictSig )
42 import SimplMonad
43 import Type             ( Type, mkForAllTys, seqType, 
44                           splitTyConApp_maybe, tyConAppArgs, mkTyVarTys,
45                           isUnLiftedType, splitRepFunTys, isStrictType
46                         )
47 import OccName          ( UserFS )
48 import TyCon            ( tyConDataConsIfAvailable, isDataTyCon )
49 import DataCon          ( dataConRepArity, dataConSig, dataConArgTys )
50 import Var              ( mkSysTyVar, tyVarKind )
51 import VarEnv           ( SubstEnv )
52 import VarSet           ( mkVarSet, varSetElems, intersectVarSet )
53 import Util             ( lengthExceeds, mapAccumL )
54 import Outputable
55 \end{code}
56
57
58 %************************************************************************
59 %*                                                                      *
60 \subsection{The continuation data type}
61 %*                                                                      *
62 %************************************************************************
63
64 \begin{code}
65 data SimplCont          -- Strict contexts
66   = Stop     OutType            -- Type of the result
67              LetRhsFlag
68              Bool               -- True <=> This is the RHS of a thunk whose type suggests
69                                 --          that update-in-place would be possible
70                                 --          (This makes the inliner a little keener.)
71
72   | CoerceIt OutType                    -- The To-type, simplified
73              SimplCont
74
75   | InlinePlease                        -- This continuation makes a function very
76              SimplCont                  -- keen to inline itelf
77
78   | ApplyTo  DupFlag 
79              InExpr SimplEnv            -- The argument, as yet unsimplified, 
80              SimplCont                  -- and its environment
81
82   | Select   DupFlag 
83              InId [InAlt] SimplEnv      -- The case binder, alts, and subst-env
84              SimplCont
85
86   | ArgOf    DupFlag            -- An arbitrary strict context: the argument 
87                                 --      of a strict function, or a primitive-arg fn
88                                 --      or a PrimOp
89              LetRhsFlag
90              OutType            -- cont_ty: the type of the expression being sought by the context
91                                 --      f (error "foo") ==> coerce t (error "foo")
92                                 -- when f is strict
93                                 -- We need to know the type t, to which to coerce.
94              (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)     -- What to do with the result
95                                 -- The result expression in the OutExprStuff has type cont_ty
96
97 data LetRhsFlag = AnArg         -- It's just an argument not a let RHS
98                 | AnRhs         -- It's the RHS of a let (so please float lets out of big lambdas)
99
100 instance Outputable LetRhsFlag where
101   ppr AnArg = ptext SLIT("arg")
102   ppr AnRhs = ptext SLIT("rhs")
103
104 instance Outputable SimplCont where
105   ppr (Stop _ is_rhs _)              = ptext SLIT("Stop") <> brackets (ppr is_rhs)
106   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
107   ppr (ArgOf   dup _ _ _)            = ptext SLIT("ArgOf...") <+> ppr dup
108   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
109                                        (nest 4 (ppr alts)) $$ ppr cont
110   ppr (CoerceIt ty cont)             = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
111   ppr (InlinePlease cont)            = ptext SLIT("InlinePlease") $$ ppr cont
112
113 data DupFlag = OkToDup | NoDup
114
115 instance Outputable DupFlag where
116   ppr OkToDup = ptext SLIT("ok")
117   ppr NoDup   = ptext SLIT("nodup")
118
119
120 -------------------
121 mkBoringStop :: OutType -> SimplCont
122 mkBoringStop ty = Stop ty AnArg (canUpdateInPlace ty)
123
124 mkStop :: OutType -> LetRhsFlag -> SimplCont
125 mkStop ty is_rhs = Stop ty is_rhs (canUpdateInPlace ty)
126
127 contIsRhs :: SimplCont -> Bool
128 contIsRhs (Stop _ AnRhs _)    = True
129 contIsRhs (ArgOf _ AnRhs _ _) = True
130 contIsRhs other               = False
131
132 contIsRhsOrArg (Stop _ _ _)    = True
133 contIsRhsOrArg (ArgOf _ _ _ _) = True
134 contIsRhsOrArg other           = False
135
136 -------------------
137 contIsDupable :: SimplCont -> Bool
138 contIsDupable (Stop _ _ _)               = True
139 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
140 contIsDupable (ArgOf    OkToDup _ _ _)   = True
141 contIsDupable (Select   OkToDup _ _ _ _) = True
142 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
143 contIsDupable (InlinePlease cont)        = contIsDupable cont
144 contIsDupable other                      = False
145
146 -------------------
147 discardInline :: SimplCont -> SimplCont
148 discardInline (InlinePlease cont)  = cont
149 discardInline (ApplyTo d e s cont) = ApplyTo d e s (discardInline cont)
150 discardInline cont                 = cont
151
152 -------------------
153 discardableCont :: SimplCont -> Bool
154 discardableCont (Stop _ _ _)        = False
155 discardableCont (CoerceIt _ cont)   = discardableCont cont
156 discardableCont (InlinePlease cont) = discardableCont cont
157 discardableCont other               = True
158
159 discardCont :: SimplCont        -- A continuation, expecting
160             -> SimplCont        -- Replace the continuation with a suitable coerce
161 discardCont cont = case cont of
162                      Stop to_ty is_rhs _ -> cont
163                      other               -> CoerceIt to_ty (mkBoringStop to_ty)
164                  where
165                    to_ty = contResultType cont
166
167 -------------------
168 contResultType :: SimplCont -> OutType
169 contResultType (Stop to_ty _ _)      = to_ty
170 contResultType (ArgOf _ _ to_ty _)   = to_ty
171 contResultType (ApplyTo _ _ _ cont)  = contResultType cont
172 contResultType (CoerceIt _ cont)     = contResultType cont
173 contResultType (InlinePlease cont)   = contResultType cont
174 contResultType (Select _ _ _ _ cont) = contResultType cont
175
176 -------------------
177 countValArgs :: SimplCont -> Int
178 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
179 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
180 countValArgs other                         = 0
181
182 countArgs :: SimplCont -> Int
183 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
184 countArgs other                   = 0
185 \end{code}
186
187
188 \begin{code}
189 getContArgs :: SwitchChecker
190             -> OutId -> SimplCont 
191             -> ([(InExpr, SimplEnv, Bool)],     -- Arguments; the Bool is true for strict args
192                 SimplCont,                      -- Remaining continuation
193                 Bool)                           -- Whether we came across an InlineCall
194 -- getContArgs id k = (args, k', inl)
195 --      args are the leading ApplyTo items in k
196 --      (i.e. outermost comes first)
197 --      augmented with demand info from the functionn
198 getContArgs chkr fun orig_cont
199   = let
200                 -- Ignore strictness info if the no-case-of-case
201                 -- flag is on.  Strictness changes evaluation order
202                 -- and that can change full laziness
203         stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
204                 | otherwise                    = computed_stricts
205     in
206     go [] stricts False orig_cont
207   where
208     ----------------------------
209
210         -- Type argument
211     go acc ss inl (ApplyTo _ arg@(Type _) se cont)
212         = go ((arg,se,False) : acc) ss inl cont
213                 -- NB: don't bother to instantiate the function type
214
215         -- Value argument
216     go acc (s:ss) inl (ApplyTo _ arg se cont)
217         = go ((arg,se,s) : acc) ss inl cont
218
219         -- An Inline continuation
220     go acc ss inl (InlinePlease cont)
221         = go acc ss True cont
222
223         -- We're run out of arguments, or else we've run out of demands
224         -- The latter only happens if the result is guaranteed bottom
225         -- This is the case for
226         --      * case (error "hello") of { ... }
227         --      * (error "Hello") arg
228         --      * f (error "Hello") where f is strict
229         --      etc
230     go acc ss inl cont 
231         | null ss && discardableCont cont = (reverse acc, discardCont cont, inl)
232         | otherwise                       = (reverse acc, cont,             inl)
233
234     ----------------------------
235     vanilla_stricts, computed_stricts :: [Bool]
236     vanilla_stricts  = repeat False
237     computed_stricts = zipWith (||) fun_stricts arg_stricts
238
239     ----------------------------
240     (val_arg_tys, _) = splitRepFunTys (idType fun)
241     arg_stricts      = map isStrictType val_arg_tys ++ repeat False
242         -- These argument types are used as a cheap and cheerful way to find
243         -- unboxed arguments, which must be strict.  But it's an InType
244         -- and so there might be a type variable where we expect a function
245         -- type (the substitution hasn't happened yet).  And we don't bother
246         -- doing the type applications for a polymorphic function.
247         -- Hence the split*Rep*FunTys
248
249     ----------------------------
250         -- If fun_stricts is finite, it means the function returns bottom
251         -- after that number of value args have been consumed
252         -- Otherwise it's infinite, extended with False
253     fun_stricts
254       = case splitStrictSig (idNewStrictness fun) of
255           (demands, result_info)
256                 | not (demands `lengthExceeds` countValArgs orig_cont)
257                 ->      -- Enough args, use the strictness given.
258                         -- For bottoming functions we used to pretend that the arg
259                         -- is lazy, so that we don't treat the arg as an
260                         -- interesting context.  This avoids substituting
261                         -- top-level bindings for (say) strings into 
262                         -- calls to error.  But now we are more careful about
263                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
264                    if isBotRes result_info then
265                         map isStrictDmd demands         -- Finite => result is bottom
266                    else
267                         map isStrictDmd demands ++ vanilla_stricts
268
269           other -> vanilla_stricts      -- Not enough args, or no strictness
270
271 -------------------
272 interestingArg :: InScopeSet -> InExpr -> SubstEnv -> Bool
273         -- An argument is interesting if it has *some* structure
274         -- We are here trying to avoid unfolding a function that
275         -- is applied only to variables that have no unfolding
276         -- (i.e. they are probably lambda bound): f x y z
277         -- There is little point in inlining f here.
278 interestingArg in_scope arg subst
279   = analyse (substExpr (mkSubst in_scope subst) arg)
280         -- 'analyse' only looks at the top part of the result
281         -- and substExpr is lazy, so this isn't nearly as brutal
282         -- as it looks.
283   where
284     analyse (Var v)           = hasSomeUnfolding (idUnfolding v)
285                                 -- Was: isValueUnfolding (idUnfolding v')
286                                 -- But that seems over-pessimistic
287     analyse (Type _)          = False
288     analyse (App fn (Type _)) = analyse fn
289     analyse (Note _ a)        = analyse a
290     analyse other             = True
291         -- Consider     let x = 3 in f x
292         -- The substitution will contain (x -> ContEx 3), and we want to
293         -- to say that x is an interesting argument.
294         -- But consider also (\x. f x y) y
295         -- The substitution will contain (x -> ContEx y), and we want to say
296         -- that x is not interesting (assuming y has no unfolding)
297 \end{code}
298
299 Comment about interestingCallContext
300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
301 We want to avoid inlining an expression where there can't possibly be
302 any gain, such as in an argument position.  Hence, if the continuation
303 is interesting (eg. a case scrutinee, application etc.) then we
304 inline, otherwise we don't.  
305
306 Previously some_benefit used to return True only if the variable was
307 applied to some value arguments.  This didn't work:
308
309         let x = _coerce_ (T Int) Int (I# 3) in
310         case _coerce_ Int (T Int) x of
311                 I# y -> ....
312
313 we want to inline x, but can't see that it's a constructor in a case
314 scrutinee position, and some_benefit is False.
315
316 Another example:
317
318 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
319
320 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
321
322 we'd really like to inline dMonadST here, but we *don't* want to
323 inline if the case expression is just
324
325         case x of y { DEFAULT -> ... }
326
327 since we can just eliminate this case instead (x is in WHNF).  Similar
328 applies when x is bound to a lambda expression.  Hence
329 contIsInteresting looks for case expressions with just a single
330 default case.
331
332 \begin{code}
333 interestingCallContext :: Bool          -- False <=> no args at all
334                        -> Bool          -- False <=> no value args
335                        -> SimplCont -> Bool
336         -- The "lone-variable" case is important.  I spent ages
337         -- messing about with unsatisfactory varaints, but this is nice.
338         -- The idea is that if a variable appear all alone
339         --      as an arg of lazy fn, or rhs    Stop
340         --      as scrutinee of a case          Select
341         --      as arg of a strict fn           ArgOf
342         -- then we should not inline it (unless there is some other reason,
343         -- e.g. is is the sole occurrence).  We achieve this by making
344         -- interestingCallContext return False for a lone variable.
345         --
346         -- Why?  At least in the case-scrutinee situation, turning
347         --      let x = (a,b) in case x of y -> ...
348         -- into
349         --      let x = (a,b) in case (a,b) of y -> ...
350         -- and thence to 
351         --      let x = (a,b) in let y = (a,b) in ...
352         -- is bad if the binding for x will remain.
353         --
354         -- Another example: I discovered that strings
355         -- were getting inlined straight back into applications of 'error'
356         -- because the latter is strict.
357         --      s = "foo"
358         --      f = \x -> ...(error s)...
359
360         -- Fundamentally such contexts should not ecourage inlining because
361         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
362         -- so there's no gain.
363         --
364         -- However, even a type application or coercion isn't a lone variable.
365         -- Consider
366         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
367         -- We had better inline that sucker!  The case won't see through it.
368         --
369         -- For now, I'm treating treating a variable applied to types 
370         -- in a *lazy* context "lone". The motivating example was
371         --      f = /\a. \x. BIG
372         --      g = /\a. \y.  h (f a)
373         -- There's no advantage in inlining f here, and perhaps
374         -- a significant disadvantage.  Hence some_val_args in the Stop case
375
376 interestingCallContext some_args some_val_args cont
377   = interesting cont
378   where
379     interesting (InlinePlease _)       = True
380     interesting (Select _ _ _ _ _)     = some_args
381     interesting (ApplyTo _ _ _ _)      = True   -- Can happen if we have (coerce t (f x)) y
382                                                 -- Perhaps True is a bit over-keen, but I've
383                                                 -- seen (coerce f) x, where f has an INLINE prag,
384                                                 -- So we have to give some motivaiton for inlining it
385     interesting (ArgOf _ _ _ _)          = some_val_args
386     interesting (Stop ty _ upd_in_place) = some_val_args && upd_in_place
387     interesting (CoerceIt _ cont)        = interesting cont
388         -- If this call is the arg of a strict function, the context
389         -- is a bit interesting.  If we inline here, we may get useful
390         -- evaluation information to avoid repeated evals: e.g.
391         --      x + (y * z)
392         -- Here the contIsInteresting makes the '*' keener to inline,
393         -- which in turn exposes a constructor which makes the '+' inline.
394         -- Assuming that +,* aren't small enough to inline regardless.
395         --
396         -- It's also very important to inline in a strict context for things
397         -- like
398         --              foldr k z (f x)
399         -- Here, the context of (f x) is strict, and if f's unfolding is
400         -- a build it's *great* to inline it here.  So we must ensure that
401         -- the context for (f x) is not totally uninteresting.
402
403
404 -------------------
405 canUpdateInPlace :: Type -> Bool
406 -- Consider   let x = <wurble> in ...
407 -- If <wurble> returns an explicit constructor, we might be able
408 -- to do update in place.  So we treat even a thunk RHS context
409 -- as interesting if update in place is possible.  We approximate
410 -- this by seeing if the type has a single constructor with a
411 -- small arity.  But arity zero isn't good -- we share the single copy
412 -- for that case, so no point in sharing.
413
414 canUpdateInPlace ty 
415   | not opt_UF_UpdateInPlace = False
416   | otherwise
417   = case splitTyConApp_maybe ty of 
418         Nothing         -> False 
419         Just (tycon, _) -> case tyConDataConsIfAvailable tycon of
420                                 [dc]  -> arity == 1 || arity == 2
421                                       where
422                                          arity = dataConRepArity dc
423                                 other -> False
424 \end{code}
425
426
427
428 %************************************************************************
429 %*                                                                      *
430 \section{Dealing with a single binder}
431 %*                                                                      *
432 %************************************************************************
433
434 These functions are in the monad only so that they can be made strict via seq.
435
436 \begin{code}
437 simplBinders :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
438 simplBinders env bndrs
439   = let
440         (subst', bndrs') = Subst.simplBndrs (getSubst env) bndrs
441     in
442     seqBndrs bndrs'     `seq`
443     returnSmpl (setSubst env subst', bndrs')
444
445 simplBinder :: SimplEnv -> InBinder -> SimplM (SimplEnv, OutBinder)
446 simplBinder env bndr
447   = let
448         (subst', bndr') = Subst.simplBndr (getSubst env) bndr
449     in
450     seqBndr bndr'       `seq`
451     returnSmpl (setSubst env subst', bndr')
452
453
454 simplLamBinders :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
455 simplLamBinders env bndrs
456   = let
457         (subst', bndrs') = mapAccumL Subst.simplLamBndr (getSubst env) bndrs
458     in
459     seqBndrs bndrs'     `seq`
460     returnSmpl (setSubst env subst', bndrs')
461
462 simplRecIds :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
463 simplRecIds env ids
464   = let
465         (subst', ids') = mapAccumL Subst.simplLetId (getSubst env) ids
466     in
467     seqBndrs ids'       `seq`
468     returnSmpl (setSubst env subst', ids')
469
470 simplLetId :: SimplEnv -> InBinder -> SimplM (SimplEnv, OutBinder)
471 simplLetId env id
472   = let
473         (subst', id') = Subst.simplLetId (getSubst env) id
474     in
475     seqBndr id'         `seq`
476     returnSmpl (setSubst env subst', id')
477
478 seqBndrs [] = ()
479 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
480
481 seqBndr b | isTyVar b = b `seq` ()
482           | otherwise = seqType (idType b)      `seq`
483                         idInfo b                `seq`
484                         ()
485 \end{code}
486
487
488 \begin{code}
489 newId :: UserFS -> Type -> SimplM Id
490 newId fs ty = getUniqueSmpl     `thenSmpl` \ uniq ->
491               returnSmpl (mkSysLocal fs uniq ty)
492 \end{code}
493
494
495 %************************************************************************
496 %*                                                                      *
497 \subsection{Rebuilding a lambda}
498 %*                                                                      *
499 %************************************************************************
500
501 \begin{code}
502 mkLam :: SimplEnv -> [OutBinder] -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
503 \end{code}
504
505 Try three things
506         a) eta reduction, if that gives a trivial expression
507         b) eta expansion [only if there are some value lambdas]
508         c) floating lets out through big lambdas 
509                 [only if all tyvar lambdas, and only if this lambda
510                  is the RHS of a let]
511
512 \begin{code}
513 mkLam env bndrs body cont
514  | opt_SimplDoEtaReduction,
515    Just etad_lam <- tryEtaReduce bndrs body
516  = tick (EtaReduction (head bndrs))     `thenSmpl_`
517    returnSmpl (emptyFloats env, etad_lam)
518
519  | opt_SimplDoLambdaEtaExpansion,
520    any isRuntimeVar bndrs
521  = tryEtaExpansion body         `thenSmpl` \ body' ->
522    returnSmpl (emptyFloats env, mkLams bndrs body')
523
524 {-      Sept 01: I'm experimenting with getting the
525         full laziness pass to float out past big lambdsa
526  | all isTyVar bndrs,   -- Only for big lambdas
527    contIsRhs cont       -- Only try the rhs type-lambda floating
528                         -- if this is indeed a right-hand side; otherwise
529                         -- we end up floating the thing out, only for float-in
530                         -- to float it right back in again!
531  = tryRhsTyLam env bndrs body           `thenSmpl` \ (floats, body') ->
532    returnSmpl (floats, mkLams bndrs body')
533 -}
534
535  | otherwise 
536  = returnSmpl (emptyFloats env, mkLams bndrs body)
537 \end{code}
538
539
540 %************************************************************************
541 %*                                                                      *
542 \subsection{Eta expansion and reduction}
543 %*                                                                      *
544 %************************************************************************
545
546 We try for eta reduction here, but *only* if we get all the 
547 way to an exprIsTrivial expression.    
548 We don't want to remove extra lambdas unless we are going 
549 to avoid allocating this thing altogether
550
551 \begin{code}
552 tryEtaReduce :: [OutBinder] -> OutExpr -> Maybe OutExpr
553 tryEtaReduce bndrs body 
554         -- We don't use CoreUtils.etaReduce, because we can be more
555         -- efficient here:
556         --  (a) we already have the binders
557         --  (b) we can do the triviality test before computing the free vars
558         --      [in fact I take the simple path and look for just a variable]
559   = go (reverse bndrs) body
560   where
561     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
562     go []       (Var fun)     | ok_fun fun   = Just (Var fun)   -- Success!
563     go _        _                            = Nothing          -- Failure!
564
565     ok_fun fun   = not (fun `elem` bndrs) && not (hasNoBinding fun)
566     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
567 \end{code}
568
569
570         Try eta expansion for RHSs
571
572 We go for:
573    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
574                                  (n >= 0)
575
576 where (in both cases) 
577
578         * The xi can include type variables
579
580         * The yi are all value variables
581
582         * N is a NORMAL FORM (i.e. no redexes anywhere)
583           wanting a suitable number of extra args.
584
585 We may have to sandwich some coerces between the lambdas
586 to make the types work.   exprEtaExpandArity looks through coerces
587 when computing arity; and etaExpand adds the coerces as necessary when
588 actually computing the expansion.
589
590 \begin{code}
591 tryEtaExpansion :: OutExpr -> SimplM OutExpr
592 -- There is at least one runtime binder in the binders
593 tryEtaExpansion body
594   | arity_is_manifest           -- Some lambdas but not enough
595   = returnSmpl body
596
597   | otherwise
598   = getUniquesSmpl                      `thenSmpl` \ us ->
599     returnSmpl (etaExpand fun_arity us body (exprType body))
600   where
601     (fun_arity, arity_is_manifest) = exprEtaExpandArity body
602 \end{code}
603
604
605 %************************************************************************
606 %*                                                                      *
607 \subsection{Floating lets out of big lambdas}
608 %*                                                                      *
609 %************************************************************************
610
611 tryRhsTyLam tries this transformation, when the big lambda appears as
612 the RHS of a let(rec) binding:
613
614         /\abc -> let(rec) x = e in b
615    ==>
616         let(rec) x' = /\abc -> let x = x' a b c in e
617         in 
618         /\abc -> let x = x' a b c in b
619
620 This is good because it can turn things like:
621
622         let f = /\a -> letrec g = ... g ... in g
623 into
624         letrec g' = /\a -> ... g' a ...
625         in
626         let f = /\ a -> g' a
627
628 which is better.  In effect, it means that big lambdas don't impede
629 let-floating.
630
631 This optimisation is CRUCIAL in eliminating the junk introduced by
632 desugaring mutually recursive definitions.  Don't eliminate it lightly!
633
634 So far as the implementation is concerned:
635
636         Invariant: go F e = /\tvs -> F e
637         
638         Equalities:
639                 go F (Let x=e in b)
640                 = Let x' = /\tvs -> F e 
641                   in 
642                   go G b
643                 where
644                     G = F . Let x = x' tvs
645         
646                 go F (Letrec xi=ei in b)
647                 = Letrec {xi' = /\tvs -> G ei} 
648                   in
649                   go G b
650                 where
651                   G = F . Let {xi = xi' tvs}
652
653 [May 1999]  If we do this transformation *regardless* then we can
654 end up with some pretty silly stuff.  For example, 
655
656         let 
657             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
658         in ..
659 becomes
660         let y1 = /\s -> r1
661             y2 = /\s -> r2
662             st = /\s -> ...[y1 s/x1, y2 s/x2]
663         in ..
664
665 Unless the "..." is a WHNF there is really no point in doing this.
666 Indeed it can make things worse.  Suppose x1 is used strictly,
667 and is of the form
668
669         x1* = case f y of { (a,b) -> e }
670
671 If we abstract this wrt the tyvar we then can't do the case inline
672 as we would normally do.
673
674
675 \begin{code}
676 {-      Trying to do this in full laziness
677
678 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
679 -- Call ensures that all the binders are type variables
680
681 tryRhsTyLam env tyvars body             -- Only does something if there's a let
682   |  not (all isTyVar tyvars)
683   || not (worth_it body)                -- inside a type lambda, 
684   = returnSmpl (emptyFloats env, body)  -- and a WHNF inside that
685
686   | otherwise
687   = go env (\x -> x) body
688
689   where
690     worth_it e@(Let _ _) = whnf_in_middle e
691     worth_it e           = False
692
693     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
694     whnf_in_middle (Let _ e) = whnf_in_middle e
695     whnf_in_middle e         = exprIsCheap e
696
697     main_tyvar_set = mkVarSet tyvars
698
699     go env fn (Let bind@(NonRec var rhs) body)
700       | exprIsTrivial rhs
701       = go env (fn . Let bind) body
702
703     go env fn (Let (NonRec var rhs) body)
704       = mk_poly tyvars_here var                                                 `thenSmpl` \ (var', rhs') ->
705         addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs)))        $ \ env -> 
706         go env (fn . Let (mk_silly_bind var rhs')) body
707
708       where
709
710         tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
711                 -- Abstract only over the type variables free in the rhs
712                 -- wrt which the new binding is abstracted.  But the naive
713                 -- approach of abstract wrt the tyvars free in the Id's type
714                 -- fails. Consider:
715                 --      /\ a b -> let t :: (a,b) = (e1, e2)
716                 --                    x :: a     = fst t
717                 --                in ...
718                 -- Here, b isn't free in x's type, but we must nevertheless
719                 -- abstract wrt b as well, because t's type mentions b.
720                 -- Since t is floated too, we'd end up with the bogus:
721                 --      poly_t = /\ a b -> (e1, e2)
722                 --      poly_x = /\ a   -> fst (poly_t a *b*)
723                 -- So for now we adopt the even more naive approach of
724                 -- abstracting wrt *all* the tyvars.  We'll see if that
725                 -- gives rise to problems.   SLPJ June 98
726
727     go env fn (Let (Rec prs) body)
728        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
729          let
730             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
731             pairs   = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
732          in
733          addAuxiliaryBind env (Rec pairs)               $ \ env ->
734          go env gn body 
735        where
736          (vars,rhss) = unzip prs
737          tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
738                 -- See notes with tyvars_here above
739
740     go env fn body = returnSmpl (emptyFloats env, fn body)
741
742     mk_poly tyvars_here var
743       = getUniqueSmpl           `thenSmpl` \ uniq ->
744         let
745             poly_name = setNameUnique (idName var) uniq         -- Keep same name
746             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
747             poly_id   = mkLocalId poly_name poly_ty 
748
749                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
750                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
751                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
752                 -- at already simplified code, so it doesn't matter
753                 -- 
754                 -- It's even right to retain single-occurrence or dead-var info:
755                 -- Suppose we started with  /\a -> let x = E in B
756                 -- where x occurs once in B. Then we transform to:
757                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
758                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
759                 -- the occurrences of x' will be just the occurrences originally
760                 -- pinned on x.
761         in
762         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
763
764     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
765                 -- Suppose we start with:
766                 --
767                 --      x = /\ a -> let g = G in E
768                 --
769                 -- Then we'll float to get
770                 --
771                 --      x = let poly_g = /\ a -> G
772                 --          in /\ a -> let g = poly_g a in E
773                 --
774                 -- But now the occurrence analyser will see just one occurrence
775                 -- of poly_g, not inside a lambda, so the simplifier will
776                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
777                 -- (I used to think that the "don't inline lone occurrences" stuff
778                 --  would stop this happening, but since it's the *only* occurrence,
779                 --  PreInlineUnconditionally kicks in first!)
780                 --
781                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
782                 --           to appear many times.  (NB: mkInlineMe eliminates
783                 --           such notes on trivial RHSs, so do it manually.)
784 -}
785 \end{code}
786
787
788 %************************************************************************
789 %*                                                                      *
790 \subsection{Case absorption and identity-case elimination}
791 %*                                                                      *
792 %************************************************************************
793
794 mkCase puts a case expression back together, trying various transformations first.
795
796 \begin{code}
797 mkCase :: OutExpr -> OutId -> [OutAlt] -> SimplM OutExpr
798
799 mkCase scrut case_bndr alts
800   = mkAlts scrut case_bndr alts `thenSmpl` \ better_alts ->
801     mkCase1 scrut case_bndr better_alts
802 \end{code}
803
804
805 mkAlts tries these things:
806
807 1.  If several alternatives are identical, merge them into
808     a single DEFAULT alternative.  I've occasionally seen this 
809     making a big difference:
810
811         case e of               =====>     case e of
812           C _ -> f x                         D v -> ....v....
813           D v -> ....v....                   DEFAULT -> f x
814           DEFAULT -> f x
815
816    The point is that we merge common RHSs, at least for the DEFAULT case.
817    [One could do something more elaborate but I've never seen it needed.]
818    To avoid an expensive test, we just merge branches equal to the *first*
819    alternative; this picks up the common cases
820         a) all branches equal
821         b) some branches equal to the DEFAULT (which occurs first)
822
823 2.  If the DEFAULT alternative can match only one possible constructor,
824     then make that constructor explicit.
825     e.g.
826         case e of x { DEFAULT -> rhs }
827      ===>
828         case e of x { (a,b) -> rhs }
829     where the type is a single constructor type.  This gives better code
830     when rhs also scrutinises x or e.
831
832 3.  Case merging:
833        case e of b {             ==>   case e of b {
834          p1 -> rhs1                      p1 -> rhs1
835          ...                             ...
836          pm -> rhsm                      pm -> rhsm
837          _  -> case b of b' {            pn -> let b'=b in rhsn
838                      pn -> rhsn          ...
839                      ...                 po -> let b'=b in rhso
840                      po -> rhso          _  -> let b'=b in rhsd
841                      _  -> rhsd
842        }  
843     
844     which merges two cases in one case when -- the default alternative of
845     the outer case scrutises the same variable as the outer case This
846     transformation is called Case Merging.  It avoids that the same
847     variable is scrutinised multiple times.
848
849
850 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
851
852         x | p `is` 1 -> e1
853           | p `is` 2 -> e2
854         ...etc...
855
856 where @is@ was something like
857         
858         p `is` n = p /= (-1) && p == n
859
860 This gave rise to a horrible sequence of cases
861
862         case p of
863           (-1) -> $j p
864           1    -> e1
865           DEFAULT -> $j p
866
867 and similarly in cascade for all the join points!
868
869
870
871 \begin{code}
872 --------------------------------------------------
873 --      1. Merge identical branches
874 --------------------------------------------------
875 mkAlts scrut case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
876   | all isDeadBinder bndrs1,                    -- Remember the default 
877     length filtered_alts < length con_alts      -- alternative comes first
878   = tick (AltMerge case_bndr)                   `thenSmpl_`
879     returnSmpl better_alts
880   where
881     filtered_alts        = filter keep con_alts
882     keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
883     better_alts          = (DEFAULT, [], rhs1) : filtered_alts
884
885
886 --------------------------------------------------
887 --      2. Fill in missing constructor
888 --------------------------------------------------
889
890 mkAlts scrut case_bndr alts
891   | Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr),
892     isDataTyCon tycon,                  -- It's a data type
893     (alts_no_deflt, Just rhs) <- findDefault alts,
894                 -- There is a DEFAULT case
895     [missing_con] <- filter is_missing (tyConDataConsIfAvailable tycon)
896                 -- There is just one missing constructor!
897   = tick (FillInCaseDefault case_bndr)  `thenSmpl_`
898     getUniquesSmpl                      `thenSmpl` \ tv_uniqs ->
899     getUniquesSmpl                      `thenSmpl` \ id_uniqs ->
900     let
901         (_,_,ex_tyvars,_,_,_) = dataConSig missing_con
902         ex_tyvars'  = zipWith mk tv_uniqs ex_tyvars
903         mk uniq tv  = mkSysTyVar uniq (tyVarKind tv)
904         arg_ids     = zipWith (mkSysLocal SLIT("a")) id_uniqs arg_tys
905         arg_tys     = dataConArgTys missing_con (inst_tys ++ mkTyVarTys ex_tyvars')
906         better_alts = (DataAlt missing_con, ex_tyvars' ++ arg_ids, rhs) : alts_no_deflt
907     in
908     returnSmpl better_alts
909   where
910     impossible_cons   = otherCons (idUnfolding case_bndr)
911     handled_data_cons = [data_con | DataAlt data_con         <- impossible_cons] ++
912                         [data_con | (DataAlt data_con, _, _) <- alts]
913     is_missing con    = not (con `elem` handled_data_cons)
914
915 --------------------------------------------------
916 --      3.  Merge nested cases
917 --------------------------------------------------
918
919 mkAlts scrut outer_bndr outer_alts
920   | opt_SimplCaseMerge,
921     (outer_alts_without_deflt, maybe_outer_deflt)   <- findDefault outer_alts,
922     Just (Case (Var scrut_var) inner_bndr inner_alts) <- maybe_outer_deflt,
923     scruting_same_var scrut_var
924
925   = let     --  Eliminate any inner alts which are shadowed by the outer ones
926         outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
927     
928         munged_inner_alts = [ (con, args, munge_rhs rhs) 
929                             | (con, args, rhs) <- inner_alts, 
930                                not (con `elem` outer_cons)      -- Eliminate shadowed inner alts
931                             ]
932         munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
933     
934         (inner_con_alts, maybe_inner_default) = findDefault munged_inner_alts
935
936         new_alts = add_default maybe_inner_default
937                                (outer_alts_without_deflt ++ inner_con_alts)
938     in
939     tick (CaseMerge outer_bndr)                         `thenSmpl_`
940     returnSmpl new_alts
941         -- Warning: don't call mkAlts recursively!
942         -- Firstly, there's no point, because inner alts have already had
943         -- mkCase applied to them, so they won't have a case in their default
944         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
945         -- in munge_rhs may put a case into the DEFAULT branch!
946   where
947         -- We are scrutinising the same variable if it's
948         -- the outer case-binder, or if the outer case scrutinises a variable
949         -- (and it's the same).  Testing both allows us not to replace the
950         -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
951     scruting_same_var = case scrut of
952                           Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
953                           other           -> \ v -> v == outer_bndr
954
955     add_default (Just rhs) alts = (DEFAULT,[],rhs) : alts
956     add_default Nothing    alts = alts
957
958
959 --------------------------------------------------
960 --      Catch-all
961 --------------------------------------------------
962
963 mkAlts scrut case_bndr other_alts = returnSmpl other_alts
964 \end{code}
965
966
967
968 =================================================================================
969
970 mkCase1 tries these things
971
972 1.  Eliminate the case altogether if possible
973
974 2.  Case-identity:
975
976         case e of               ===> e
977                 True  -> True;
978                 False -> False
979
980     and similar friends.
981
982
983 Start with a simple situation:
984
985         case x# of      ===>   e[x#/y#]
986           y# -> e
987
988 (when x#, y# are of primitive type, of course).  We can't (in general)
989 do this for algebraic cases, because we might turn bottom into
990 non-bottom!
991
992 Actually, we generalise this idea to look for a case where we're
993 scrutinising a variable, and we know that only the default case can
994 match.  For example:
995 \begin{verbatim}
996         case x of
997           0#    -> ...
998           other -> ...(case x of
999                          0#    -> ...
1000                          other -> ...) ...
1001 \end{code}
1002 Here the inner case can be eliminated.  This really only shows up in
1003 eliminating error-checking code.
1004
1005 We also make sure that we deal with this very common case:
1006
1007         case e of 
1008           x -> ...x...
1009
1010 Here we are using the case as a strict let; if x is used only once
1011 then we want to inline it.  We have to be careful that this doesn't 
1012 make the program terminate when it would have diverged before, so we
1013 check that 
1014         - x is used strictly, or
1015         - e is already evaluated (it may so if e is a variable)
1016
1017 Lastly, we generalise the transformation to handle this:
1018
1019         case e of       ===> r
1020            True  -> r
1021            False -> r
1022
1023 We only do this for very cheaply compared r's (constructors, literals
1024 and variables).  If pedantic bottoms is on, we only do it when the
1025 scrutinee is a PrimOp which can't fail.
1026
1027 We do it *here*, looking at un-simplified alternatives, because we
1028 have to check that r doesn't mention the variables bound by the
1029 pattern in each alternative, so the binder-info is rather useful.
1030
1031 So the case-elimination algorithm is:
1032
1033         1. Eliminate alternatives which can't match
1034
1035         2. Check whether all the remaining alternatives
1036                 (a) do not mention in their rhs any of the variables bound in their pattern
1037            and  (b) have equal rhss
1038
1039         3. Check we can safely ditch the case:
1040                    * PedanticBottoms is off,
1041                 or * the scrutinee is an already-evaluated variable
1042                 or * the scrutinee is a primop which is ok for speculation
1043                         -- ie we want to preserve divide-by-zero errors, and
1044                         -- calls to error itself!
1045
1046                 or * [Prim cases] the scrutinee is a primitive variable
1047
1048                 or * [Alg cases] the scrutinee is a variable and
1049                      either * the rhs is the same variable
1050                         (eg case x of C a b -> x  ===>   x)
1051                      or     * there is only one alternative, the default alternative,
1052                                 and the binder is used strictly in its scope.
1053                                 [NB this is helped by the "use default binder where
1054                                  possible" transformation; see below.]
1055
1056
1057 If so, then we can replace the case with one of the rhss.
1058
1059
1060 \begin{code}
1061 --------------------------------------------------
1062 --      1. Eliminate the case altogether if poss
1063 --------------------------------------------------
1064
1065 mkCase1 scrut case_bndr [(con,bndrs,rhs)]
1066   -- See if we can get rid of the case altogether
1067   -- See the extensive notes on case-elimination above
1068   -- mkCase made sure that if all the alternatives are equal, 
1069   -- then there is now only one (DEFAULT) rhs
1070  |  all isDeadBinder bndrs,
1071
1072         -- Check that the scrutinee can be let-bound instead of case-bound
1073     exprOkForSpeculation scrut
1074                 -- OK not to evaluate it
1075                 -- This includes things like (==# a# b#)::Bool
1076                 -- so that we simplify 
1077                 --      case ==# a# b# of { True -> x; False -> x }
1078                 -- to just
1079                 --      x
1080                 -- This particular example shows up in default methods for
1081                 -- comparision operations (e.g. in (>=) for Int.Int32)
1082         || exprIsValue scrut                    -- It's already evaluated
1083         || var_demanded_later scrut             -- It'll be demanded later
1084
1085 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1086 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1087 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1088 --      its argument:  case x of { y -> dataToTag# y }
1089 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1090 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1091 --      other problems
1092   = tick (CaseElim case_bndr)                   `thenSmpl_` 
1093     returnSmpl (bindCaseBndr case_bndr scrut rhs)
1094
1095   where
1096         -- The case binder is going to be evaluated later, 
1097         -- and the scrutinee is a simple variable
1098     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1099     var_demanded_later other   = False
1100
1101
1102 --------------------------------------------------
1103 --      2. Identity case
1104 --------------------------------------------------
1105
1106 mkCase1 scrut case_bndr alts    -- Identity case
1107   | all identity_alt alts
1108   = tick (CaseIdentity case_bndr)               `thenSmpl_`
1109     returnSmpl (re_note scrut)
1110   where
1111     identity_alt (con, args, rhs) = de_note rhs `cheapEqExpr` identity_rhs con args
1112
1113     identity_rhs (DataAlt con) args = mkConApp con (arg_tys ++ map varToCoreExpr args)
1114     identity_rhs (LitAlt lit)  _    = Lit lit
1115     identity_rhs DEFAULT       _    = Var case_bndr
1116
1117     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1118
1119         -- We've seen this:
1120         --      case coerce T e of x { _ -> coerce T' x }
1121         -- And we definitely want to eliminate this case!
1122         -- So we throw away notes from the RHS, and reconstruct
1123         -- (at least an approximation) at the other end
1124     de_note (Note _ e) = de_note e
1125     de_note e          = e
1126
1127         -- re_note wraps a coerce if it might be necessary
1128     re_note scrut = case head alts of
1129                         (_,_,rhs1@(Note _ _)) -> mkCoerce (exprType rhs1) (idType case_bndr) scrut
1130                         other                 -> scrut
1131
1132
1133 --------------------------------------------------
1134 --      Catch-all
1135 --------------------------------------------------
1136 mkCase1 scrut bndr alts = returnSmpl (Case scrut bndr alts)
1137 \end{code}
1138
1139
1140 When adding auxiliary bindings for the case binder, it's worth checking if
1141 its dead, because it often is, and occasionally these mkCase transformations
1142 cascade rather nicely.
1143
1144 \begin{code}
1145 bindCaseBndr bndr rhs body
1146   | isDeadBinder bndr = body
1147   | otherwise         = bindNonRec bndr rhs body
1148 \end{code}