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