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