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