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