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