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