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