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