d28523f0b0ebf80755792fde200f2b140e69040d
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 module Simplify ( simplTopBinds, simplExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( switchIsOn, opt_SimplDoEtaReduction,
12                           opt_SimplNoPreInlining, 
13                           dopt, DynFlag(Opt_D_dump_inlinings),
14                           SimplifierSwitch(..)
15                         )
16 import SimplMonad
17 import SimplUtils       ( mkCase, tryRhsTyLam, tryEtaExpansion,
18                           simplBinder, simplBinders, simplRecIds, simplLetId,
19                           SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
20                           contResultType, discardInline, countArgs, contIsDupable,
21                           getContArgs, interestingCallContext, interestingArg, isStrictType
22                         )
23 import Var              ( mkSysTyVar, tyVarKind, mustHaveLocalBinding )
24 import VarEnv
25 import Literal          ( Literal )
26 import Id               ( Id, idType, idInfo, isDataConId, hasNoBinding,
27                           idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
28                           idDemandInfo, setIdInfo,
29                           idOccInfo, setIdOccInfo, 
30                           zapLamIdInfo, setOneShotLambda, 
31                         )
32 import IdInfo           ( OccInfo(..), isDeadOcc, isLoopBreaker,
33                           setArityInfo, 
34                           setUnfoldingInfo, atLeastArity,
35                           occInfo
36                         )
37 import Demand           ( isStrict )
38 import DataCon          ( dataConNumInstArgs, dataConRepStrictness,
39                           dataConSig, dataConArgTys
40                         )
41 import CoreSyn
42 import PprCore          ( pprParendExpr, pprCoreExpr )
43 import CoreUnfold       ( mkOtherCon, mkUnfolding, otherCons,
44                           callSiteInline
45                         )
46 import CoreUtils        ( cheapEqExpr, exprIsDupable, exprIsTrivial, 
47                           exprIsConApp_maybe, mkPiType, findAlt, findDefault,
48                           exprType, coreAltsType, exprIsValue, 
49                           exprOkForSpeculation, exprArity, exprIsCheap,
50                           mkCoerce, mkSCC, mkInlineMe, mkAltExpr
51                         )
52 import Rules            ( lookupRule )
53 import CostCentre       ( currentCCS )
54 import Type             ( mkTyVarTys, isUnLiftedType, seqType,
55                           mkFunTy, splitTyConApp_maybe, tyConAppArgs,
56                           funResultTy, splitFunTy_maybe, splitFunTy
57                         )
58 import Subst            ( mkSubst, substTy, substEnv, substExpr,
59                           isInScope, lookupIdSubst, simplIdInfo
60                         )
61 import TyCon            ( isDataTyCon, tyConDataConsIfAvailable )
62 import TysPrim          ( realWorldStatePrimTy )
63 import PrelInfo         ( realWorldPrimId )
64 import OrdList
65 import Maybes           ( maybeToBool )
66 import Outputable
67 \end{code}
68
69
70 The guts of the simplifier is in this module, but the driver
71 loop for the simplifier is in SimplCore.lhs.
72
73
74 -----------------------------------------
75         *** IMPORTANT NOTE ***
76 -----------------------------------------
77 The simplifier used to guarantee that the output had no shadowing, but
78 it does not do so any more.   (Actually, it never did!)  The reason is
79 documented with simplifyArgs.
80
81
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Bindings}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 simplTopBinds :: [InBind] -> SimplM [OutBind]
92
93 simplTopBinds binds
94   =     -- Put all the top-level binders into scope at the start
95         -- so that if a transformation rule has unexpectedly brought
96         -- anything into scope, then we don't get a complaint about that.
97         -- It's rather as if the top-level binders were imported.
98     simplRecIds (bindersOfBinds binds)  $ \ bndrs' -> 
99     simpl_binds binds bndrs'            `thenSmpl` \ (binds', _) ->
100     freeTick SimplifierDone             `thenSmpl_`
101     returnSmpl (fromOL binds')
102   where
103
104         -- We need to track the zapped top-level binders, because
105         -- they should have their fragile IdInfo zapped (notably occurrence info)
106     simpl_binds []                        bs     = ASSERT( null bs ) returnSmpl (nilOL, panic "simplTopBinds corner")
107     simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr  b rhs       (simpl_binds binds bs)
108     simpl_binds (Rec pairs       : binds) bs     = simplRecBind  True pairs (take n bs) (simpl_binds binds (drop n bs))
109                                                  where 
110                                                    n = length pairs
111
112 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
113              -> SimplM (OutStuff a) -> SimplM (OutStuff a)
114 simplRecBind top_lvl pairs bndrs' thing_inside
115   = go pairs bndrs'             `thenSmpl` \ (binds', (_, (binds'', res))) ->
116     returnSmpl (unitOL (Rec (flattenBinds (fromOL binds'))) `appOL` binds'', res)
117   where
118     go [] _ = thing_inside      `thenSmpl` \ stuff ->
119               returnOutStuff stuff
120         
121     go ((bndr, rhs) : pairs) (bndr' : bndrs')
122         = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
123                 -- Don't float unboxed bindings out,
124                 -- because we can't "rec" them
125 \end{code}
126
127
128 %************************************************************************
129 %*                                                                      *
130 \subsection[Simplify-simplExpr]{The main function: simplExpr}
131 %*                                                                      *
132 %************************************************************************
133
134 The reason for this OutExprStuff stuff is that we want to float *after*
135 simplifying a RHS, not before.  If we do so naively we get quadratic
136 behaviour as things float out.
137
138 To see why it's important to do it after, consider this (real) example:
139
140         let t = f x
141         in fst t
142 ==>
143         let t = let a = e1
144                     b = e2
145                 in (a,b)
146         in fst t
147 ==>
148         let a = e1
149             b = e2
150             t = (a,b)
151         in
152         a       -- Can't inline a this round, cos it appears twice
153 ==>
154         e1
155
156 Each of the ==> steps is a round of simplification.  We'd save a
157 whole round if we float first.  This can cascade.  Consider
158
159         let f = g d
160         in \x -> ...f...
161 ==>
162         let f = let d1 = ..d.. in \y -> e
163         in \x -> ...f...
164 ==>
165         let d1 = ..d..
166         in \x -> ...(\y ->e)...
167
168 Only in this second round can the \y be applied, and it 
169 might do the same again.
170
171
172 \begin{code}
173 simplExpr :: CoreExpr -> SimplM CoreExpr
174 simplExpr expr = getSubst       `thenSmpl` \ subst ->
175                  simplExprC expr (mkStop (substTy subst (exprType expr)))
176         -- The type in the Stop continuation is usually not used
177         -- It's only needed when discarding continuations after finding
178         -- a function that returns bottom.
179         -- Hence the lazy substitution
180
181 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
182         -- Simplify an expression, given a continuation
183
184 simplExprC expr cont = simplExprF expr cont     `thenSmpl` \ (floats, (_, body)) ->
185                        returnSmpl (wrapFloats floats body)
186
187 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
188         -- Simplify an expression, returning floated binds
189
190 simplExprF (Var v)          cont = simplVar v cont
191 simplExprF (Lit lit)        cont = simplLit lit cont
192 simplExprF expr@(Lam _ _)   cont = simplLam expr cont
193 simplExprF (Note note expr) cont = simplNote note expr cont
194
195 simplExprF (App fun arg) cont
196   = getSubstEnv         `thenSmpl` \ se ->
197     simplExprF fun (ApplyTo NoDup arg se cont)
198
199 simplExprF (Type ty) cont
200   = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
201     simplType ty        `thenSmpl` \ ty' ->
202     rebuild (Type ty') cont
203
204 simplExprF (Case scrut bndr alts) cont
205   = getSubstEnv                 `thenSmpl` \ subst_env ->
206     getSwitchChecker            `thenSmpl` \ chkr ->
207     if not (switchIsOn chkr NoCaseOfCase) then
208         -- Simplify the scrutinee with a Select continuation
209         simplExprF scrut (Select NoDup bndr alts subst_env cont)
210
211     else
212         -- If case-of-case is off, simply simplify the case expression
213         -- in a vanilla Stop context, and rebuild the result around it
214         simplExprC scrut (Select NoDup bndr alts subst_env 
215                                  (mkStop (contResultType cont)))        `thenSmpl` \ case_expr' ->
216         rebuild case_expr' cont
217
218 simplExprF (Let (Rec pairs) body) cont
219   = simplRecIds (map fst pairs)                 $ \ bndrs' -> 
220         -- NB: bndrs' don't have unfoldings or spec-envs
221         -- We add them as we go down, using simplPrags
222
223     simplRecBind False pairs bndrs' (simplExprF body cont)
224
225 -- A non-recursive let is dealt with by simplNonRecBind
226 simplExprF (Let (NonRec bndr rhs) body) cont
227   = getSubstEnv                 `thenSmpl` \ se ->
228     simplNonRecBind bndr rhs se (contResultType cont)   $
229     simplExprF body cont
230
231
232 ---------------------------------
233 simplType :: InType -> SimplM OutType
234 simplType ty
235   = getSubst    `thenSmpl` \ subst ->
236     let
237         new_ty = substTy subst ty
238     in
239     seqType new_ty `seq`  
240     returnSmpl new_ty
241
242 ---------------------------------
243 simplLit :: Literal -> SimplCont -> SimplM OutExprStuff
244
245 simplLit lit (Select _ bndr alts se cont)
246   = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
247
248 simplLit lit cont = rebuild (Lit lit) cont
249 \end{code}
250
251
252 %************************************************************************
253 %*                                                                      *
254 \subsection{Lambdas}
255 %*                                                                      *
256 %************************************************************************
257
258 \begin{code}
259 simplLam fun cont
260   = go fun cont
261   where
262     zap_it  = mkLamBndrZapper fun cont
263     cont_ty = contResultType cont
264
265         -- Type-beta reduction
266     go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
267       = ASSERT( isTyVar bndr )
268         tick (BetaReduction bndr)       `thenSmpl_`
269         simplTyArg ty_arg arg_se        `thenSmpl` \ ty_arg' ->
270         extendSubst bndr (DoneTy ty_arg')
271         (go body body_cont)
272
273         -- Ordinary beta reduction
274     go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
275       = tick (BetaReduction bndr)                       `thenSmpl_`
276         simplNonRecBind zapped_bndr arg arg_se cont_ty
277         (go body body_cont)
278       where
279         zapped_bndr = zap_it bndr
280
281         -- Not enough args
282     go lam@(Lam _ _) cont = completeLam [] lam cont
283
284         -- Exactly enough args
285     go expr cont = simplExprF expr cont
286
287 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
288 -- continuation, so there are real lambdas left to put in the result
289
290 -- We try for eta reduction here, but *only* if we get all the 
291 -- way to an exprIsTrivial expression.    
292 -- We don't want to remove extra lambdas unless we are going 
293 -- to avoid allocating this thing altogether
294
295 completeLam rev_bndrs (Lam bndr body) cont
296   = simplBinder bndr                    $ \ bndr' ->
297     completeLam (bndr':rev_bndrs) body cont
298
299 completeLam rev_bndrs body cont
300   = simplExpr body                      `thenSmpl` \ body' ->
301     case try_eta body' of
302         Just etad_lam -> tick (EtaReduction (head rev_bndrs))   `thenSmpl_`
303                          rebuild etad_lam cont
304
305         Nothing       -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
306   where
307         -- We don't use CoreUtils.etaReduce, because we can be more
308         -- efficient here:
309         --  (a) we already have the binders,
310         --  (b) we can do the triviality test before computing the free vars
311         --      [in fact I take the simple path and look for just a variable]
312         --  (c) we don't want to eta-reduce a data con worker or primop
313         --      because we only have to eta-expand them later when we saturate
314     try_eta body | not opt_SimplDoEtaReduction = Nothing
315                  | otherwise                   = go rev_bndrs body
316
317     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
318     go []       body          | ok_body body = Just body        -- Success!
319     go _        _                            = Nothing          -- Failure!
320
321     ok_body (Var v) = not (v `elem` rev_bndrs) && not (hasNoBinding v)
322     ok_body other   = False
323     ok_arg b arg    = varToCoreExpr b `cheapEqExpr` arg
324
325 mkLamBndrZapper :: CoreExpr     -- Function
326                 -> SimplCont    -- The context
327                 -> Id -> Id     -- Use this to zap the binders
328 mkLamBndrZapper fun cont
329   | n_args >= n_params fun = \b -> b            -- Enough args
330   | otherwise              = \b -> zapLamIdInfo b
331   where
332         -- NB: we count all the args incl type args
333         -- so we must count all the binders (incl type lambdas)
334     n_args = countArgs cont
335
336     n_params (Note _ e) = n_params e
337     n_params (Lam b e)  = 1 + n_params e
338     n_params other      = 0::Int
339 \end{code}
340
341
342 %************************************************************************
343 %*                                                                      *
344 \subsection{Notes}
345 %*                                                                      *
346 %************************************************************************
347
348 \begin{code}
349 simplNote (Coerce to from) body cont
350   = getInScope                  `thenSmpl` \ in_scope ->
351     let
352         addCoerce s1 k1 (CoerceIt t1 cont)
353                 --      coerce T1 S1 (coerce S1 K1 e)
354                 -- ==>
355                 --      e,                      if T1=K1
356                 --      coerce T1 K1 e,         otherwise
357                 --
358                 -- For example, in the initial form of a worker
359                 -- we may find  (coerce T (coerce S (\x.e))) y
360                 -- and we'd like it to simplify to e[y/x] in one round 
361                 -- of simplification
362           | t1 == k1  = cont                    -- The coerces cancel out
363           | otherwise = CoerceIt t1 cont        -- They don't cancel, but 
364                                                 -- the inner one is redundant
365
366         addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
367           | Just (s1, s2) <- splitFunTy_maybe s1s2
368                 --      (coerce (T1->T2) (S1->S2) F) E
369                 -- ===> 
370                 --      coerce T2 S2 (F (coerce S1 T1 E))
371                 --
372                 -- t1t2 must be a function type, T1->T2
373                 -- but s1s2 might conceivably not be
374                 --
375                 -- When we build the ApplyTo we can't mix the out-types
376                 -- with the InExpr in the argument, so we simply substitute
377                 -- to make it all consistent.  This isn't a common case.
378           = let 
379                 (t1,t2) = splitFunTy t1t2
380                 new_arg = mkCoerce s1 t1 (substExpr (mkSubst in_scope arg_se) arg)
381             in
382             ApplyTo dup new_arg emptySubstEnv (addCoerce t2 s2 cont)
383                         
384         addCoerce to' _ cont = CoerceIt to' cont
385     in
386     simplType to                `thenSmpl` \ to' ->
387     simplType from              `thenSmpl` \ from' ->
388     simplExprF body (addCoerce to' from' cont)
389
390                 
391 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
392 -- inlining.  All other CCCSs are mapped to currentCCS.
393 simplNote (SCC cc) e cont
394   = setEnclosingCC currentCCS $
395     simplExpr e         `thenSmpl` \ e ->
396     rebuild (mkSCC cc e) cont
397
398 simplNote InlineCall e cont
399   = simplExprF e (InlinePlease cont)
400
401 --       Comments about the InlineMe case 
402 --       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403 -- Don't inline in the RHS of something that has an
404 -- inline pragma.  But be careful that the InScopeEnv that
405 -- we return does still have inlinings on!
406 -- 
407 -- It really is important to switch off inlinings.  This function
408 -- may be inlinined in other modules, so we don't want to remove
409 -- (by inlining) calls to functions that have specialisations, or
410 -- that may have transformation rules in an importing scope.
411 -- E.g.         {-# INLINE f #-}
412 --              f x = ...g...
413 -- and suppose that g is strict *and* has specialisations.
414 -- If we inline g's wrapper, we deny f the chance of getting
415 -- the specialised version of g when f is inlined at some call site
416 -- (perhaps in some other module).
417
418 -- It's also important not to inline a worker back into a wrapper.
419 -- A wrapper looks like
420 --      wraper = inline_me (\x -> ...worker... )
421 -- Normally, the inline_me prevents the worker getting inlined into
422 -- the wrapper (initially, the worker's only call site!).  But,
423 -- if the wrapper is sure to be called, the strictness analyser will
424 -- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
425 -- continuation.  That's why the keep_inline predicate returns True for
426 -- ArgOf continuations.  It shouldn't do any harm not to dissolve the
427 -- inline-me note under these circumstances
428
429 simplNote InlineMe e cont
430   | keep_inline cont            -- Totally boring continuation
431   =                             -- Don't inline inside an INLINE expression
432     setBlackList noInlineBlackList (simplExpr e)        `thenSmpl` \ e' ->
433     rebuild (mkInlineMe e') cont
434
435   | otherwise   -- Dissolve the InlineMe note if there's
436                 -- an interesting context of any kind to combine with
437                 -- (even a type application -- anything except Stop)
438   = simplExprF e cont
439   where
440     keep_inline (Stop _ _)    = True            -- See notes above
441     keep_inline (ArgOf _ _ _) = True            -- about this predicate
442     keep_inline other         = False
443 \end{code}
444
445
446 %************************************************************************
447 %*                                                                      *
448 \subsection{Binding}
449 %*                                                                      *
450 %************************************************************************
451
452 @simplNonRecBind@ is used for non-recursive lets in expressions, 
453 as well as true beta reduction.
454
455 Very similar to @simplLazyBind@, but not quite the same.
456
457 \begin{code}
458 simplNonRecBind :: InId                 -- Binder
459           -> InExpr -> SubstEnv         -- Arg, with its subst-env
460           -> OutType                    -- Type of thing computed by the context
461           -> SimplM OutExprStuff        -- The body
462           -> SimplM OutExprStuff
463 #ifdef DEBUG
464 simplNonRecBind bndr rhs rhs_se cont_ty thing_inside
465   | isTyVar bndr
466   = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
467 #endif
468
469 simplNonRecBind bndr rhs rhs_se cont_ty thing_inside
470   | preInlineUnconditionally False {- not black listed -} bndr
471   = tick (PreInlineUnconditionally bndr)                `thenSmpl_`
472     extendSubst bndr (ContEx rhs_se rhs) thing_inside
473
474   | otherwise
475   =     -- Simplify the binder.
476         -- Don't use simplBinder because that doesn't keep 
477         -- fragile occurrence in the substitution
478     simplLetId bndr                                     $ \ bndr' ->
479     getSubst                                            `thenSmpl` \ bndr_subst ->
480     let
481         -- Substitute its IdInfo (which simplLetId does not)
482         -- The appropriate substitution env is the one right here,
483         -- not rhs_se.  Often they are the same, when all this 
484         -- has arisen from an application (\x. E) RHS, perhaps they aren't
485         bndr''    = simplIdInfo bndr_subst (idInfo bndr) bndr'
486         bndr_ty'  = idType bndr'
487         is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
488     in
489     modifyInScope bndr'' bndr''                         $
490
491         -- Simplify the argument
492     simplValArg bndr_ty' is_strict rhs rhs_se cont_ty   $ \ rhs' ->
493
494         -- Now complete the binding and simplify the body
495     if needsCaseBinding bndr_ty' rhs' then
496         addCaseBind bndr'' rhs' thing_inside
497     else
498         completeBinding bndr bndr'' False False rhs' thing_inside
499 \end{code}
500
501
502 \begin{code}
503 simplTyArg :: InType -> SubstEnv -> SimplM OutType
504 simplTyArg ty_arg se
505   = getInScope          `thenSmpl` \ in_scope ->
506     let
507         ty_arg' = substTy (mkSubst in_scope se) ty_arg
508     in
509     seqType ty_arg'     `seq`
510     returnSmpl ty_arg'
511
512 simplValArg :: OutType          -- rhs_ty: Type of arg; used only occasionally
513             -> Bool             -- True <=> evaluate eagerly
514             -> InExpr -> SubstEnv
515             -> OutType          -- cont_ty: Type of thing computed by the context
516             -> (OutExpr -> SimplM OutExprStuff) 
517                                 -- Takes an expression of type rhs_ty, 
518                                 -- returns an expression of type cont_ty
519             -> SimplM OutExprStuff      -- An expression of type cont_ty
520
521 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
522   | is_strict
523   = getEnv                              `thenSmpl` \ env ->
524     setSubstEnv arg_se                          $
525     simplExprF arg (ArgOf NoDup cont_ty         $ \ rhs' ->
526     setAllExceptInScope env                     $
527     thing_inside rhs')
528
529   | otherwise
530   = simplRhs False {- Not top level -} 
531              True {- OK to float unboxed -}
532              arg_ty arg arg_se 
533              thing_inside
534 \end{code}
535
536
537 completeBinding
538         - deals only with Ids, not TyVars
539         - take an already-simplified RHS
540
541 It does *not* attempt to do let-to-case.  Why?  Because they are used for
542
543         - top-level bindings
544                 (when let-to-case is impossible) 
545
546         - many situations where the "rhs" is known to be a WHNF
547                 (so let-to-case is inappropriate).
548
549 \begin{code}
550 completeBinding :: InId                 -- Binder
551                 -> OutId                -- New binder
552                 -> Bool                 -- True <=> top level
553                 -> Bool                 -- True <=> black-listed; don't inline
554                 -> OutExpr              -- Simplified RHS
555                 -> SimplM (OutStuff a)  -- Thing inside
556                 -> SimplM (OutStuff a)
557
558 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
559   |  isDeadOcc occ_info         -- This happens; for example, the case_bndr during case of
560                                 -- known constructor:  case (a,b) of x { (p,q) -> ... }
561                                 -- Here x isn't mentioned in the RHS, so we don't want to
562                                 -- create the (dead) let-binding  let x = (a,b) in ...
563   =  thing_inside
564
565   | trivial_rhs && not must_keep_binding
566         -- We're looking at a binding with a trivial RHS, so
567         -- perhaps we can discard it altogether!
568         --
569         -- NB: a loop breaker has must_keep_binding = True
570         -- and non-loop-breakers only have *forward* references
571         -- Hence, it's safe to discard the binding
572         --      
573         -- NOTE: This isn't our last opportunity to inline.
574         -- We're at the binding site right now, and
575         -- we'll get another opportunity when we get to the ocurrence(s)
576
577         -- Note that we do this unconditional inlining only for trival RHSs.
578         -- Don't inline even WHNFs inside lambdas; doing so may
579         -- simply increase allocation when the function is called
580         -- This isn't the last chance; see NOTE above.
581         --
582         -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
583         -- Why?  Because we don't even want to inline them into the
584         -- RHS of constructor arguments. See NOTE above
585         --
586         -- NB: Even NOINLINEis ignored here: if the rhs is trivial
587         -- it's best to inline it anyway.  We often get a=E; b=a
588         -- from desugaring, with both a and b marked NOINLINE.
589   =             -- Drop the binding
590     extendSubst old_bndr (DoneEx new_rhs)       $
591                 -- Use the substitution to make quite, quite sure that the substitution
592                 -- will happen, since we are going to discard the binding
593     tick (PostInlineUnconditionally old_bndr)   `thenSmpl_`
594     thing_inside
595
596   | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs,
597     not trivial_rhs && not (isUnLiftedType inner_ty)
598         -- x = coerce t e  ==>  c = e; x = inline_me (coerce t c)
599         -- Now x can get inlined, which moves the coercion
600         -- to the usage site.  This is a bit like worker/wrapper stuff,
601         -- but it's useful to do it very promptly, so that
602         --      x = coerce T (I# 3)
603         -- get's w/wd to
604         --      c = I# 3
605         --      x = coerce T c
606         -- This in turn means that
607         --      case (coerce Int x) of ...
608         -- will inline x.  
609         -- Also the full-blown w/w thing isn't set up for non-functions
610         --
611         -- The (not (isUnLiftedType inner_ty)) avoids the nasty case of
612         --      x::Int = coerce Int Int# (foo y)
613         -- ==>
614         --      v::Int# = foo y
615         --      x::Int  = coerce Int Int# v
616         -- which would be bogus because then v will be evaluated strictly.
617         -- How can this arise?  Via 
618         --      x::Int = case (foo y) of { ... }
619         -- followed by case elimination.
620         --
621         -- The inline_me note is so that the simplifier doesn't 
622         -- just substitute c back inside x's rhs!  (Typically, x will
623         -- get substituted away, but not if it's exported.)
624   = newId SLIT("c") inner_ty                                    $ \ c_id ->
625     completeBinding c_id c_id top_lvl False inner_rhs           $
626     completeBinding old_bndr new_bndr top_lvl black_listed
627                     (Note InlineMe (Note coercion (Var c_id)))  $
628     thing_inside
629
630   |  otherwise
631   = let
632                 -- We make new IdInfo for the new binder by starting from the old binder, 
633                 -- doing appropriate substitutions.
634                 -- Then we add arity and unfolding info to get the new binder
635         new_bndr_info = idInfo new_bndr `setArityInfo` arity_info
636
637                 -- Add the unfolding *only* for non-loop-breakers
638                 -- Making loop breakers not have an unfolding at all 
639                 -- means that we can avoid tests in exprIsConApp, for example.
640                 -- This is important: if exprIsConApp says 'yes' for a recursive
641                 -- thing, then we can get into an infinite loop
642         info_w_unf | loop_breaker = new_bndr_info
643                    | otherwise    = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
644
645         final_id = new_bndr `setIdInfo` info_w_unf
646     in
647                 -- These seqs forces the Id, and hence its IdInfo,
648                 -- and hence any inner substitutions
649     final_id                            `seq`
650     addLetBind (NonRec final_id new_rhs)        $
651     modifyInScope new_bndr final_id thing_inside
652
653   where
654     old_info          = idInfo old_bndr
655     occ_info          = occInfo old_info
656     loop_breaker      = isLoopBreaker occ_info
657     trivial_rhs       = exprIsTrivial new_rhs
658     must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
659     arity_info        = atLeastArity (exprArity new_rhs)
660 \end{code}    
661
662
663
664 %************************************************************************
665 %*                                                                      *
666 \subsection{simplLazyBind}
667 %*                                                                      *
668 %************************************************************************
669
670 simplLazyBind basically just simplifies the RHS of a let(rec).
671 It does two important optimisations though:
672
673         * It floats let(rec)s out of the RHS, even if they
674           are hidden by big lambdas
675
676         * It does eta expansion
677
678 \begin{code}
679 simplLazyBind :: Bool                   -- True <=> top level
680               -> InId -> OutId
681               -> InExpr                 -- The RHS
682               -> SimplM (OutStuff a)    -- The body of the binding
683               -> SimplM (OutStuff a)
684 -- When called, the subst env is correct for the entire let-binding
685 -- and hence right for the RHS.
686 -- Also the binder has already been simplified, and hence is in scope
687
688 simplLazyBind top_lvl bndr bndr' rhs thing_inside
689   = getBlackList                `thenSmpl` \ black_list_fn ->
690     let
691         black_listed = black_list_fn bndr
692     in
693
694     if preInlineUnconditionally black_listed bndr then
695         -- Inline unconditionally
696         tick (PreInlineUnconditionally bndr)    `thenSmpl_`
697         getSubstEnv                             `thenSmpl` \ rhs_se ->
698         (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
699     else
700
701         -- Simplify the RHS
702     getSubst                                    `thenSmpl` \ rhs_subst ->
703     let
704         -- Substitute IdInfo on binder, in the light of earlier
705         -- substitutions in this very letrec, and extend the in-scope
706         -- env so that it can see the new thing
707         bndr'' = simplIdInfo rhs_subst (idInfo bndr) bndr'
708     in
709     modifyInScope bndr'' bndr''                         $
710
711     simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
712              (idType bndr')
713              rhs (substEnv rhs_subst)                   $ \ rhs' ->
714
715         -- Now compete the binding and simplify the body
716     completeBinding bndr bndr'' top_lvl black_listed rhs' thing_inside
717 \end{code}
718
719
720
721 \begin{code}
722 simplRhs :: Bool                -- True <=> Top level
723          -> Bool                -- True <=> OK to float unboxed (speculative) bindings
724                                 --          False for (a) recursive and (b) top-level bindings
725          -> OutType             -- Type of RHS; used only occasionally
726          -> InExpr -> SubstEnv
727          -> (OutExpr -> SimplM (OutStuff a))
728          -> SimplM (OutStuff a)
729 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
730   =     -- Simplify it
731     setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty))      `thenSmpl` \ (floats1, (rhs_in_scope, rhs1)) ->
732     let
733         (floats2, rhs2) = splitFloats float_ubx floats1 rhs1
734     in
735                 -- There's a subtlety here.  There may be a binding (x* = e) in the
736                 -- floats, where the '*' means 'will be demanded'.  So is it safe
737                 -- to float it out?  Answer no, but it won't matter because
738                 -- we only float if arg' is a WHNF,
739                 -- and so there can't be any 'will be demanded' bindings in the floats.
740                 -- Hence the assert
741     WARN( any demanded_float (fromOL floats2), ppr (fromOL floats2) )
742
743         --                      Transform the RHS
744         -- It's important that we do eta expansion on function *arguments* (which are
745         -- simplified with simplRhs), as well as let-bound right-hand sides.  
746         -- Otherwise we find that things like
747         --      f (\x -> case x of I# x' -> coerce T (\ y -> ...))
748         -- get right through to the code generator as two separate lambdas, 
749         -- which is a Bad Thing
750     tryRhsTyLam rhs2            `thenSmpl` \ (floats3, rhs3) ->
751     tryEtaExpansion rhs3 rhs_ty `thenSmpl` \ (floats4, rhs4) ->
752
753         -- Float lets if (a) we're at the top level
754         -- or            (b) the resulting RHS is one we'd like to expose
755     if (top_lvl || exprIsCheap rhs4) then
756         (if (isNilOL floats2 && null floats3 && null floats4) then
757                 returnSmpl ()
758          else
759                 tick LetFloatFromLet)                   `thenSmpl_`
760
761         addFloats floats2 rhs_in_scope  $
762         addAuxiliaryBinds floats3       $
763         addAuxiliaryBinds floats4       $
764         thing_inside rhs4
765     else        
766                 -- Don't do the float
767         thing_inside (wrapFloats floats1 rhs1)
768
769 demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
770                 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
771 demanded_float (Rec _)      = False
772
773 -- If float_ubx is true we float all the bindings, otherwise
774 -- we just float until we come across an unlifted one.
775 -- Remember that the unlifted bindings in the floats are all for
776 -- guaranteed-terminating non-exception-raising unlifted things,
777 -- which we are happy to do speculatively.  However, we may still
778 -- not be able to float them out, because the context
779 -- is either a Rec group, or the top level, neither of which
780 -- can tolerate them.
781 splitFloats float_ubx floats rhs
782   | float_ubx = (floats, rhs)           -- Float them all
783   | otherwise = go (fromOL floats)
784   where
785     go []                   = (nilOL, rhs)
786     go (f:fs) | must_stay f = (nilOL, mkLets (f:fs) rhs)
787               | otherwise   = case go fs of
788                                    (out, rhs') -> (f `consOL` out, rhs')
789
790     must_stay (Rec prs)    = False      -- No unlifted bindings in here
791     must_stay (NonRec b r) = isUnLiftedType (idType b)
792 \end{code}
793
794
795
796 %************************************************************************
797 %*                                                                      *
798 \subsection{Variables}
799 %*                                                                      *
800 %************************************************************************
801
802 \begin{code}
803 simplVar var cont
804   = getSubst            `thenSmpl` \ subst ->
805     case lookupIdSubst subst var of
806         DoneEx e        -> zapSubstEnv (simplExprF e cont)
807         ContEx env1 e   -> setSubstEnv env1 (simplExprF e cont)
808         DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
809                                  text "simplVar:" <+> ppr var )
810                            zapSubstEnv (completeCall var1 occ cont)
811                 -- The template is already simplified, so don't re-substitute.
812                 -- This is VITAL.  Consider
813                 --      let x = e in
814                 --      let y = \z -> ...x... in
815                 --      \ x -> ...y...
816                 -- We'll clone the inner \x, adding x->x' in the id_subst
817                 -- Then when we inline y, we must *not* replace x by x' in
818                 -- the inlined copy!!
819
820 ---------------------------------------------------------
821 --      Dealing with a call
822
823 completeCall var occ_info cont
824   = getBlackList                `thenSmpl` \ black_list_fn ->
825     getInScope                  `thenSmpl` \ in_scope ->
826     getContArgs var cont        `thenSmpl` \ (args, call_cont, inline_call) ->
827     getDOptsSmpl                `thenSmpl` \ dflags ->
828     let
829         black_listed       = black_list_fn var
830         arg_infos          = [ interestingArg in_scope arg subst 
831                              | (arg, subst, _) <- args, isValArg arg]
832
833         interesting_cont = interestingCallContext (not (null args)) 
834                                                   (not (null arg_infos))
835                                                   call_cont
836
837         inline_cont | inline_call = discardInline cont
838                     | otherwise   = cont
839
840         maybe_inline = callSiteInline dflags black_listed inline_call occ_info
841                                       var arg_infos interesting_cont
842     in
843         -- First, look for an inlining
844     case maybe_inline of {
845         Just unfolding          -- There is an inlining!
846           ->  tick (UnfoldingDone var)          `thenSmpl_`
847               simplExprF unfolding inline_cont
848
849         ;
850         Nothing ->              -- No inlining!
851
852
853     simplifyArgs (isDataConId var) args (contResultType call_cont)  $ \ args' ->
854
855         -- Next, look for rules or specialisations that match
856         --
857         -- It's important to simplify the args first, because the rule-matcher
858         -- doesn't do substitution as it goes.  We don't want to use subst_args
859         -- (defined in the 'where') because that throws away useful occurrence info,
860         -- and perhaps-very-important specialisations.
861         --
862         -- Some functions have specialisations *and* are strict; in this case,
863         -- we don't want to inline the wrapper of the non-specialised thing; better
864         -- to call the specialised thing instead.
865         -- But the black-listing mechanism means that inlining of the wrapper
866         -- won't occur for things that have specialisations till a later phase, so
867         -- it's ok to try for inlining first.
868         --
869         -- You might think that we shouldn't apply rules for a loop breaker: 
870         -- doing so might give rise to an infinite loop, because a RULE is
871         -- rather like an extra equation for the function:
872         --      RULE:           f (g x) y = x+y
873         --      Eqn:            f a     y = a-y
874         --
875         -- But it's too drastic to disable rules for loop breakers.  
876         -- Even the foldr/build rule would be disabled, because foldr 
877         -- is recursive, and hence a loop breaker:
878         --      foldr k z (build g) = g k z
879         -- So it's up to the programmer: rules can cause divergence
880
881     getSwitchChecker    `thenSmpl` \ chkr ->
882     let
883         maybe_rule | switchIsOn chkr DontApplyRules = Nothing
884                    | otherwise                      = lookupRule in_scope var args' 
885     in
886     case maybe_rule of {
887         Just (rule_name, rule_rhs) -> 
888                 tick (RuleFired rule_name)                      `thenSmpl_`
889 #ifdef DEBUG
890                 (if dopt Opt_D_dump_inlinings dflags then
891                    pprTrace "Rule fired" (vcat [
892                         text "Rule:" <+> ptext rule_name,
893                         text "Before:" <+> ppr var <+> sep (map pprParendExpr args'),
894                         text "After: " <+> pprCoreExpr rule_rhs])
895                  else
896                         id)             $
897 #endif
898                 simplExprF rule_rhs call_cont ;
899         
900         Nothing ->              -- No rules
901
902         -- Done
903     rebuild (mkApps (Var var) args') call_cont
904     }}
905
906
907 ---------------------------------------------------------
908 --      Simplifying the arguments of a call
909
910 simplifyArgs :: Bool                            -- It's a data constructor
911              -> [(InExpr, SubstEnv, Bool)]      -- Details of the arguments
912              -> OutType                         -- Type of the continuation
913              -> ([OutExpr] -> SimplM OutExprStuff)
914              -> SimplM OutExprStuff
915
916 -- Simplify the arguments to a call.
917 -- This part of the simplifier may break the no-shadowing invariant
918 -- Consider
919 --      f (...(\a -> e)...) (case y of (a,b) -> e')
920 -- where f is strict in its second arg
921 -- If we simplify the innermost one first we get (...(\a -> e)...)
922 -- Simplifying the second arg makes us float the case out, so we end up with
923 --      case y of (a,b) -> f (...(\a -> e)...) e'
924 -- So the output does not have the no-shadowing invariant.  However, there is
925 -- no danger of getting name-capture, because when the first arg was simplified
926 -- we used an in-scope set that at least mentioned all the variables free in its
927 -- static environment, and that is enough.
928 --
929 -- We can't just do innermost first, or we'd end up with a dual problem:
930 --      case x of (a,b) -> f e (...(\a -> e')...)
931 --
932 -- I spent hours trying to recover the no-shadowing invariant, but I just could
933 -- not think of an elegant way to do it.  The simplifier is already knee-deep in
934 -- continuations.  We have to keep the right in-scope set around; AND we have
935 -- to get the effect that finding (error "foo") in a strict arg position will
936 -- discard the entire application and replace it with (error "foo").  Getting
937 -- all this at once is TOO HARD!
938
939 simplifyArgs is_data_con args cont_ty thing_inside
940   | not is_data_con
941   = go args thing_inside
942
943   | otherwise   -- It's a data constructor, so we want 
944                 -- to switch off inlining in the arguments
945                 -- If we don't do this, consider:
946                 --      let x = +# p q in C {x}
947                 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
948                 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
949   = getBlackList                                `thenSmpl` \ old_bl ->
950     setBlackList noInlineBlackList              $
951     go args                                     $ \ args' ->
952     setBlackList old_bl                         $
953     thing_inside args'
954
955   where
956     go []         thing_inside = thing_inside []
957     go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty    $ \ arg' ->
958                                  go args                                $ \ args' ->
959                                  thing_inside (arg':args')
960
961 simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
962   = simplTyArg ty_arg se        `thenSmpl` \ new_ty_arg ->
963     thing_inside (Type new_ty_arg)
964
965 simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
966   = getInScope          `thenSmpl` \ in_scope ->
967     let
968         arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
969     in
970     if not is_data_con then
971         -- An ordinary function
972         simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
973     else
974         -- A data constructor
975         -- simplifyArgs has already switched off inlining, so 
976         -- all we have to do here is to let-bind any non-trivial argument
977
978         -- It's not always the case that new_arg will be trivial
979         -- Consider             f x
980         -- where, in one pass, f gets substituted by a constructor,
981         -- but x gets substituted by an expression (assume this is the
982         -- unique occurrence of x).  It doesn't really matter -- it'll get
983         -- fixed up next pass.  And it happens for dictionary construction,
984         -- which mentions the wrapper constructor to start with.
985         simplValArg arg_ty is_strict val_arg se cont_ty         $ \ arg' ->
986         
987         if exprIsTrivial arg' then
988              thing_inside arg'
989         else
990         newId SLIT("a") (exprType arg')         $ \ arg_id ->
991         addNonRecBind arg_id arg'               $
992         thing_inside (Var arg_id)
993 \end{code}                 
994
995
996 %************************************************************************
997 %*                                                                      *
998 \subsection{Decisions about inlining}
999 %*                                                                      *
1000 %************************************************************************
1001
1002 NB: At one time I tried not pre/post-inlining top-level things,
1003 even if they occur exactly once.  Reason: 
1004         (a) some might appear as a function argument, so we simply
1005                 replace static allocation with dynamic allocation:
1006                    l = <...>
1007                    x = f l
1008         becomes
1009                    x = f <...>
1010
1011         (b) some top level things might be black listed
1012
1013 HOWEVER, I found that some useful foldr/build fusion was lost (most
1014 notably in spectral/hartel/parstof) because the foldr didn't see the build.
1015
1016 Doing the dynamic allocation isn't a big deal, in fact, but losing the
1017 fusion can be.
1018
1019 \begin{code}
1020 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
1021         -- Examines a bndr to see if it is used just once in a 
1022         -- completely safe way, so that it is safe to discard the binding
1023         -- inline its RHS at the (unique) usage site, REGARDLESS of how
1024         -- big the RHS might be.  If this is the case we don't simplify
1025         -- the RHS first, but just inline it un-simplified.
1026         --
1027         -- This is much better than first simplifying a perhaps-huge RHS
1028         -- and then inlining and re-simplifying it.
1029         --
1030         -- NB: we don't even look at the RHS to see if it's trivial
1031         -- We might have
1032         --                      x = y
1033         -- where x is used many times, but this is the unique occurrence
1034         -- of y.  We should NOT inline x at all its uses, because then
1035         -- we'd do the same for y -- aargh!  So we must base this
1036         -- pre-rhs-simplification decision solely on x's occurrences, not
1037         -- on its rhs.
1038         -- 
1039         -- Evne RHSs labelled InlineMe aren't caught here, because
1040         -- there might be no benefit from inlining at the call site.
1041
1042 preInlineUnconditionally black_listed bndr
1043   | black_listed || opt_SimplNoPreInlining = False
1044   | otherwise = case idOccInfo bndr of
1045                   OneOcc in_lam once -> not in_lam && once
1046                         -- Not inside a lambda, one occurrence ==> safe!
1047                   other              -> False
1048 \end{code}
1049
1050
1051
1052 %************************************************************************
1053 %*                                                                      *
1054 \subsection{The main rebuilder}
1055 %*                                                                      *
1056 %************************************************************************
1057
1058 \begin{code}
1059 -------------------------------------------------------------------
1060 -- Finish rebuilding
1061 rebuild_done expr = returnOutStuff expr
1062
1063 ---------------------------------------------------------
1064 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1065
1066 --      Stop continuation
1067 rebuild expr (Stop _ _) = rebuild_done expr
1068
1069 --      ArgOf continuation
1070 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1071
1072 --      ApplyTo continuation
1073 rebuild expr cont@(ApplyTo _ arg se cont')
1074   = setSubstEnv se (simplExpr arg)      `thenSmpl` \ arg' ->
1075     rebuild (App expr arg') cont'
1076
1077 --      Coerce continuation
1078 rebuild expr (CoerceIt to_ty cont)
1079   = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1080
1081 --      Inline continuation
1082 rebuild expr (InlinePlease cont)
1083   = rebuild (Note InlineCall expr) cont
1084
1085 rebuild scrut (Select _ bndr alts se cont)
1086   = rebuild_case scrut bndr alts se cont
1087 \end{code}
1088
1089 Case elimination [see the code above]
1090 ~~~~~~~~~~~~~~~~
1091 Start with a simple situation:
1092
1093         case x# of      ===>   e[x#/y#]
1094           y# -> e
1095
1096 (when x#, y# are of primitive type, of course).  We can't (in general)
1097 do this for algebraic cases, because we might turn bottom into
1098 non-bottom!
1099
1100 Actually, we generalise this idea to look for a case where we're
1101 scrutinising a variable, and we know that only the default case can
1102 match.  For example:
1103 \begin{verbatim}
1104         case x of
1105           0#    -> ...
1106           other -> ...(case x of
1107                          0#    -> ...
1108                          other -> ...) ...
1109 \end{code}
1110 Here the inner case can be eliminated.  This really only shows up in
1111 eliminating error-checking code.
1112
1113 We also make sure that we deal with this very common case:
1114
1115         case e of 
1116           x -> ...x...
1117
1118 Here we are using the case as a strict let; if x is used only once
1119 then we want to inline it.  We have to be careful that this doesn't 
1120 make the program terminate when it would have diverged before, so we
1121 check that 
1122         - x is used strictly, or
1123         - e is already evaluated (it may so if e is a variable)
1124
1125 Lastly, we generalise the transformation to handle this:
1126
1127         case e of       ===> r
1128            True  -> r
1129            False -> r
1130
1131 We only do this for very cheaply compared r's (constructors, literals
1132 and variables).  If pedantic bottoms is on, we only do it when the
1133 scrutinee is a PrimOp which can't fail.
1134
1135 We do it *here*, looking at un-simplified alternatives, because we
1136 have to check that r doesn't mention the variables bound by the
1137 pattern in each alternative, so the binder-info is rather useful.
1138
1139 So the case-elimination algorithm is:
1140
1141         1. Eliminate alternatives which can't match
1142
1143         2. Check whether all the remaining alternatives
1144                 (a) do not mention in their rhs any of the variables bound in their pattern
1145            and  (b) have equal rhss
1146
1147         3. Check we can safely ditch the case:
1148                    * PedanticBottoms is off,
1149                 or * the scrutinee is an already-evaluated variable
1150                 or * the scrutinee is a primop which is ok for speculation
1151                         -- ie we want to preserve divide-by-zero errors, and
1152                         -- calls to error itself!
1153
1154                 or * [Prim cases] the scrutinee is a primitive variable
1155
1156                 or * [Alg cases] the scrutinee is a variable and
1157                      either * the rhs is the same variable
1158                         (eg case x of C a b -> x  ===>   x)
1159                      or     * there is only one alternative, the default alternative,
1160                                 and the binder is used strictly in its scope.
1161                                 [NB this is helped by the "use default binder where
1162                                  possible" transformation; see below.]
1163
1164
1165 If so, then we can replace the case with one of the rhss.
1166
1167
1168 Blob of helper functions for the "case-of-something-else" situation.
1169
1170 \begin{code}
1171 ---------------------------------------------------------
1172 --      Eliminate the case if possible
1173
1174 rebuild_case scrut bndr alts se cont
1175   | maybeToBool maybe_con_app
1176   = knownCon scrut (DataAlt con) args bndr alts se cont
1177
1178   | canEliminateCase scrut bndr alts
1179   = tick (CaseElim bndr)                        `thenSmpl_` (
1180     setSubstEnv se                              $                       
1181     simplBinder bndr                            $ \ bndr' ->
1182         -- Remember to bind the case binder!
1183     completeBinding bndr bndr' False False scrut        $
1184     simplExprF (head (rhssOfAlts alts)) cont)
1185
1186   | otherwise
1187   = complete_case scrut bndr alts se cont
1188
1189   where
1190     maybe_con_app    = exprIsConApp_maybe scrut
1191     Just (con, args) = maybe_con_app
1192
1193         -- See if we can get rid of the case altogether
1194         -- See the extensive notes on case-elimination above
1195 canEliminateCase scrut bndr alts
1196   =     -- Check that the RHSs are all the same, and
1197         -- don't use the binders in the alternatives
1198         -- This test succeeds rapidly in the common case of
1199         -- a single DEFAULT alternative
1200     all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1201
1202         -- Check that the scrutinee can be let-bound instead of case-bound
1203     && (   exprOkForSpeculation scrut
1204                 -- OK not to evaluate it
1205                 -- This includes things like (==# a# b#)::Bool
1206                 -- so that we simplify 
1207                 --      case ==# a# b# of { True -> x; False -> x }
1208                 -- to just
1209                 --      x
1210                 -- This particular example shows up in default methods for
1211                 -- comparision operations (e.g. in (>=) for Int.Int32)
1212         || exprIsValue scrut                    -- It's already evaluated
1213         || var_demanded_later scrut             -- It'll be demanded later
1214
1215 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1216 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1217 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1218 --      its argument:  case x of { y -> dataToTag# y }
1219 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1220 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1221 --      other problems
1222        )
1223
1224   where
1225     (rhs1:other_rhss)            = rhssOfAlts alts
1226     binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1227
1228     var_demanded_later (Var v) = isStrict (idDemandInfo bndr)   -- It's going to be evaluated later
1229     var_demanded_later other   = False
1230
1231
1232 ---------------------------------------------------------
1233 --      Case of something else
1234
1235 complete_case scrut case_bndr alts se cont
1236   =     -- Prepare case alternatives
1237     prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1238                     impossible_cons alts                `thenSmpl` \ better_alts ->
1239     
1240         -- Set the new subst-env in place (before dealing with the case binder)
1241     setSubstEnv se                              $
1242
1243         -- Deal with the case binder, and prepare the continuation;
1244         -- The new subst_env is in place
1245     prepareCaseCont better_alts cont            $ \ cont' ->
1246         
1247
1248         -- Deal with variable scrutinee
1249     (   
1250         getSwitchChecker                                `thenSmpl` \ chkr ->
1251         simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1252                         scrut case_bndr                 $ \ case_bndr' zap_occ_info ->
1253
1254         -- Deal with the case alternatives
1255         simplAlts zap_occ_info impossible_cons
1256                   case_bndr' better_alts cont'  `thenSmpl` \ alts' ->
1257
1258         mkCase scrut case_bndr' alts'
1259     )                                           `thenSmpl` \ case_expr ->
1260
1261         -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1262         -- over the rebuild_done; rebuild_done returns the in-scope set, and
1263         -- that should not include these chaps!
1264     rebuild_done case_expr      
1265   where
1266     impossible_cons = case scrut of
1267                             Var v -> otherCons (idUnfolding v)
1268                             other -> []
1269
1270
1271 knownCon :: OutExpr -> AltCon -> [OutExpr]
1272          -> InId -> [InAlt] -> SubstEnv -> SimplCont
1273          -> SimplM OutExprStuff
1274
1275 knownCon expr con args bndr alts se cont
1276   =     -- Arguments should be atomic;
1277         -- yell if not
1278     WARN( not (all exprIsTrivial args), 
1279           text "knownCon" <+> ppr expr )
1280     tick (KnownBranch bndr)     `thenSmpl_`
1281     setSubstEnv se              (
1282     simplBinder bndr            $ \ bndr' ->
1283     completeBinding bndr bndr' False False expr $
1284         -- Don't use completeBeta here.  The expr might be
1285         -- an unboxed literal, like 3, or a variable
1286         -- whose unfolding is an unboxed literal... and
1287         -- completeBeta will just construct another case
1288                                         -- expression!
1289     case findAlt con alts of
1290         (DEFAULT, bs, rhs)     -> ASSERT( null bs )
1291                                   simplExprF rhs cont
1292
1293         (LitAlt lit, bs, rhs) ->  ASSERT( null bs )
1294                                   simplExprF rhs cont
1295
1296         (DataAlt dc, bs, rhs)  -> ASSERT( length bs == length real_args )
1297                                   extendSubstList bs (map mk real_args) $
1298                                   simplExprF rhs cont
1299                                where
1300                                   real_args    = drop (dataConNumInstArgs dc) args
1301                                   mk (Type ty) = DoneTy ty
1302                                   mk other     = DoneEx other
1303     )
1304 \end{code}
1305
1306 \begin{code}
1307 prepareCaseCont :: [InAlt] -> SimplCont
1308                 -> (SimplCont -> SimplM (OutStuff a))
1309                 -> SimplM (OutStuff a)
1310         -- Polymorphic recursion here!
1311
1312 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1313 prepareCaseCont alts  cont thing_inside = simplType (coreAltsType alts)         `thenSmpl` \ alts_ty ->
1314                                           mkDupableCont alts_ty cont thing_inside
1315         -- At one time I passed in the un-simplified type, and simplified
1316         -- it only if we needed to construct a join binder, but that    
1317         -- didn't work because we have to decompse function types
1318         -- (using funResultTy) in mkDupableCont.
1319 \end{code}
1320
1321 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1322 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1323 way, there's a chance that v will now only be used once, and hence
1324 inlined.
1325
1326 There is a time we *don't* want to do that, namely when
1327 -fno-case-of-case is on.  This happens in the first simplifier pass,
1328 and enhances full laziness.  Here's the bad case:
1329         f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1330 If we eliminate the inner case, we trap it inside the I# v -> arm,
1331 which might prevent some full laziness happening.  I've seen this
1332 in action in spectral/cichelli/Prog.hs:
1333          [(m,n) | m <- [1..max], n <- [1..max]]
1334 Hence the no_case_of_case argument
1335
1336
1337 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1338 in the case binder, because the case-binder now effectively occurs
1339 whenever v does.  AND we have to do the same for the pattern-bound
1340 variables!  Example:
1341
1342         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1343
1344 Here, b and p are dead.  But when we move the argment inside the first
1345 case RHS, and eliminate the second case, we get
1346
1347         case x or { (a,b) -> a b }
1348
1349 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1350 happened.  Hence the zap_occ_info function returned by simplCaseBinder
1351
1352 \begin{code}
1353 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1354   | not no_case_of_case
1355   = simplBinder (zap case_bndr)                                 $ \ case_bndr' ->
1356     modifyInScope v case_bndr'                                  $
1357         -- We could extend the substitution instead, but it would be
1358         -- a hack because then the substitution wouldn't be idempotent
1359         -- any more (v is an OutId).  And this just just as well.
1360     thing_inside case_bndr' zap
1361   where
1362     zap b = b `setIdOccInfo` NoOccInfo
1363             
1364 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1365   = simplBinder case_bndr               $ \ case_bndr' ->
1366     thing_inside case_bndr' (\ bndr -> bndr)    -- NoOp on bndr
1367 \end{code}
1368
1369 prepareCaseAlts does two things:
1370
1371 1.  Remove impossible alternatives
1372
1373 2.  If the DEFAULT alternative can match only one possible constructor,
1374     then make that constructor explicit.
1375     e.g.
1376         case e of x { DEFAULT -> rhs }
1377      ===>
1378         case e of x { (a,b) -> rhs }
1379     where the type is a single constructor type.  This gives better code
1380     when rhs also scrutinises x or e.
1381
1382 \begin{code}
1383 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1384   | isDataTyCon tycon
1385   = case (findDefault filtered_alts, missing_cons) of
1386
1387         ((alts_no_deflt, Just rhs), [data_con])         -- Just one missing constructor!
1388                 -> tick (FillInCaseDefault bndr)        `thenSmpl_`
1389                    let
1390                         (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1391                    in
1392                    getUniquesSmpl                       `thenSmpl` \ tv_uniqs ->
1393                    let
1394                         ex_tyvars' = zipWith mk tv_uniqs ex_tyvars
1395                         mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1396                         arg_tys    = dataConArgTys data_con
1397                                                    (inst_tys ++ mkTyVarTys ex_tyvars')
1398                    in
1399                    newIds SLIT("a") arg_tys             $ \ bndrs ->
1400                    returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1401
1402         other -> returnSmpl filtered_alts
1403   where
1404         -- Filter out alternatives that can't possibly match
1405     filtered_alts = case scrut_cons of
1406                         []    -> alts
1407                         other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1408
1409     missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon, 
1410                                not (data_con `elem` handled_data_cons)]
1411     handled_data_cons = [data_con | DataAlt data_con         <- scrut_cons] ++
1412                         [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1413
1414 -- The default case
1415 prepareCaseAlts _ _ scrut_cons alts
1416   = returnSmpl alts                     -- Functions
1417
1418
1419 ----------------------
1420 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1421   = mapSmpl simpl_alt alts
1422   where
1423     inst_tys' = tyConAppArgs (idType case_bndr')
1424
1425         -- handled_cons is all the constructors that are dealt
1426         -- with, either by being impossible, or by there being an alternative
1427     handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1428
1429     simpl_alt (DEFAULT, _, rhs)
1430         =       -- In the default case we record the constructors that the
1431                 -- case-binder *can't* be.
1432                 -- We take advantage of any OtherCon info in the case scrutinee
1433           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons)        $ 
1434           simplExprC rhs cont'                                                  `thenSmpl` \ rhs' ->
1435           returnSmpl (DEFAULT, [], rhs')
1436
1437     simpl_alt (con, vs, rhs)
1438         =       -- Deal with the pattern-bound variables
1439                 -- Mark the ones that are in ! positions in the data constructor
1440                 -- as certainly-evaluated.
1441                 -- NB: it happens that simplBinders does *not* erase the OtherCon
1442                 --     form of unfolding, so it's ok to add this info before 
1443                 --     doing simplBinders
1444           simplBinders (add_evals con vs)                                       $ \ vs' ->
1445
1446                 -- Bind the case-binder to (con args)
1447           let
1448                 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1449           in
1450           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding)      $
1451           simplExprC rhs cont'          `thenSmpl` \ rhs' ->
1452           returnSmpl (con, vs', rhs')
1453
1454
1455         -- add_evals records the evaluated-ness of the bound variables of
1456         -- a case pattern.  This is *important*.  Consider
1457         --      data T = T !Int !Int
1458         --
1459         --      case x of { T a b -> T (a+1) b }
1460         --
1461         -- We really must record that b is already evaluated so that we don't
1462         -- go and re-evaluate it when constructing the result.
1463
1464     add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1465     add_evals other_con    vs = vs
1466
1467     cat_evals [] [] = []
1468     cat_evals (v:vs) (str:strs)
1469         | isTyVar v    = v                                   : cat_evals vs (str:strs)
1470         | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1471         | otherwise    = v'                                  : cat_evals vs strs
1472         where
1473           v' = zap_occ_info v
1474 \end{code}
1475
1476
1477 %************************************************************************
1478 %*                                                                      *
1479 \subsection{Duplicating continuations}
1480 %*                                                                      *
1481 %************************************************************************
1482
1483 \begin{code}
1484 mkDupableCont :: OutType                -- Type of the thing to be given to the continuation
1485               -> SimplCont 
1486               -> (SimplCont -> SimplM (OutStuff a))
1487               -> SimplM (OutStuff a)
1488 mkDupableCont ty cont thing_inside 
1489   | contIsDupable cont
1490   = thing_inside cont
1491
1492 mkDupableCont _ (CoerceIt ty cont) thing_inside
1493   = mkDupableCont ty cont               $ \ cont' ->
1494     thing_inside (CoerceIt ty cont')
1495
1496 mkDupableCont ty (InlinePlease cont) thing_inside
1497   = mkDupableCont ty cont               $ \ cont' ->
1498     thing_inside (InlinePlease cont')
1499
1500 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1501   =     -- Build the RHS of the join point
1502     newId SLIT("a") join_arg_ty                         ( \ arg_id ->
1503         cont_fn (Var arg_id)                            `thenSmpl` \ (floats, (_, rhs)) ->
1504         returnSmpl (Lam (setOneShotLambda arg_id) (wrapFloats floats rhs))
1505     )                                                   `thenSmpl` \ join_rhs ->
1506    
1507         -- Build the join Id and continuation
1508         -- We give it a "$j" name just so that for later amusement
1509         -- we can identify any join points that don't end up as let-no-escapes
1510         -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1511     newId SLIT("$j") (mkFunTy join_arg_ty cont_ty)      $ \ join_id ->
1512     let
1513         new_cont = ArgOf OkToDup cont_ty
1514                          (\arg' -> rebuild_done (App (Var join_id) arg'))
1515     in
1516
1517     tick (CaseOfCase join_id)                                           `thenSmpl_`
1518         -- Want to tick here so that we go round again,
1519         -- and maybe copy or inline the code;
1520         -- not strictly CaseOf Case
1521     addLetBind (NonRec join_id join_rhs)        $
1522     thing_inside new_cont
1523
1524 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1525   = mkDupableCont (funResultTy ty) cont                 $ \ cont' ->
1526     setSubstEnv se (simplExpr arg)                      `thenSmpl` \ arg' ->
1527     if exprIsDupable arg' then
1528         thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1529     else
1530     newId SLIT("a") (exprType arg')                     $ \ bndr ->
1531
1532     tick (CaseOfCase bndr)                              `thenSmpl_`
1533         -- Want to tick here so that we go round again,
1534         -- and maybe copy or inline the code;
1535         -- not strictly CaseOf Case
1536
1537      addLetBind (NonRec bndr arg')              $
1538         -- But what if the arg should be case-bound?  We can't use
1539         -- addNonRecBind here because its type is too specific.
1540         -- This has been this way for a long time, so I'll leave it,
1541         -- but I can't convince myself that it's right.
1542
1543      thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1544
1545
1546 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1547   = tick (CaseOfCase case_bndr)                                         `thenSmpl_`
1548     setSubstEnv se (
1549         simplBinder case_bndr                                           $ \ case_bndr' ->
1550         prepareCaseCont alts cont                                       $ \ cont' ->
1551         mkDupableAlts case_bndr case_bndr' cont' alts                   $ \ alts' ->
1552         returnOutStuff alts'
1553     )                                   `thenSmpl` \ (alt_binds, (in_scope, alts')) ->
1554
1555     addFloats alt_binds in_scope                $
1556
1557         -- NB that the new alternatives, alts', are still InAlts, using the original
1558         -- binders.  That means we can keep the case_bndr intact. This is important
1559         -- because another case-of-case might strike, and so we want to keep the
1560         -- info that the case_bndr is dead (if it is, which is often the case).
1561         -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1562         -- case in I/O rich code.  We aren't allowed a lambda bound
1563         -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1564     thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1565
1566 mkDupableAlts :: InId -> OutId -> SimplCont -> [InAlt] 
1567              -> ([InAlt] -> SimplM (OutStuff a))
1568              -> SimplM (OutStuff a)
1569 mkDupableAlts case_bndr case_bndr' cont [] thing_inside
1570   = thing_inside []
1571 mkDupableAlts case_bndr case_bndr' cont (alt:alts) thing_inside
1572   = mkDupableAlt  case_bndr case_bndr' cont alt         $ \ alt' -> 
1573     mkDupableAlts case_bndr case_bndr' cont alts        $ \ alts' ->
1574     thing_inside (alt' : alts')
1575
1576 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs) thing_inside
1577   = simplBinders bndrs                                  $ \ bndrs' ->
1578     simplExprC rhs cont                                 `thenSmpl` \ rhs' ->
1579
1580     if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1581         -- It is worth checking for a small RHS because otherwise we
1582         -- get extra let bindings that may cause an extra iteration of the simplifier to
1583         -- inline back in place.  Quite often the rhs is just a variable or constructor.
1584         -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1585         -- iterations because the version with the let bindings looked big, and so wasn't
1586         -- inlined, but after the join points had been inlined it looked smaller, and so
1587         -- was inlined.
1588         --
1589         -- But since the continuation is absorbed into the rhs, we only do this
1590         -- for a Stop continuation.
1591         --
1592         -- NB: we have to check the size of rhs', not rhs. 
1593         -- Duplicating a small InAlt might invalidate occurrence information
1594         -- However, if it *is* dupable, we return the *un* simplified alternative,
1595         -- because otherwise we'd need to pair it up with an empty subst-env.
1596         -- (Remember we must zap the subst-env before re-simplifying something).
1597         -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1598         thing_inside alt
1599
1600     else
1601     let
1602         rhs_ty' = exprType rhs'
1603         (used_bndrs, used_bndrs')
1604            = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr  : bndrs)
1605                                                 (case_bndr' : bndrs'),
1606                          not (isDeadBinder bndr)]
1607                 -- The new binders have lost their occurrence info,
1608                 -- so we have to extract it from the old ones
1609     in
1610     ( if null used_bndrs' 
1611         -- If we try to lift a primitive-typed something out
1612         -- for let-binding-purposes, we will *caseify* it (!),
1613         -- with potentially-disastrous strictness results.  So
1614         -- instead we turn it into a function: \v -> e
1615         -- where v::State# RealWorld#.  The value passed to this function
1616         -- is realworld#, which generates (almost) no code.
1617
1618         -- There's a slight infelicity here: we pass the overall 
1619         -- case_bndr to all the join points if it's used in *any* RHS,
1620         -- because we don't know its usage in each RHS separately
1621
1622         -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1623         -- we make the join point into a function whenever used_bndrs'
1624         -- is empty.  This makes the join-point more CPR friendly. 
1625         -- Consider:    let j = if .. then I# 3 else I# 4
1626         --              in case .. of { A -> j; B -> j; C -> ... }
1627         --
1628         -- Now CPR doesn't w/w j because it's a thunk, so
1629         -- that means that the enclosing function can't w/w either,
1630         -- which is a lose.  Here's the example that happened in practice:
1631         --      kgmod :: Int -> Int -> Int
1632         --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1633         --                  then 78
1634         --                  else 5
1635         --
1636         -- I have seen a case alternative like this:
1637         --      True -> \v -> ...
1638         -- It's a bit silly to add the realWorld dummy arg in this case, making
1639         --      $j = \s v -> ...
1640         --         True -> $j s
1641         -- (the \v alone is enough to make CPR happy) but I think it's rare
1642
1643         then newId SLIT("w") realWorldStatePrimTy  $ \ rw_id ->
1644              returnSmpl ([rw_id], [Var realWorldPrimId])
1645         else 
1646              returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1647     )
1648         `thenSmpl` \ (final_bndrs', final_args) ->
1649
1650         -- See comment about "$j" name above
1651     newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs')      $ \ join_bndr ->
1652         -- Notice the funky mkPiType.  If the contructor has existentials
1653         -- it's possible that the join point will be abstracted over
1654         -- type varaibles as well as term variables.
1655         --  Example:  Suppose we have
1656         --      data T = forall t.  C [t]
1657         --  Then faced with
1658         --      case (case e of ...) of
1659         --          C t xs::[t] -> rhs
1660         --  We get the join point
1661         --      let j :: forall t. [t] -> ...
1662         --          j = /\t \xs::[t] -> rhs
1663         --      in
1664         --      case (case e of ...) of
1665         --          C t xs::[t] -> j t xs
1666
1667     let 
1668         -- We make the lambdas into one-shot-lambdas.  The
1669         -- join point is sure to be applied at most once, and doing so
1670         -- prevents the body of the join point being floated out by
1671         -- the full laziness pass
1672         really_final_bndrs = map one_shot final_bndrs'
1673         one_shot v | isId v    = setOneShotLambda v
1674                    | otherwise = v
1675     in
1676     addLetBind (NonRec join_bndr (mkLams really_final_bndrs rhs'))      $
1677     thing_inside (con, bndrs, mkApps (Var join_bndr) final_args)
1678 \end{code}