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