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