Major overhaul of the Simplifier
[ghc-hetmet.git] / 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         -- Rebuilding
9         mkLam, mkCase, 
10
11         -- Inlining,
12         preInlineUnconditionally, postInlineUnconditionally, 
13         activeInline, activeRule, inlineMode,
14
15         -- The continuation type
16         SimplCont(..), DupFlag(..), LetRhsFlag(..), 
17         contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs, 
18         countValArgs, countArgs,
19         mkBoringStop, mkLazyArgStop, mkRhsStop, contIsRhsOrArg,
20         interestingCallContext, interestingArgContext,
21
22         interestingArg, isStrictBndr, mkArgInfo
23     ) where
24
25 #include "HsVersions.h"
26
27 import SimplEnv
28 import DynFlags
29 import StaticFlags
30 import CoreSyn
31 import CoreFVs
32 import CoreUtils
33 import Literal  
34 import CoreUnfold
35 import MkId
36 import Id
37 import NewDemand
38 import SimplMonad
39 import Type
40 import TyCon
41 import DataCon
42 import VarSet
43 import BasicTypes
44 import Util
45 import Outputable
46 \end{code}
47
48
49 %************************************************************************
50 %*                                                                      *
51                 The SimplCont type
52 %*                                                                      *
53 %************************************************************************
54
55 A SimplCont allows the simplifier to traverse the expression in a 
56 zipper-like fashion.  The SimplCont represents the rest of the expression,
57 "above" the point of interest.
58
59 You can also think of a SimplCont as an "evaluation context", using
60 that term in the way it is used for operational semantics. This is the
61 way I usually think of it, For example you'll often see a syntax for
62 evaluation context looking like
63         C ::= []  |  C e   |  case C of alts  |  C `cast` co
64 That's the kind of thing we are doing here, and I use that syntax in
65 the comments.
66
67
68 Key points:
69   * A SimplCont describes a *strict* context (just like 
70     evaluation contexts do).  E.g. Just [] is not a SimplCont
71
72   * A SimplCont describes a context that *does not* bind
73     any variables.  E.g. \x. [] is not a SimplCont
74
75 \begin{code}
76 data SimplCont  
77   = Stop                -- An empty context, or hole, []     
78         OutType         -- Type of the result
79         LetRhsFlag
80         Bool            -- True <=> There is something interesting about
81                         --          the context, and hence the inliner
82                         --          should be a bit keener (see interestingCallContext)
83                         -- Two cases:
84                         -- (a) This is the RHS of a thunk whose type suggests
85                         --     that update-in-place would be possible
86                         -- (b) This is an argument of a function that has RULES
87                         --     Inlining the call might allow the rule to fire
88
89   | CoerceIt            -- C `cast` co
90         OutCoercion             -- The coercion simplified
91         SimplCont
92
93   | ApplyTo             -- C arg
94         DupFlag 
95         InExpr SimplEnv         -- The argument and its static env
96         SimplCont
97
98   | Select              -- case C of alts
99         DupFlag 
100         InId [InAlt] SimplEnv   -- The case binder, alts, and subst-env
101         SimplCont
102
103   -- The two strict forms have no DupFlag, because we never duplicate them
104   | StrictBind          -- (\x* \xs. e) C
105         InId [InBndr]           -- let x* = [] in e     
106         InExpr SimplEnv         --      is a special case 
107         SimplCont       
108
109   | StrictArg           -- e C
110         OutExpr OutType         -- e and its type
111         (Bool,[Bool])           -- Whether the function at the head of e has rules,
112         SimplCont               --     plus strictness flags for further args
113
114 data LetRhsFlag = AnArg         -- It's just an argument not a let RHS
115                 | AnRhs         -- It's the RHS of a let (so please float lets out of big lambdas)
116
117 instance Outputable LetRhsFlag where
118   ppr AnArg = ptext SLIT("arg")
119   ppr AnRhs = ptext SLIT("rhs")
120
121 instance Outputable SimplCont where
122   ppr (Stop ty is_rhs _)             = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
123   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
124   ppr (StrictBind b _ _ _ cont)      = (ptext SLIT("StrictBind") <+> ppr b) $$ ppr cont
125   ppr (StrictArg f _ _ cont)         = (ptext SLIT("StrictArg") <+> ppr f) $$ ppr cont
126   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
127                                        (nest 4 (ppr alts $$ ppr (seIdSubst se))) $$ ppr cont
128   ppr (CoerceIt co cont)             = (ptext SLIT("CoerceIt") <+> ppr co) $$ ppr cont
129
130 data DupFlag = OkToDup | NoDup
131
132 instance Outputable DupFlag where
133   ppr OkToDup = ptext SLIT("ok")
134   ppr NoDup   = ptext SLIT("nodup")
135
136
137
138 -------------------
139 mkBoringStop :: OutType -> SimplCont
140 mkBoringStop ty = Stop ty AnArg False
141
142 mkLazyArgStop :: OutType -> Bool -> SimplCont
143 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
144
145 mkRhsStop :: OutType -> SimplCont
146 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
147
148 contIsRhsOrArg (Stop _ _ _)    = True
149 contIsRhsOrArg (StrictBind {}) = True
150 contIsRhsOrArg (StrictArg {})  = True
151 contIsRhsOrArg other           = False
152
153 -------------------
154 contIsDupable :: SimplCont -> Bool
155 contIsDupable (Stop _ _ _)               = True
156 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
157 contIsDupable (Select   OkToDup _ _ _ _) = True
158 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
159 contIsDupable other                      = False
160
161 -------------------
162 contIsTrivial :: SimplCont -> Bool
163 contIsTrivial (Stop _ _ _)                = True
164 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
165 contIsTrivial (CoerceIt _ cont)           = contIsTrivial cont
166 contIsTrivial other                       = False
167
168 -------------------
169 contResultType :: SimplCont -> OutType
170 contResultType (Stop to_ty _ _)          = to_ty
171 contResultType (StrictArg _ _ _ cont)    = contResultType cont
172 contResultType (StrictBind _ _ _ _ cont) = contResultType cont
173 contResultType (ApplyTo _ _ _ cont)      = contResultType cont
174 contResultType (CoerceIt _ cont)         = contResultType cont
175 contResultType (Select _ _ _ _ cont)     = contResultType cont
176
177 -------------------
178 countValArgs :: SimplCont -> Int
179 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
180 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
181 countValArgs other                         = 0
182
183 countArgs :: SimplCont -> Int
184 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
185 countArgs other                   = 0
186
187 contArgs :: SimplCont -> ([OutExpr], SimplCont)
188 -- Uses substitution to turn each arg into an OutExpr
189 contArgs cont = go [] cont
190   where
191     go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
192     go args cont                    = (reverse args, cont)
193
194 dropArgs :: Int -> SimplCont -> SimplCont
195 dropArgs 0 cont = cont
196 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
197 dropArgs n other                = pprPanic "dropArgs" (ppr n <+> ppr other)
198 \end{code}
199
200
201 \begin{code}
202 interestingArg :: OutExpr -> Bool
203         -- An argument is interesting if it has *some* structure
204         -- We are here trying to avoid unfolding a function that
205         -- is applied only to variables that have no unfolding
206         -- (i.e. they are probably lambda bound): f x y z
207         -- There is little point in inlining f here.
208 interestingArg (Var v)           = hasSomeUnfolding (idUnfolding v)
209                                         -- Was: isValueUnfolding (idUnfolding v')
210                                         -- But that seems over-pessimistic
211                                  || isDataConWorkId v
212                                         -- This accounts for an argument like
213                                         -- () or [], which is definitely interesting
214 interestingArg (Type _)          = False
215 interestingArg (App fn (Type _)) = interestingArg fn
216 interestingArg (Note _ a)        = interestingArg a
217 interestingArg other             = True
218         -- Consider     let x = 3 in f x
219         -- The substitution will contain (x -> ContEx 3), and we want to
220         -- to say that x is an interesting argument.
221         -- But consider also (\x. f x y) y
222         -- The substitution will contain (x -> ContEx y), and we want to say
223         -- that x is not interesting (assuming y has no unfolding)
224 \end{code}
225
226
227 Comment about interestingCallContext
228 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
229 We want to avoid inlining an expression where there can't possibly be
230 any gain, such as in an argument position.  Hence, if the continuation
231 is interesting (eg. a case scrutinee, application etc.) then we
232 inline, otherwise we don't.  
233
234 Previously some_benefit used to return True only if the variable was
235 applied to some value arguments.  This didn't work:
236
237         let x = _coerce_ (T Int) Int (I# 3) in
238         case _coerce_ Int (T Int) x of
239                 I# y -> ....
240
241 we want to inline x, but can't see that it's a constructor in a case
242 scrutinee position, and some_benefit is False.
243
244 Another example:
245
246 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
247
248 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
249
250 we'd really like to inline dMonadST here, but we *don't* want to
251 inline if the case expression is just
252
253         case x of y { DEFAULT -> ... }
254
255 since we can just eliminate this case instead (x is in WHNF).  Similar
256 applies when x is bound to a lambda expression.  Hence
257 contIsInteresting looks for case expressions with just a single
258 default case.
259
260 \begin{code}
261 interestingCallContext :: Bool          -- False <=> no args at all
262                        -> Bool          -- False <=> no value args
263                        -> SimplCont -> Bool
264         -- The "lone-variable" case is important.  I spent ages
265         -- messing about with unsatisfactory varaints, but this is nice.
266         -- The idea is that if a variable appear all alone
267         --      as an arg of lazy fn, or rhs    Stop
268         --      as scrutinee of a case          Select
269         --      as arg of a strict fn           ArgOf
270         -- then we should not inline it (unless there is some other reason,
271         -- e.g. is is the sole occurrence).  We achieve this by making
272         -- interestingCallContext return False for a lone variable.
273         --
274         -- Why?  At least in the case-scrutinee situation, turning
275         --      let x = (a,b) in case x of y -> ...
276         -- into
277         --      let x = (a,b) in case (a,b) of y -> ...
278         -- and thence to 
279         --      let x = (a,b) in let y = (a,b) in ...
280         -- is bad if the binding for x will remain.
281         --
282         -- Another example: I discovered that strings
283         -- were getting inlined straight back into applications of 'error'
284         -- because the latter is strict.
285         --      s = "foo"
286         --      f = \x -> ...(error s)...
287
288         -- Fundamentally such contexts should not ecourage inlining because
289         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
290         -- so there's no gain.
291         --
292         -- However, even a type application or coercion isn't a lone variable.
293         -- Consider
294         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
295         -- We had better inline that sucker!  The case won't see through it.
296         --
297         -- For now, I'm treating treating a variable applied to types 
298         -- in a *lazy* context "lone". The motivating example was
299         --      f = /\a. \x. BIG
300         --      g = /\a. \y.  h (f a)
301         -- There's no advantage in inlining f here, and perhaps
302         -- a significant disadvantage.  Hence some_val_args in the Stop case
303
304 interestingCallContext some_args some_val_args cont
305   = interesting cont
306   where
307     interesting (Select {})              = some_args
308     interesting (ApplyTo {})             = True -- Can happen if we have (coerce t (f x)) y
309                                                 -- Perhaps True is a bit over-keen, but I've
310                                                 -- seen (coerce f) x, where f has an INLINE prag,
311                                                 -- So we have to give some motivaiton for inlining it
312     interesting (StrictArg {})           = some_val_args
313     interesting (StrictBind {})          = some_val_args        -- ??
314     interesting (Stop ty _ interesting)  = some_val_args && interesting
315     interesting (CoerceIt _ cont)        = interesting cont
316         -- If this call is the arg of a strict function, the context
317         -- is a bit interesting.  If we inline here, we may get useful
318         -- evaluation information to avoid repeated evals: e.g.
319         --      x + (y * z)
320         -- Here the contIsInteresting makes the '*' keener to inline,
321         -- which in turn exposes a constructor which makes the '+' inline.
322         -- Assuming that +,* aren't small enough to inline regardless.
323         --
324         -- It's also very important to inline in a strict context for things
325         -- like
326         --              foldr k z (f x)
327         -- Here, the context of (f x) is strict, and if f's unfolding is
328         -- a build it's *great* to inline it here.  So we must ensure that
329         -- the context for (f x) is not totally uninteresting.
330
331
332 -------------------
333 mkArgInfo :: Id
334           -> Int        -- Number of value args
335           -> SimplCont  -- Context of the cal
336           -> (Bool, [Bool])     -- Arg info
337 -- The arg info consists of
338 --  * A Bool indicating if the function has rules (recursively)
339 --  * A [Bool] indicating strictness for each arg
340 -- The [Bool] is usually infinite, but if it is finite it 
341 -- guarantees that the function diverges after being given
342 -- that number of args
343
344 mkArgInfo fun n_val_args call_cont
345   = (interestingArgContext fun call_cont, fun_stricts)
346   where
347     vanilla_stricts, fun_stricts :: [Bool]
348     vanilla_stricts  = repeat False
349
350     fun_stricts
351       = case splitStrictSig (idNewStrictness fun) of
352           (demands, result_info)
353                 | not (demands `lengthExceeds` n_val_args)
354                 ->      -- Enough args, use the strictness given.
355                         -- For bottoming functions we used to pretend that the arg
356                         -- is lazy, so that we don't treat the arg as an
357                         -- interesting context.  This avoids substituting
358                         -- top-level bindings for (say) strings into 
359                         -- calls to error.  But now we are more careful about
360                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
361                    if isBotRes result_info then
362                         map isStrictDmd demands         -- Finite => result is bottom
363                    else
364                         map isStrictDmd demands ++ vanilla_stricts
365
366           other -> vanilla_stricts      -- Not enough args, or no strictness
367
368 interestingArgContext :: Id -> SimplCont -> Bool
369 -- If the argument has form (f x y), where x,y are boring,
370 -- and f is marked INLINE, then we don't want to inline f.
371 -- But if the context of the argument is
372 --      g (f x y) 
373 -- where g has rules, then we *do* want to inline f, in case it
374 -- exposes a rule that might fire.  Similarly, if the context is
375 --      h (g (f x x))
376 -- where h has rules, then we do want to inline f.
377 -- The interesting_arg_ctxt flag makes this happen; if it's
378 -- set, the inliner gets just enough keener to inline f 
379 -- regardless of how boring f's arguments are, if it's marked INLINE
380 --
381 -- The alternative would be to *always* inline an INLINE function,
382 -- regardless of how boring its context is; but that seems overkill
383 -- For example, it'd mean that wrapper functions were always inlined
384 interestingArgContext fn cont
385   = idHasRules fn || go cont
386   where
387     go (Select {})            = False
388     go (ApplyTo {})           = False
389     go (StrictArg {})         = True
390     go (StrictBind {})        = False   -- ??
391     go (CoerceIt _ c)         = go c
392     go (Stop _ _ interesting) = interesting
393
394 -------------------
395 canUpdateInPlace :: Type -> Bool
396 -- Consider   let x = <wurble> in ...
397 -- If <wurble> returns an explicit constructor, we might be able
398 -- to do update in place.  So we treat even a thunk RHS context
399 -- as interesting if update in place is possible.  We approximate
400 -- this by seeing if the type has a single constructor with a
401 -- small arity.  But arity zero isn't good -- we share the single copy
402 -- for that case, so no point in sharing.
403
404 canUpdateInPlace ty 
405   | not opt_UF_UpdateInPlace = False
406   | otherwise
407   = case splitTyConApp_maybe ty of 
408         Nothing         -> False 
409         Just (tycon, _) -> case tyConDataCons_maybe tycon of
410                                 Just [dc]  -> arity == 1 || arity == 2
411                                            where
412                                               arity = dataConRepArity dc
413                                 other -> False
414 \end{code}
415
416
417
418 %************************************************************************
419 %*                                                                      *
420 \subsection{Decisions about inlining}
421 %*                                                                      *
422 %************************************************************************
423
424 Inlining is controlled partly by the SimplifierMode switch.  This has two
425 settings:
426
427         SimplGently     (a) Simplifying before specialiser/full laziness
428                         (b) Simplifiying inside INLINE pragma
429                         (c) Simplifying the LHS of a rule
430                         (d) Simplifying a GHCi expression or Template 
431                                 Haskell splice
432
433         SimplPhase n    Used at all other times
434
435 The key thing about SimplGently is that it does no call-site inlining.
436 Before full laziness we must be careful not to inline wrappers,
437 because doing so inhibits floating
438     e.g. ...(case f x of ...)...
439     ==> ...(case (case x of I# x# -> fw x#) of ...)...
440     ==> ...(case x of I# x# -> case fw x# of ...)...
441 and now the redex (f x) isn't floatable any more.
442
443 The no-inlining thing is also important for Template Haskell.  You might be 
444 compiling in one-shot mode with -O2; but when TH compiles a splice before
445 running it, we don't want to use -O2.  Indeed, we don't want to inline
446 anything, because the byte-code interpreter might get confused about 
447 unboxed tuples and suchlike.
448
449 INLINE pragmas
450 ~~~~~~~~~~~~~~
451 SimplGently is also used as the mode to simplify inside an InlineMe note.
452
453 \begin{code}
454 inlineMode :: SimplifierMode
455 inlineMode = SimplGently
456 \end{code}
457
458 It really is important to switch off inlinings inside such
459 expressions.  Consider the following example 
460
461         let f = \pq -> BIG
462         in
463         let g = \y -> f y y
464             {-# INLINE g #-}
465         in ...g...g...g...g...g...
466
467 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
468 and thence copied multiple times when g is inlined.
469
470
471 This function may be inlinined in other modules, so we
472 don't want to remove (by inlining) calls to functions that have
473 specialisations, or that may have transformation rules in an importing
474 scope.
475
476 E.g.    {-# INLINE f #-}
477                 f x = ...g...
478
479 and suppose that g is strict *and* has specialisations.  If we inline
480 g's wrapper, we deny f the chance of getting the specialised version
481 of g when f is inlined at some call site (perhaps in some other
482 module).
483
484 It's also important not to inline a worker back into a wrapper.
485 A wrapper looks like
486         wraper = inline_me (\x -> ...worker... )
487 Normally, the inline_me prevents the worker getting inlined into
488 the wrapper (initially, the worker's only call site!).  But,
489 if the wrapper is sure to be called, the strictness analyser will
490 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
491 continuation.  That's why the keep_inline predicate returns True for
492 ArgOf continuations.  It shouldn't do any harm not to dissolve the
493 inline-me note under these circumstances.
494
495 Note that the result is that we do very little simplification
496 inside an InlineMe.  
497
498         all xs = foldr (&&) True xs
499         any p = all . map p  {-# INLINE any #-}
500
501 Problem: any won't get deforested, and so if it's exported and the
502 importer doesn't use the inlining, (eg passes it as an arg) then we
503 won't get deforestation at all.  We havn't solved this problem yet!
504
505
506 preInlineUnconditionally
507 ~~~~~~~~~~~~~~~~~~~~~~~~
508 @preInlineUnconditionally@ examines a bndr to see if it is used just
509 once in a completely safe way, so that it is safe to discard the
510 binding inline its RHS at the (unique) usage site, REGARDLESS of how
511 big the RHS might be.  If this is the case we don't simplify the RHS
512 first, but just inline it un-simplified.
513
514 This is much better than first simplifying a perhaps-huge RHS and then
515 inlining and re-simplifying it.  Indeed, it can be at least quadratically
516 better.  Consider
517
518         x1 = e1
519         x2 = e2[x1]
520         x3 = e3[x2]
521         ...etc...
522         xN = eN[xN-1]
523
524 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
525 This can happen with cascades of functions too:
526
527         f1 = \x1.e1
528         f2 = \xs.e2[f1]
529         f3 = \xs.e3[f3]
530         ...etc...
531
532 THE MAIN INVARIANT is this:
533
534         ----  preInlineUnconditionally invariant -----
535    IF preInlineUnconditionally chooses to inline x = <rhs>
536    THEN doing the inlining should not change the occurrence
537         info for the free vars of <rhs>
538         ----------------------------------------------
539
540 For example, it's tempting to look at trivial binding like
541         x = y
542 and inline it unconditionally.  But suppose x is used many times,
543 but this is the unique occurrence of y.  Then inlining x would change
544 y's occurrence info, which breaks the invariant.  It matters: y
545 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
546
547
548 Evne RHSs labelled InlineMe aren't caught here, because there might be
549 no benefit from inlining at the call site.
550
551 [Sept 01] Don't unconditionally inline a top-level thing, because that
552 can simply make a static thing into something built dynamically.  E.g.
553         x = (a,b)
554         main = \s -> h x
555
556 [Remember that we treat \s as a one-shot lambda.]  No point in
557 inlining x unless there is something interesting about the call site.
558
559 But watch out: if you aren't careful, some useful foldr/build fusion
560 can be lost (most notably in spectral/hartel/parstof) because the
561 foldr didn't see the build.  Doing the dynamic allocation isn't a big
562 deal, in fact, but losing the fusion can be.  But the right thing here
563 seems to be to do a callSiteInline based on the fact that there is
564 something interesting about the call site (it's strict).  Hmm.  That
565 seems a bit fragile.
566
567 Conclusion: inline top level things gaily until Phase 0 (the last
568 phase), at which point don't.
569
570 \begin{code}
571 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
572 preInlineUnconditionally env top_lvl bndr rhs
573   | not active             = False
574   | opt_SimplNoPreInlining = False
575   | otherwise = case idOccInfo bndr of
576                   IAmDead                    -> True    -- Happens in ((\x.1) v)
577                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
578                   other                      -> False
579   where
580     phase = getMode env
581     active = case phase of
582                    SimplGently  -> isAlwaysActive prag
583                    SimplPhase n -> isActive n prag
584     prag = idInlinePragma bndr
585
586     try_once in_lam int_cxt     -- There's one textual occurrence
587         | not in_lam = isNotTopLevel top_lvl || early_phase
588         | otherwise  = int_cxt && canInlineInLam rhs
589
590 -- Be very careful before inlining inside a lambda, becuase (a) we must not 
591 -- invalidate occurrence information, and (b) we want to avoid pushing a
592 -- single allocation (here) into multiple allocations (inside lambda).  
593 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
594 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
595 --      where 
596 --              is_cheap = exprIsCheap rhs
597 --              ok = is_cheap && int_cxt
598
599         --      int_cxt         The context isn't totally boring
600         -- E.g. let f = \ab.BIG in \y. map f xs
601         --      Don't want to substitute for f, because then we allocate
602         --      its closure every time the \y is called
603         -- But: let f = \ab.BIG in \y. map (f y) xs
604         --      Now we do want to substitute for f, even though it's not 
605         --      saturated, because we're going to allocate a closure for 
606         --      (f y) every time round the loop anyhow.
607
608         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
609         -- so substituting rhs inside a lambda doesn't change the occ info.
610         -- Sadly, not quite the same as exprIsHNF.
611     canInlineInLam (Lit l)              = True
612     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
613     canInlineInLam (Note _ e)           = canInlineInLam e
614     canInlineInLam _                    = False
615
616     early_phase = case phase of
617                         SimplPhase 0 -> False
618                         other        -> True
619 -- If we don't have this early_phase test, consider
620 --      x = length [1,2,3]
621 -- The full laziness pass carefully floats all the cons cells to
622 -- top level, and preInlineUnconditionally floats them all back in.
623 -- Result is (a) static allocation replaced by dynamic allocation
624 --           (b) many simplifier iterations because this tickles
625 --               a related problem; only one inlining per pass
626 -- 
627 -- On the other hand, I have seen cases where top-level fusion is
628 -- lost if we don't inline top level thing (e.g. string constants)
629 -- Hence the test for phase zero (which is the phase for all the final
630 -- simplifications).  Until phase zero we take no special notice of
631 -- top level things, but then we become more leery about inlining
632 -- them.  
633
634 \end{code}
635
636 postInlineUnconditionally
637 ~~~~~~~~~~~~~~~~~~~~~~~~~
638 @postInlineUnconditionally@ decides whether to unconditionally inline
639 a thing based on the form of its RHS; in particular if it has a
640 trivial RHS.  If so, we can inline and discard the binding altogether.
641
642 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
643 only have *forward* references Hence, it's safe to discard the binding
644         
645 NOTE: This isn't our last opportunity to inline.  We're at the binding
646 site right now, and we'll get another opportunity when we get to the
647 ocurrence(s)
648
649 Note that we do this unconditional inlining only for trival RHSs.
650 Don't inline even WHNFs inside lambdas; doing so may simply increase
651 allocation when the function is called. This isn't the last chance; see
652 NOTE above.
653
654 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
655 Because we don't even want to inline them into the RHS of constructor
656 arguments. See NOTE above
657
658 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
659 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
660 with both a and b marked NOINLINE.  But that seems incompatible with
661 our new view that inlining is like a RULE, so I'm sticking to the 'active'
662 story for now.
663
664 \begin{code}
665 postInlineUnconditionally 
666     :: SimplEnv -> TopLevelFlag
667     -> InId             -- The binder (an OutId would be fine too)
668     -> OccInfo          -- From the InId
669     -> OutExpr
670     -> Unfolding
671     -> Bool
672 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
673   | not active             = False
674   | isLoopBreaker occ_info = False      -- If it's a loop-breaker of any kind, dont' inline
675                                         -- because it might be referred to "earlier"
676   | isExportedId bndr      = False
677   | exprIsTrivial rhs      = True
678   | otherwise
679   = case occ_info of
680         -- The point of examining occ_info here is that for *non-values* 
681         -- that occur outside a lambda, the call-site inliner won't have
682         -- a chance (becuase it doesn't know that the thing
683         -- only occurs once).   The pre-inliner won't have gotten
684         -- it either, if the thing occurs in more than one branch
685         -- So the main target is things like
686         --      let x = f y in
687         --      case v of
688         --         True  -> case x of ...
689         --         False -> case x of ...
690         -- I'm not sure how important this is in practice
691       OneOcc in_lam one_br int_cxt      -- OneOcc => no code-duplication issue
692         ->     smallEnoughToInline unfolding    -- Small enough to dup
693                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
694                         --
695                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
696                         -- Reason: doing so risks exponential behaviour.  We simplify a big
697                         --         expression, inline it, and simplify it again.  But if the
698                         --         very same thing happens in the big expression, we get 
699                         --         exponential cost!
700                         -- PRINCIPLE: when we've already simplified an expression once, 
701                         -- make sure that we only inline it if it's reasonably small.
702
703            &&  ((isNotTopLevel top_lvl && not in_lam) || 
704                         -- But outside a lambda, we want to be reasonably aggressive
705                         -- about inlining into multiple branches of case
706                         -- e.g. let x = <non-value> 
707                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
708                         -- Inlining can be a big win if C3 is the hot-spot, even if
709                         -- the uses in C1, C2 are not 'interesting'
710                         -- An example that gets worse if you add int_cxt here is 'clausify'
711
712                 (isCheapUnfolding unfolding && int_cxt))
713                         -- isCheap => acceptable work duplication; in_lam may be true
714                         -- int_cxt to prevent us inlining inside a lambda without some 
715                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
716
717       IAmDead -> True   -- This happens; for example, the case_bndr during case of
718                         -- known constructor:  case (a,b) of x { (p,q) -> ... }
719                         -- Here x isn't mentioned in the RHS, so we don't want to
720                         -- create the (dead) let-binding  let x = (a,b) in ...
721
722       other -> False
723
724 -- Here's an example that we don't handle well:
725 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
726 --      in \y. ....case f of {...} ....
727 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
728 -- But
729 -- * We can't preInlineUnconditionally because that woud invalidate
730 --   the occ info for b.  
731 -- * We can't postInlineUnconditionally because the RHS is big, and
732 --   that risks exponential behaviour
733 -- * We can't call-site inline, because the rhs is big
734 -- Alas!
735
736   where
737     active = case getMode env of
738                    SimplGently  -> isAlwaysActive prag
739                    SimplPhase n -> isActive n prag
740     prag = idInlinePragma bndr
741
742 activeInline :: SimplEnv -> OutId -> Bool
743 activeInline env id
744   = case getMode env of
745       SimplGently -> False
746         -- No inlining at all when doing gentle stuff,
747         -- except for local things that occur once
748         -- The reason is that too little clean-up happens if you 
749         -- don't inline use-once things.   Also a bit of inlining is *good* for
750         -- full laziness; it can expose constant sub-expressions.
751         -- Example in spectral/mandel/Mandel.hs, where the mandelset 
752         -- function gets a useful let-float if you inline windowToViewport
753
754         -- NB: we used to have a second exception, for data con wrappers.
755         -- On the grounds that we use gentle mode for rule LHSs, and 
756         -- they match better when data con wrappers are inlined.
757         -- But that only really applies to the trivial wrappers (like (:)),
758         -- and they are now constructed as Compulsory unfoldings (in MkId)
759         -- so they'll happen anyway.
760
761       SimplPhase n -> isActive n prag
762   where
763     prag = idInlinePragma id
764
765 activeRule :: SimplEnv -> Maybe (Activation -> Bool)
766 -- Nothing => No rules at all
767 activeRule env
768   | opt_RulesOff = Nothing
769   | otherwise
770   = case getMode env of
771         SimplGently  -> Just isAlwaysActive
772                         -- Used to be Nothing (no rules in gentle mode)
773                         -- Main motivation for changing is that I wanted
774                         --      lift String ===> ...
775                         -- to work in Template Haskell when simplifying
776                         -- splices, so we get simpler code for literal strings
777         SimplPhase n -> Just (isActive n)
778 \end{code}      
779
780
781 %************************************************************************
782 %*                                                                      *
783         Rebuilding a lambda
784 %*                                                                      *
785 %************************************************************************
786
787 \begin{code}
788 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
789 -- mkLam tries three things
790 --      a) eta reduction, if that gives a trivial expression
791 --      b) eta expansion [only if there are some value lambdas]
792
793 mkLam bndrs body
794   = do  { dflags <- getDOptsSmpl
795         ; mkLam' dflags bndrs body }
796   where
797     mkLam' dflags bndrs body
798       | dopt Opt_DoEtaReduction dflags,
799         Just etad_lam <- tryEtaReduce bndrs body
800       = do { tick (EtaReduction (head bndrs))
801            ; return etad_lam }
802
803       | dopt Opt_DoLambdaEtaExpansion dflags,
804         any isRuntimeVar bndrs
805       = do { body' <- tryEtaExpansion dflags body
806            ; return (mkLams bndrs body') }
807    
808       | otherwise 
809       = returnSmpl (mkLams bndrs body)
810 \end{code}
811
812 --      c) floating lets out through big lambdas 
813 --              [only if all tyvar lambdas, and only if this lambda
814 --               is the RHS of a let]
815
816 {-      Sept 01: I'm experimenting with getting the
817         full laziness pass to float out past big lambdsa
818  | all isTyVar bndrs,   -- Only for big lambdas
819    contIsRhs cont       -- Only try the rhs type-lambda floating
820                         -- if this is indeed a right-hand side; otherwise
821                         -- we end up floating the thing out, only for float-in
822                         -- to float it right back in again!
823  = tryRhsTyLam env bndrs body           `thenSmpl` \ (floats, body') ->
824    returnSmpl (floats, mkLams bndrs body')
825 -}
826
827
828 %************************************************************************
829 %*                                                                      *
830 \subsection{Eta expansion and reduction}
831 %*                                                                      *
832 %************************************************************************
833
834 We try for eta reduction here, but *only* if we get all the 
835 way to an exprIsTrivial expression.    
836 We don't want to remove extra lambdas unless we are going 
837 to avoid allocating this thing altogether
838
839 \begin{code}
840 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
841 tryEtaReduce bndrs body 
842         -- We don't use CoreUtils.etaReduce, because we can be more
843         -- efficient here:
844         --  (a) we already have the binders
845         --  (b) we can do the triviality test before computing the free vars
846   = go (reverse bndrs) body
847   where
848     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
849     go []       fun           | ok_fun fun   = Just fun         -- Success!
850     go _        _                            = Nothing          -- Failure!
851
852     ok_fun fun =  exprIsTrivial fun
853                && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
854                && (exprIsHNF fun || all ok_lam bndrs)
855     ok_lam v = isTyVar v || isDictId v
856         -- The exprIsHNF is because eta reduction is not 
857         -- valid in general:  \x. bot  /=  bot
858         -- So we need to be sure that the "fun" is a value.
859         --
860         -- However, we always want to reduce (/\a -> f a) to f
861         -- This came up in a RULE: foldr (build (/\a -> g a))
862         --      did not match      foldr (build (/\b -> ...something complex...))
863         -- The type checker can insert these eta-expanded versions,
864         -- with both type and dictionary lambdas; hence the slightly 
865         -- ad-hoc isDictTy
866
867     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
868 \end{code}
869
870
871         Try eta expansion for RHSs
872
873 We go for:
874    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
875                                  (n >= 0)
876
877 where (in both cases) 
878
879         * The xi can include type variables
880
881         * The yi are all value variables
882
883         * N is a NORMAL FORM (i.e. no redexes anywhere)
884           wanting a suitable number of extra args.
885
886 We may have to sandwich some coerces between the lambdas
887 to make the types work.   exprEtaExpandArity looks through coerces
888 when computing arity; and etaExpand adds the coerces as necessary when
889 actually computing the expansion.
890
891 \begin{code}
892 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
893 -- There is at least one runtime binder in the binders
894 tryEtaExpansion dflags body
895   = getUniquesSmpl                      `thenSmpl` \ us ->
896     returnSmpl (etaExpand fun_arity us body (exprType body))
897   where
898     fun_arity = exprEtaExpandArity dflags body
899 \end{code}
900
901
902 %************************************************************************
903 %*                                                                      *
904 \subsection{Floating lets out of big lambdas}
905 %*                                                                      *
906 %************************************************************************
907
908 tryRhsTyLam tries this transformation, when the big lambda appears as
909 the RHS of a let(rec) binding:
910
911         /\abc -> let(rec) x = e in b
912    ==>
913         let(rec) x' = /\abc -> let x = x' a b c in e
914         in 
915         /\abc -> let x = x' a b c in b
916
917 This is good because it can turn things like:
918
919         let f = /\a -> letrec g = ... g ... in g
920 into
921         letrec g' = /\a -> ... g' a ...
922         in
923         let f = /\ a -> g' a
924
925 which is better.  In effect, it means that big lambdas don't impede
926 let-floating.
927
928 This optimisation is CRUCIAL in eliminating the junk introduced by
929 desugaring mutually recursive definitions.  Don't eliminate it lightly!
930
931 So far as the implementation is concerned:
932
933         Invariant: go F e = /\tvs -> F e
934         
935         Equalities:
936                 go F (Let x=e in b)
937                 = Let x' = /\tvs -> F e 
938                   in 
939                   go G b
940                 where
941                     G = F . Let x = x' tvs
942         
943                 go F (Letrec xi=ei in b)
944                 = Letrec {xi' = /\tvs -> G ei} 
945                   in
946                   go G b
947                 where
948                   G = F . Let {xi = xi' tvs}
949
950 [May 1999]  If we do this transformation *regardless* then we can
951 end up with some pretty silly stuff.  For example, 
952
953         let 
954             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
955         in ..
956 becomes
957         let y1 = /\s -> r1
958             y2 = /\s -> r2
959             st = /\s -> ...[y1 s/x1, y2 s/x2]
960         in ..
961
962 Unless the "..." is a WHNF there is really no point in doing this.
963 Indeed it can make things worse.  Suppose x1 is used strictly,
964 and is of the form
965
966         x1* = case f y of { (a,b) -> e }
967
968 If we abstract this wrt the tyvar we then can't do the case inline
969 as we would normally do.
970
971
972 \begin{code}
973 {-      Trying to do this in full laziness
974
975 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
976 -- Call ensures that all the binders are type variables
977
978 tryRhsTyLam env tyvars body             -- Only does something if there's a let
979   |  not (all isTyVar tyvars)
980   || not (worth_it body)                -- inside a type lambda, 
981   = returnSmpl (emptyFloats env, body)  -- and a WHNF inside that
982
983   | otherwise
984   = go env (\x -> x) body
985
986   where
987     worth_it e@(Let _ _) = whnf_in_middle e
988     worth_it e           = False
989
990     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
991     whnf_in_middle (Let _ e) = whnf_in_middle e
992     whnf_in_middle e         = exprIsCheap e
993
994     main_tyvar_set = mkVarSet tyvars
995
996     go env fn (Let bind@(NonRec var rhs) body)
997       | exprIsTrivial rhs
998       = go env (fn . Let bind) body
999
1000     go env fn (Let (NonRec var rhs) body)
1001       = mk_poly tyvars_here var                                                 `thenSmpl` \ (var', rhs') ->
1002         addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs)))        $ \ env -> 
1003         go env (fn . Let (mk_silly_bind var rhs')) body
1004
1005       where
1006
1007         tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1008                 -- Abstract only over the type variables free in the rhs
1009                 -- wrt which the new binding is abstracted.  But the naive
1010                 -- approach of abstract wrt the tyvars free in the Id's type
1011                 -- fails. Consider:
1012                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1013                 --                    x :: a     = fst t
1014                 --                in ...
1015                 -- Here, b isn't free in x's type, but we must nevertheless
1016                 -- abstract wrt b as well, because t's type mentions b.
1017                 -- Since t is floated too, we'd end up with the bogus:
1018                 --      poly_t = /\ a b -> (e1, e2)
1019                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1020                 -- So for now we adopt the even more naive approach of
1021                 -- abstracting wrt *all* the tyvars.  We'll see if that
1022                 -- gives rise to problems.   SLPJ June 98
1023
1024     go env fn (Let (Rec prs) body)
1025        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
1026          let
1027             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1028             pairs   = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1029          in
1030          addAuxiliaryBind env (Rec pairs)               $ \ env ->
1031          go env gn body 
1032        where
1033          (vars,rhss) = unzip prs
1034          tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1035                 -- See notes with tyvars_here above
1036
1037     go env fn body = returnSmpl (emptyFloats env, fn body)
1038
1039     mk_poly tyvars_here var
1040       = getUniqueSmpl           `thenSmpl` \ uniq ->
1041         let
1042             poly_name = setNameUnique (idName var) uniq         -- Keep same name
1043             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
1044             poly_id   = mkLocalId poly_name poly_ty 
1045
1046                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1047                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1048                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1049                 -- at already simplified code, so it doesn't matter
1050                 -- 
1051                 -- It's even right to retain single-occurrence or dead-var info:
1052                 -- Suppose we started with  /\a -> let x = E in B
1053                 -- where x occurs once in B. Then we transform to:
1054                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1055                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1056                 -- the occurrences of x' will be just the occurrences originally
1057                 -- pinned on x.
1058         in
1059         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1060
1061     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1062                 -- Suppose we start with:
1063                 --
1064                 --      x = /\ a -> let g = G in E
1065                 --
1066                 -- Then we'll float to get
1067                 --
1068                 --      x = let poly_g = /\ a -> G
1069                 --          in /\ a -> let g = poly_g a in E
1070                 --
1071                 -- But now the occurrence analyser will see just one occurrence
1072                 -- of poly_g, not inside a lambda, so the simplifier will
1073                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1074                 -- (I used to think that the "don't inline lone occurrences" stuff
1075                 --  would stop this happening, but since it's the *only* occurrence,
1076                 --  PreInlineUnconditionally kicks in first!)
1077                 --
1078                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1079                 --           to appear many times.  (NB: mkInlineMe eliminates
1080                 --           such notes on trivial RHSs, so do it manually.)
1081 -}
1082 \end{code}
1083
1084 %************************************************************************
1085 %*                                                                      *
1086 \subsection{Case absorption and identity-case elimination}
1087 %*                                                                      *
1088 %************************************************************************
1089
1090
1091 mkCase puts a case expression back together, trying various transformations first.
1092
1093 \begin{code}
1094 mkCase :: OutExpr -> OutId -> OutType
1095        -> [OutAlt]              -- Increasing order
1096        -> SimplM OutExpr
1097
1098 mkCase scrut case_bndr ty alts
1099   = getDOptsSmpl                        `thenSmpl` \dflags ->
1100     mkAlts dflags scrut case_bndr alts  `thenSmpl` \ better_alts ->
1101     mkCase1 scrut case_bndr ty better_alts
1102 \end{code}
1103
1104
1105 mkAlts tries these things:
1106
1107 1.  If several alternatives are identical, merge them into
1108     a single DEFAULT alternative.  I've occasionally seen this 
1109     making a big difference:
1110
1111         case e of               =====>     case e of
1112           C _ -> f x                         D v -> ....v....
1113           D v -> ....v....                   DEFAULT -> f x
1114           DEFAULT -> f x
1115
1116    The point is that we merge common RHSs, at least for the DEFAULT case.
1117    [One could do something more elaborate but I've never seen it needed.]
1118    To avoid an expensive test, we just merge branches equal to the *first*
1119    alternative; this picks up the common cases
1120         a) all branches equal
1121         b) some branches equal to the DEFAULT (which occurs first)
1122
1123 2.  Case merging:
1124        case e of b {             ==>   case e of b {
1125          p1 -> rhs1                      p1 -> rhs1
1126          ...                             ...
1127          pm -> rhsm                      pm -> rhsm
1128          _  -> case b of b' {            pn -> let b'=b in rhsn
1129                      pn -> rhsn          ...
1130                      ...                 po -> let b'=b in rhso
1131                      po -> rhso          _  -> let b'=b in rhsd
1132                      _  -> rhsd
1133        }  
1134     
1135     which merges two cases in one case when -- the default alternative of
1136     the outer case scrutises the same variable as the outer case This
1137     transformation is called Case Merging.  It avoids that the same
1138     variable is scrutinised multiple times.
1139
1140
1141 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1142
1143         x | p `is` 1 -> e1
1144           | p `is` 2 -> e2
1145         ...etc...
1146
1147 where @is@ was something like
1148         
1149         p `is` n = p /= (-1) && p == n
1150
1151 This gave rise to a horrible sequence of cases
1152
1153         case p of
1154           (-1) -> $j p
1155           1    -> e1
1156           DEFAULT -> $j p
1157
1158 and similarly in cascade for all the join points!
1159
1160
1161
1162 \begin{code}
1163 --------------------------------------------------
1164 --      1. Merge identical branches
1165 --------------------------------------------------
1166 mkAlts dflags scrut case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1167   | all isDeadBinder bndrs1,                    -- Remember the default 
1168     length filtered_alts < length con_alts      -- alternative comes first
1169   = tick (AltMerge case_bndr)                   `thenSmpl_`
1170     returnSmpl better_alts
1171   where
1172     filtered_alts        = filter keep con_alts
1173     keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1174     better_alts          = (DEFAULT, [], rhs1) : filtered_alts
1175
1176
1177 --------------------------------------------------
1178 --      2.  Merge nested cases
1179 --------------------------------------------------
1180
1181 mkAlts dflags scrut outer_bndr outer_alts
1182   | dopt Opt_CaseMerge dflags,
1183     (outer_alts_without_deflt, maybe_outer_deflt)   <- findDefault outer_alts,
1184     Just (Case (Var scrut_var) inner_bndr _ inner_alts) <- maybe_outer_deflt,
1185     scruting_same_var scrut_var
1186   = let
1187         munged_inner_alts = [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts]
1188         munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1189   
1190         new_alts = mergeAlts outer_alts_without_deflt munged_inner_alts
1191                 -- The merge keeps the inner DEFAULT at the front, if there is one
1192                 -- and eliminates any inner_alts that are shadowed by the outer_alts
1193     in
1194     tick (CaseMerge outer_bndr)                         `thenSmpl_`
1195     returnSmpl new_alts
1196         -- Warning: don't call mkAlts recursively!
1197         -- Firstly, there's no point, because inner alts have already had
1198         -- mkCase applied to them, so they won't have a case in their default
1199         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1200         -- in munge_rhs may put a case into the DEFAULT branch!
1201   where
1202         -- We are scrutinising the same variable if it's
1203         -- the outer case-binder, or if the outer case scrutinises a variable
1204         -- (and it's the same).  Testing both allows us not to replace the
1205         -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1206     scruting_same_var = case scrut of
1207                           Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1208                           other           -> \ v -> v == outer_bndr
1209
1210 ------------------------------------------------
1211 --      Catch-all
1212 ------------------------------------------------
1213
1214 mkAlts dflags scrut case_bndr other_alts = returnSmpl other_alts
1215 \end{code}
1216
1217
1218
1219 =================================================================================
1220
1221 mkCase1 tries these things
1222
1223 1.  Eliminate the case altogether if possible
1224
1225 2.  Case-identity:
1226
1227         case e of               ===> e
1228                 True  -> True;
1229                 False -> False
1230
1231     and similar friends.
1232
1233
1234 Start with a simple situation:
1235
1236         case x# of      ===>   e[x#/y#]
1237           y# -> e
1238
1239 (when x#, y# are of primitive type, of course).  We can't (in general)
1240 do this for algebraic cases, because we might turn bottom into
1241 non-bottom!
1242
1243 Actually, we generalise this idea to look for a case where we're
1244 scrutinising a variable, and we know that only the default case can
1245 match.  For example:
1246 \begin{verbatim}
1247         case x of
1248           0#    -> ...
1249           other -> ...(case x of
1250                          0#    -> ...
1251                          other -> ...) ...
1252 \end{code}
1253 Here the inner case can be eliminated.  This really only shows up in
1254 eliminating error-checking code.
1255
1256 We also make sure that we deal with this very common case:
1257
1258         case e of 
1259           x -> ...x...
1260
1261 Here we are using the case as a strict let; if x is used only once
1262 then we want to inline it.  We have to be careful that this doesn't 
1263 make the program terminate when it would have diverged before, so we
1264 check that 
1265         - x is used strictly, or
1266         - e is already evaluated (it may so if e is a variable)
1267
1268 Lastly, we generalise the transformation to handle this:
1269
1270         case e of       ===> r
1271            True  -> r
1272            False -> r
1273
1274 We only do this for very cheaply compared r's (constructors, literals
1275 and variables).  If pedantic bottoms is on, we only do it when the
1276 scrutinee is a PrimOp which can't fail.
1277
1278 We do it *here*, looking at un-simplified alternatives, because we
1279 have to check that r doesn't mention the variables bound by the
1280 pattern in each alternative, so the binder-info is rather useful.
1281
1282 So the case-elimination algorithm is:
1283
1284         1. Eliminate alternatives which can't match
1285
1286         2. Check whether all the remaining alternatives
1287                 (a) do not mention in their rhs any of the variables bound in their pattern
1288            and  (b) have equal rhss
1289
1290         3. Check we can safely ditch the case:
1291                    * PedanticBottoms is off,
1292                 or * the scrutinee is an already-evaluated variable
1293                 or * the scrutinee is a primop which is ok for speculation
1294                         -- ie we want to preserve divide-by-zero errors, and
1295                         -- calls to error itself!
1296
1297                 or * [Prim cases] the scrutinee is a primitive variable
1298
1299                 or * [Alg cases] the scrutinee is a variable and
1300                      either * the rhs is the same variable
1301                         (eg case x of C a b -> x  ===>   x)
1302                      or     * there is only one alternative, the default alternative,
1303                                 and the binder is used strictly in its scope.
1304                                 [NB this is helped by the "use default binder where
1305                                  possible" transformation; see below.]
1306
1307
1308 If so, then we can replace the case with one of the rhss.
1309
1310 Further notes about case elimination
1311 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1312 Consider:       test :: Integer -> IO ()
1313                 test = print
1314
1315 Turns out that this compiles to:
1316     Print.test
1317       = \ eta :: Integer
1318           eta1 :: State# RealWorld ->
1319           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1320           case hPutStr stdout
1321                  (PrelNum.jtos eta ($w[] @ Char))
1322                  eta1
1323           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1324
1325 Notice the strange '<' which has no effect at all. This is a funny one.  
1326 It started like this:
1327
1328 f x y = if x < 0 then jtos x
1329           else if y==0 then "" else jtos x
1330
1331 At a particular call site we have (f v 1).  So we inline to get
1332
1333         if v < 0 then jtos x 
1334         else if 1==0 then "" else jtos x
1335
1336 Now simplify the 1==0 conditional:
1337
1338         if v<0 then jtos v else jtos v
1339
1340 Now common-up the two branches of the case:
1341
1342         case (v<0) of DEFAULT -> jtos v
1343
1344 Why don't we drop the case?  Because it's strict in v.  It's technically
1345 wrong to drop even unnecessary evaluations, and in practice they
1346 may be a result of 'seq' so we *definitely* don't want to drop those.
1347 I don't really know how to improve this situation.
1348
1349
1350 \begin{code}
1351 --------------------------------------------------
1352 --      0. Check for empty alternatives
1353 --------------------------------------------------
1354
1355 -- This isn't strictly an error.  It's possible that the simplifer might "see"
1356 -- that an inner case has no accessible alternatives before it "sees" that the
1357 -- entire branch of an outer case is inaccessible.  So we simply
1358 -- put an error case here insteadd
1359 mkCase1 scrut case_bndr ty []
1360   = pprTrace "mkCase1: null alts" (ppr case_bndr <+> ppr scrut) $
1361     return (mkApps (Var eRROR_ID)
1362                    [Type ty, Lit (mkStringLit "Impossible alternative")])
1363
1364 --------------------------------------------------
1365 --      1. Eliminate the case altogether if poss
1366 --------------------------------------------------
1367
1368 mkCase1 scrut case_bndr ty [(con,bndrs,rhs)]
1369   -- See if we can get rid of the case altogether
1370   -- See the extensive notes on case-elimination above
1371   -- mkCase made sure that if all the alternatives are equal, 
1372   -- then there is now only one (DEFAULT) rhs
1373  |  all isDeadBinder bndrs,
1374
1375         -- Check that the scrutinee can be let-bound instead of case-bound
1376     exprOkForSpeculation scrut
1377                 -- OK not to evaluate it
1378                 -- This includes things like (==# a# b#)::Bool
1379                 -- so that we simplify 
1380                 --      case ==# a# b# of { True -> x; False -> x }
1381                 -- to just
1382                 --      x
1383                 -- This particular example shows up in default methods for
1384                 -- comparision operations (e.g. in (>=) for Int.Int32)
1385         || exprIsHNF scrut                      -- It's already evaluated
1386         || var_demanded_later scrut             -- It'll be demanded later
1387
1388 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1389 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1390 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1391 --      its argument:  case x of { y -> dataToTag# y }
1392 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1393 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1394 --      other problems
1395 --      Also we don't want to discard 'seq's
1396   = tick (CaseElim case_bndr)                   `thenSmpl_` 
1397     returnSmpl (bindCaseBndr case_bndr scrut rhs)
1398
1399   where
1400         -- The case binder is going to be evaluated later, 
1401         -- and the scrutinee is a simple variable
1402     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1403     var_demanded_later other   = False
1404
1405
1406 --------------------------------------------------
1407 --      2. Identity case
1408 --------------------------------------------------
1409
1410 mkCase1 scrut case_bndr ty alts -- Identity case
1411   | all identity_alt alts
1412   = tick (CaseIdentity case_bndr)               `thenSmpl_`
1413     returnSmpl (re_cast scrut)
1414   where
1415     identity_alt (con, args, rhs) = de_cast rhs `cheapEqExpr` mk_id_rhs con args
1416
1417     mk_id_rhs (DataAlt con) args = mkConApp con (arg_tys ++ varsToCoreExprs args)
1418     mk_id_rhs (LitAlt lit)  _    = Lit lit
1419     mk_id_rhs DEFAULT       _    = Var case_bndr
1420
1421     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1422
1423         -- We've seen this:
1424         --      case e of x { _ -> x `cast` c }
1425         -- And we definitely want to eliminate this case, to give
1426         --      e `cast` c
1427         -- So we throw away the cast from the RHS, and reconstruct
1428         -- it at the other end.  All the RHS casts must be the same
1429         -- if (all identity_alt alts) holds.
1430         -- 
1431         -- Don't worry about nested casts, because the simplifier combines them
1432     de_cast (Cast e _) = e
1433     de_cast e          = e
1434
1435     re_cast scrut = case head alts of
1436                         (_,_,Cast _ co) -> Cast scrut co
1437                         other           -> scrut
1438
1439
1440
1441 --------------------------------------------------
1442 --      Catch-all
1443 --------------------------------------------------
1444 mkCase1 scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1445 \end{code}
1446
1447
1448 When adding auxiliary bindings for the case binder, it's worth checking if
1449 its dead, because it often is, and occasionally these mkCase transformations
1450 cascade rather nicely.
1451
1452 \begin{code}
1453 bindCaseBndr bndr rhs body
1454   | isDeadBinder bndr = body
1455   | otherwise         = bindNonRec bndr rhs body
1456 \end{code}