[project @ 2000-10-19 10:06:46 by sewardj]
[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                           ArityInfo, setArityInfo, unknownArity,
33                           setUnfoldingInfo,
34                           occInfo
35                         )
36 import Demand           ( 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, exprIsConApp_maybe,
46                           exprType, coreAltsType, exprIsValue, idAppIsCheap,
47                           exprOkForSpeculation, etaReduceExpr,
48                           mkCoerce, mkSCC, mkInlineMe, mkAltExpr
49                         )
50 import Rules            ( lookupRule )
51 import CostCentre       ( currentCCS )
52 import Type             ( mkTyVarTys, isUnLiftedType, seqType,
53                           mkFunTy, splitFunTy, splitTyConApp_maybe, 
54                           funResultTy
55                         )
56 import Subst            ( mkSubst, substTy, substExpr,
57                           isInScope, lookupIdSubst, substIdInfo
58                         )
59 import TyCon            ( isDataTyCon, tyConDataConsIfAvailable )
60 import TysPrim          ( realWorldStatePrimTy )
61 import PrelInfo         ( realWorldPrimId )
62 import Maybes           ( maybeToBool )
63 import Util             ( zipWithEqual )
64 import Outputable
65 \end{code}
66
67
68 The guts of the simplifier is in this module, but the driver
69 loop for the simplifier is in SimplCore.lhs.
70
71
72 -----------------------------------------
73         *** IMPORTANT NOTE ***
74 -----------------------------------------
75 The simplifier used to guarantee that the output had no shadowing, but
76 it does not do so any more.   (Actually, it never did!)  The reason is
77 documented with simplifyArgs.
78
79
80
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection{Bindings}
85 %*                                                                      *
86 %************************************************************************
87
88 \begin{code}
89 simplTopBinds :: [InBind] -> SimplM [OutBind]
90
91 simplTopBinds binds
92   =     -- Put all the top-level binders into scope at the start
93         -- so that if a transformation rule has unexpectedly brought
94         -- anything into scope, then we don't get a complaint about that.
95         -- It's rather as if the top-level binders were imported.
96     simplIds (bindersOfBinds binds)     $ \ bndrs' -> 
97     simpl_binds binds bndrs'            `thenSmpl` \ (binds', _) ->
98     freeTick SimplifierDone             `thenSmpl_`
99     returnSmpl binds'
100   where
101
102         -- We need to track the zapped top-level binders, because
103         -- they should have their fragile IdInfo zapped (notably occurrence info)
104     simpl_binds []                        bs     = ASSERT( null bs ) returnSmpl ([], panic "simplTopBinds corner")
105     simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr  b rhs       (simpl_binds binds bs)
106     simpl_binds (Rec pairs       : binds) bs     = simplRecBind  True pairs (take n bs) (simpl_binds binds (drop n bs))
107                                                  where 
108                                                    n = length pairs
109
110 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
111              -> SimplM (OutStuff a) -> SimplM (OutStuff a)
112 simplRecBind top_lvl pairs bndrs' thing_inside
113   = go pairs bndrs'             `thenSmpl` \ (binds', (binds'', res)) ->
114     returnSmpl (Rec (flattenBinds binds') : binds'', res)
115   where
116     go [] _ = thing_inside      `thenSmpl` \ stuff ->
117               returnSmpl ([], stuff)
118         
119     go ((bndr, rhs) : pairs) (bndr' : bndrs')
120         = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
121                 -- Don't float unboxed bindings out,
122                 -- because we can't "rec" them
123 \end{code}
124
125
126 %************************************************************************
127 %*                                                                      *
128 \subsection[Simplify-simplExpr]{The main function: simplExpr}
129 %*                                                                      *
130 %************************************************************************
131
132 The reason for this OutExprStuff stuff is that we want to float *after*
133 simplifying a RHS, not before.  If we do so naively we get quadratic
134 behaviour as things float out.
135
136 To see why it's important to do it after, consider this (real) example:
137
138         let t = f x
139         in fst t
140 ==>
141         let t = let a = e1
142                     b = e2
143                 in (a,b)
144         in fst t
145 ==>
146         let a = e1
147             b = e2
148             t = (a,b)
149         in
150         a       -- Can't inline a this round, cos it appears twice
151 ==>
152         e1
153
154 Each of the ==> steps is a round of simplification.  We'd save a
155 whole round if we float first.  This can cascade.  Consider
156
157         let f = g d
158         in \x -> ...f...
159 ==>
160         let f = let d1 = ..d.. in \y -> e
161         in \x -> ...f...
162 ==>
163         let d1 = ..d..
164         in \x -> ...(\y ->e)...
165
166 Only in this second round can the \y be applied, and it 
167 might do the same again.
168
169
170 \begin{code}
171 simplExpr :: CoreExpr -> SimplM CoreExpr
172 simplExpr expr = getSubst       `thenSmpl` \ subst ->
173                  simplExprC expr (mkStop (substTy subst (exprType expr)))
174         -- The type in the Stop continuation is usually not used
175         -- It's only needed when discarding continuations after finding
176         -- a function that returns bottom.
177         -- Hence the lazy substitution
178
179 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
180         -- Simplify an expression, given a continuation
181
182 simplExprC expr cont = simplExprF expr cont     `thenSmpl` \ (floats, (_, body)) ->
183                        returnSmpl (mkLets floats body)
184
185 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
186         -- Simplify an expression, returning floated binds
187
188 simplExprF (Var v) cont
189   = simplVar v cont
190
191 simplExprF (Lit lit) (Select _ bndr alts se cont)
192   = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
193
194 simplExprF (Lit lit) cont
195   = rebuild (Lit lit) cont
196
197 simplExprF (App fun arg) cont
198   = getSubstEnv         `thenSmpl` \ se ->
199     simplExprF fun (ApplyTo NoDup arg se cont)
200
201 simplExprF (Case scrut bndr alts) cont
202   = getSubstEnv                 `thenSmpl` \ subst_env ->
203     getSwitchChecker            `thenSmpl` \ chkr ->
204     if not (switchIsOn chkr NoCaseOfCase) then
205         -- Simplify the scrutinee with a Select continuation
206         simplExprF scrut (Select NoDup bndr alts subst_env cont)
207
208     else
209         -- If case-of-case is off, simply simplify the case expression
210         -- in a vanilla Stop context, and rebuild the result around it
211         simplExprC scrut (Select NoDup bndr alts subst_env 
212                                  (mkStop (contResultType cont)))        `thenSmpl` \ case_expr' ->
213         rebuild case_expr' cont
214
215
216 simplExprF (Let (Rec pairs) body) cont
217   = simplIds (map fst pairs)            $ \ bndrs' -> 
218         -- NB: bndrs' don't have unfoldings or spec-envs
219         -- We add them as we go down, using simplPrags
220
221     simplRecBind False pairs bndrs' (simplExprF body cont)
222
223 simplExprF expr@(Lam _ _) cont = simplLam expr cont
224
225 simplExprF (Type ty) cont
226   = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
227     simplType ty        `thenSmpl` \ ty' ->
228     rebuild (Type ty') cont
229
230 -- Comments about the Coerce case
231 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
232 -- It's worth checking for a coerce in the continuation,
233 -- in case we can cancel them.  For example, in the initial form of a worker
234 -- we may find  (coerce T (coerce S (\x.e))) y
235 -- and we'd like it to simplify to e[y/x] in one round of simplification
236
237 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
238   = simplType from              `thenSmpl` \ from' ->
239     if outer_to == from' then
240         -- The coerces cancel out
241         simplExprF e cont
242     else
243         -- They don't cancel, but the inner one is redundant
244         simplExprF e (CoerceIt outer_to cont)
245
246 simplExprF (Note (Coerce to from) e) cont
247   = simplType to                `thenSmpl` \ to' ->
248     simplExprF e (CoerceIt to' cont)
249
250 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
251 -- inlining.  All other CCCSs are mapped to currentCCS.
252 simplExprF (Note (SCC cc) e) cont
253   = setEnclosingCC currentCCS $
254     simplExpr e         `thenSmpl` \ e ->
255     rebuild (mkSCC cc e) cont
256
257 simplExprF (Note InlineCall e) cont
258   = simplExprF e (InlinePlease cont)
259
260 -- Comments about the InlineMe case 
261 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
262 -- Don't inline in the RHS of something that has an
263 -- inline pragma.  But be careful that the InScopeEnv that
264 -- we return does still have inlinings on!
265 -- 
266 -- It really is important to switch off inlinings.  This function
267 -- may be inlinined in other modules, so we don't want to remove
268 -- (by inlining) calls to functions that have specialisations, or
269 -- that may have transformation rules in an importing scope.
270 -- E.g.         {-# INLINE f #-}
271 --              f x = ...g...
272 -- and suppose that g is strict *and* has specialisations.
273 -- If we inline g's wrapper, we deny f the chance of getting
274 -- the specialised version of g when f is inlined at some call site
275 -- (perhaps in some other module).
276
277 simplExprF (Note InlineMe e) cont
278   = case cont of
279         Stop _ _ ->     -- Totally boring continuation
280                         -- Don't inline inside an INLINE expression
281                   setBlackList noInlineBlackList (simplExpr e)  `thenSmpl` \ e' ->
282                   rebuild (mkInlineMe e') cont
283
284         other  ->       -- Dissolve the InlineMe note if there's
285                         -- an interesting context of any kind to combine with
286                         -- (even a type application -- anything except Stop)
287                   simplExprF e cont     
288
289 -- A non-recursive let is dealt with by simplBeta
290 simplExprF (Let (NonRec bndr rhs) body) cont
291   = getSubstEnv                 `thenSmpl` \ se ->
292     simplBeta bndr rhs se (contResultType cont) $
293     simplExprF body cont
294 \end{code}
295
296
297 ---------------------------------
298
299 \begin{code}
300 simplLam fun cont
301   = go fun cont
302   where
303     zap_it  = mkLamBndrZapper fun cont
304     cont_ty = contResultType cont
305
306         -- Type-beta reduction
307     go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
308       = ASSERT( isTyVar bndr )
309         tick (BetaReduction bndr)       `thenSmpl_`
310         simplTyArg ty_arg arg_se        `thenSmpl` \ ty_arg' ->
311         extendSubst bndr (DoneTy ty_arg')
312         (go body body_cont)
313
314         -- Ordinary beta reduction
315     go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
316       = tick (BetaReduction bndr)                       `thenSmpl_`
317         simplBeta zapped_bndr arg arg_se cont_ty
318         (go body body_cont)
319       where
320         zapped_bndr = zap_it bndr
321
322         -- Not enough args
323     go lam@(Lam _ _) cont = completeLam [] lam cont
324
325         -- Exactly enough args
326     go expr cont = simplExprF expr cont
327
328 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
329 -- continuation, so there are real lambdas left to put in the result
330
331 -- We try for eta reduction here, but *only* if we get all the 
332 -- way to an exprIsTrivial expression.    
333 -- We don't want to remove extra lambdas unless we are going 
334 -- to avoid allocating this thing altogether
335
336 completeLam rev_bndrs (Lam bndr body) cont
337   = simplBinder bndr                    $ \ bndr' ->
338     completeLam (bndr':rev_bndrs) body cont
339
340 completeLam rev_bndrs body cont
341   = simplExpr body                      `thenSmpl` \ body' ->
342     case try_eta body' of
343         Just etad_lam -> tick (EtaReduction (head rev_bndrs))   `thenSmpl_`
344                          rebuild etad_lam cont
345
346         Nothing       -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
347   where
348         -- We don't use CoreUtils.etaReduceExpr, because we can be more
349         -- efficient here: (a) we already have the binders, (b) we can do
350         -- the triviality test before computing the free vars
351     try_eta body | not opt_SimplDoEtaReduction = Nothing
352                  | otherwise                   = go rev_bndrs body
353
354     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
355     go []       body          | ok_body body = Just body        -- Success!
356     go _        _                            = Nothing          -- Failure!
357
358     ok_body body = exprIsTrivial body && not (any (`elemVarSet` exprFreeVars body) rev_bndrs)
359     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
360
361 mkLamBndrZapper :: CoreExpr     -- Function
362                 -> SimplCont    -- The context
363                 -> Id -> Id     -- Use this to zap the binders
364 mkLamBndrZapper fun cont
365   | n_args >= n_params fun = \b -> b            -- Enough args
366   | otherwise              = \b -> zapLamIdInfo b
367   where
368         -- NB: we count all the args incl type args
369         -- so we must count all the binders (incl type lambdas)
370     n_args = countArgs cont
371
372     n_params (Note _ e) = n_params e
373     n_params (Lam b e)  = 1 + n_params e
374     n_params other      = 0::Int
375 \end{code}
376
377
378 ---------------------------------
379 \begin{code}
380 simplType :: InType -> SimplM OutType
381 simplType ty
382   = getSubst    `thenSmpl` \ subst ->
383     let
384         new_ty = substTy subst ty
385     in
386     seqType new_ty `seq`  
387     returnSmpl new_ty
388 \end{code}
389
390
391 %************************************************************************
392 %*                                                                      *
393 \subsection{Binding}
394 %*                                                                      *
395 %************************************************************************
396
397 @simplBeta@ is used for non-recursive lets in expressions, 
398 as well as true beta reduction.
399
400 Very similar to @simplLazyBind@, but not quite the same.
401
402 \begin{code}
403 simplBeta :: InId                       -- Binder
404           -> InExpr -> SubstEnv         -- Arg, with its subst-env
405           -> OutType                    -- Type of thing computed by the context
406           -> SimplM OutExprStuff        -- The body
407           -> SimplM OutExprStuff
408 #ifdef DEBUG
409 simplBeta bndr rhs rhs_se cont_ty thing_inside
410   | isTyVar bndr
411   = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
412 #endif
413
414 simplBeta bndr rhs rhs_se cont_ty thing_inside
415   | preInlineUnconditionally False {- not black listed -} bndr
416   = tick (PreInlineUnconditionally bndr)                `thenSmpl_`
417     extendSubst bndr (ContEx rhs_se rhs) thing_inside
418
419   | otherwise
420   =     -- Simplify the RHS
421     simplBinder bndr                                    $ \ bndr' ->
422     let
423         bndr_ty'  = idType bndr'
424         is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
425     in
426     simplValArg bndr_ty' is_strict rhs rhs_se cont_ty   $ \ rhs' ->
427
428         -- Now complete the binding and simplify the body
429     if needsCaseBinding bndr_ty' rhs' then
430         addCaseBind bndr' rhs' thing_inside
431     else
432         completeBinding bndr bndr' False False rhs' thing_inside
433 \end{code}
434
435
436 \begin{code}
437 simplTyArg :: InType -> SubstEnv -> SimplM OutType
438 simplTyArg ty_arg se
439   = getInScope          `thenSmpl` \ in_scope ->
440     let
441         ty_arg' = substTy (mkSubst in_scope se) ty_arg
442     in
443     seqType ty_arg'     `seq`
444     returnSmpl ty_arg'
445
446 simplValArg :: OutType          -- rhs_ty: Type of arg; used only occasionally
447             -> Bool             -- True <=> evaluate eagerly
448             -> InExpr -> SubstEnv
449             -> OutType          -- cont_ty: Type of thing computed by the context
450             -> (OutExpr -> SimplM OutExprStuff) 
451                                 -- Takes an expression of type rhs_ty, 
452                                 -- returns an expression of type cont_ty
453             -> SimplM OutExprStuff      -- An expression of type cont_ty
454
455 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
456   | is_strict
457   = getEnv                              `thenSmpl` \ env ->
458     setSubstEnv arg_se                          $
459     simplExprF arg (ArgOf NoDup cont_ty         $ \ rhs' ->
460     setAllExceptInScope env                     $
461     thing_inside rhs')
462
463   | otherwise
464   = simplRhs False {- Not top level -} 
465              True {- OK to float unboxed -}
466              arg_ty arg arg_se 
467              thing_inside
468 \end{code}
469
470
471 completeBinding
472         - deals only with Ids, not TyVars
473         - take an already-simplified RHS
474
475 It does *not* attempt to do let-to-case.  Why?  Because they are used for
476
477         - top-level bindings
478                 (when let-to-case is impossible) 
479
480         - many situations where the "rhs" is known to be a WHNF
481                 (so let-to-case is inappropriate).
482
483 \begin{code}
484 completeBinding :: InId                 -- Binder
485                 -> OutId                -- New binder
486                 -> Bool                 -- True <=> top level
487                 -> Bool                 -- True <=> black-listed; don't inline
488                 -> OutExpr              -- Simplified RHS
489                 -> SimplM (OutStuff a)  -- Thing inside
490                 -> SimplM (OutStuff a)
491
492 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
493   |  isDeadOcc occ_info         -- This happens; for example, the case_bndr during case of
494                                 -- known constructor:  case (a,b) of x { (p,q) -> ... }
495                                 -- Here x isn't mentioned in the RHS, so we don't want to
496                                 -- create the (dead) let-binding  let x = (a,b) in ...
497   =  thing_inside
498
499   | exprIsTrivial new_rhs
500         -- We're looking at a binding with a trivial RHS, so
501         -- perhaps we can discard it altogether!
502         --
503         -- NB: a loop breaker never has postInlineUnconditionally True
504         -- and non-loop-breakers only have *forward* references
505         -- Hence, it's safe to discard the binding
506         --      
507         -- NOTE: This isn't our last opportunity to inline.
508         -- We're at the binding site right now, and
509         -- we'll get another opportunity when we get to the ocurrence(s)
510
511         -- Note that we do this unconditional inlining only for trival RHSs.
512         -- Don't inline even WHNFs inside lambdas; doing so may
513         -- simply increase allocation when the function is called
514         -- This isn't the last chance; see NOTE above.
515         --
516         -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
517         -- Why?  Because we don't even want to inline them into the
518         -- RHS of constructor arguments. See NOTE above
519         --
520         -- NB: Even NOINLINEis ignored here: if the rhs is trivial
521         -- it's best to inline it anyway.  We often get a=E; b=a
522         -- from desugaring, with both a and b marked NOINLINE.
523   = if  must_keep_binding then  -- Keep the binding
524         finally_bind_it unknownArity new_rhs
525                 -- Arity doesn't really matter because for a trivial RHS
526                 -- we will inline like crazy at call sites
527                 -- If this turns out be false, we can easily compute arity
528     else                        -- Drop the binding
529         extendSubst old_bndr (DoneEx new_rhs)   $
530                 -- Use the substitution to make quite, quite sure that the substitution
531                 -- will happen, since we are going to discard the binding
532         tick (PostInlineUnconditionally old_bndr)       `thenSmpl_`
533         thing_inside
534
535   | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs
536         --      [NB inner_rhs is guaranteed non-trivial by now]
537         -- x = coerce t e  ==>  c = e; x = inline_me (coerce t c)
538         -- Now x can get inlined, which moves the coercion
539         -- to the usage site.  This is a bit like worker/wrapper stuff,
540         -- but it's useful to do it very promptly, so that
541         --      x = coerce T (I# 3)
542         -- get's w/wd to
543         --      c = I# 3
544         --      x = coerce T c
545         -- This in turn means that
546         --      case (coerce Int x) of ...
547         -- will inline x.  
548         -- Also the full-blown w/w thing isn't set up for non-functions
549         --
550         -- The inline_me note is so that the simplifier doesn't 
551         -- just substitute c back inside x's rhs!  (Typically, x will
552         -- get substituted away, but not if it's exported.)
553   = newId SLIT("c") inner_ty                                    $ \ c_id ->
554     completeBinding c_id c_id top_lvl False inner_rhs           $
555     completeBinding old_bndr new_bndr top_lvl black_listed
556                     (Note InlineMe (Note coercion (Var c_id)))  $
557     thing_inside
558
559
560   |  otherwise
561   = transformRhs new_rhs finally_bind_it
562
563   where
564     old_info          = idInfo old_bndr
565     occ_info          = occInfo old_info
566     loop_breaker      = isLoopBreaker occ_info
567     trivial_rhs       = exprIsTrivial new_rhs 
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 x
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' = case splitTyConApp_maybe (idType case_bndr') of
1349                         Just (tycon, inst_tys) -> inst_tys
1350
1351         -- handled_cons is all the constructors that are dealt
1352         -- with, either by being impossible, or by there being an alternative
1353     handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1354
1355     simpl_alt (DEFAULT, _, rhs)
1356         =       -- In the default case we record the constructors that the
1357                 -- case-binder *can't* be.
1358                 -- We take advantage of any OtherCon info in the case scrutinee
1359           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons)        $ 
1360           simplExprC rhs cont'                                                  `thenSmpl` \ rhs' ->
1361           returnSmpl (DEFAULT, [], rhs')
1362
1363     simpl_alt (con, vs, rhs)
1364         =       -- Deal with the pattern-bound variables
1365                 -- Mark the ones that are in ! positions in the data constructor
1366                 -- as certainly-evaluated.
1367                 -- NB: it happens that simplBinders does *not* erase the OtherCon
1368                 --     form of unfolding, so it's ok to add this info before 
1369                 --     doing simplBinders
1370           simplBinders (add_evals con vs)                                       $ \ vs' ->
1371
1372                 -- Bind the case-binder to (con args)
1373           let
1374                 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1375           in
1376           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding)      $
1377           simplExprC rhs cont'          `thenSmpl` \ rhs' ->
1378           returnSmpl (con, vs', rhs')
1379
1380
1381         -- add_evals records the evaluated-ness of the bound variables of
1382         -- a case pattern.  This is *important*.  Consider
1383         --      data T = T !Int !Int
1384         --
1385         --      case x of { T a b -> T (a+1) b }
1386         --
1387         -- We really must record that b is already evaluated so that we don't
1388         -- go and re-evaluate it when constructing the result.
1389
1390     add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1391     add_evals other_con    vs = vs
1392
1393     cat_evals [] [] = []
1394     cat_evals (v:vs) (str:strs)
1395         | isTyVar v    = v                                   : cat_evals vs (str:strs)
1396         | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1397         | otherwise    = v'                                  : cat_evals vs strs
1398         where
1399           v' = zap_occ_info v
1400 \end{code}
1401
1402
1403 %************************************************************************
1404 %*                                                                      *
1405 \subsection{Duplicating continuations}
1406 %*                                                                      *
1407 %************************************************************************
1408
1409 \begin{code}
1410 mkDupableCont :: OutType                -- Type of the thing to be given to the continuation
1411               -> SimplCont 
1412               -> (SimplCont -> SimplM (OutStuff a))
1413               -> SimplM (OutStuff a)
1414 mkDupableCont ty cont thing_inside 
1415   | contIsDupable cont
1416   = thing_inside cont
1417
1418 mkDupableCont _ (CoerceIt ty cont) thing_inside
1419   = mkDupableCont ty cont               $ \ cont' ->
1420     thing_inside (CoerceIt ty cont')
1421
1422 mkDupableCont ty (InlinePlease cont) thing_inside
1423   = mkDupableCont ty cont               $ \ cont' ->
1424     thing_inside (InlinePlease cont')
1425
1426 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1427   =     -- Build the RHS of the join point
1428     newId SLIT("a") join_arg_ty                         ( \ arg_id ->
1429         cont_fn (Var arg_id)                            `thenSmpl` \ (binds, (_, rhs)) ->
1430         returnSmpl (Lam (setOneShotLambda arg_id) (mkLets binds rhs))
1431     )                                                   `thenSmpl` \ join_rhs ->
1432    
1433         -- Build the join Id and continuation
1434         -- We give it a "$j" name just so that for later amusement
1435         -- we can identify any join points that don't end up as let-no-escapes
1436         -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1437     newId SLIT("$j") (mkFunTy join_arg_ty cont_ty)      $ \ join_id ->
1438     let
1439         new_cont = ArgOf OkToDup cont_ty
1440                          (\arg' -> rebuild_done (App (Var join_id) arg'))
1441     in
1442
1443     tick (CaseOfCase join_id)                                           `thenSmpl_`
1444         -- Want to tick here so that we go round again,
1445         -- and maybe copy or inline the code;
1446         -- not strictly CaseOf Case
1447     addLetBind (NonRec join_id join_rhs)        $
1448     thing_inside new_cont
1449
1450 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1451   = mkDupableCont (funResultTy ty) cont                 $ \ cont' ->
1452     setSubstEnv se (simplExpr arg)                      `thenSmpl` \ arg' ->
1453     if exprIsDupable arg' then
1454         thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1455     else
1456     newId SLIT("a") (exprType arg')                     $ \ bndr ->
1457
1458     tick (CaseOfCase bndr)                              `thenSmpl_`
1459         -- Want to tick here so that we go round again,
1460         -- and maybe copy or inline the code;
1461         -- not strictly CaseOf Case
1462
1463      addLetBind (NonRec bndr arg')              $
1464         -- But what if the arg should be case-bound?  We can't use
1465         -- addNonRecBind here because its type is too specific.
1466         -- This has been this way for a long time, so I'll leave it,
1467         -- but I can't convince myself that it's right.
1468
1469      thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1470
1471
1472 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1473   = tick (CaseOfCase case_bndr)                                         `thenSmpl_`
1474     setSubstEnv se (
1475         simplBinder case_bndr                                           $ \ case_bndr' ->
1476         prepareCaseCont alts cont                                       $ \ cont' ->
1477         mapAndUnzipSmpl (mkDupableAlt case_bndr case_bndr' cont') alts  `thenSmpl` \ (alt_binds_s, alts') ->
1478         returnSmpl (concat alt_binds_s, alts')
1479     )                                   `thenSmpl` \ (alt_binds, alts') ->
1480
1481     addAuxiliaryBinds alt_binds                                 $
1482
1483         -- NB that the new alternatives, alts', are still InAlts, using the original
1484         -- binders.  That means we can keep the case_bndr intact. This is important
1485         -- because another case-of-case might strike, and so we want to keep the
1486         -- info that the case_bndr is dead (if it is, which is often the case).
1487         -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1488         -- case in I/O rich code.  We aren't allowed a lambda bound
1489         -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1490     thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1491
1492 mkDupableAlt :: InId -> OutId -> SimplCont -> InAlt -> SimplM (OutStuff InAlt)
1493 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs)
1494   = simplBinders bndrs                                  $ \ bndrs' ->
1495     simplExprC rhs cont                                 `thenSmpl` \ rhs' ->
1496
1497     if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1498         -- It is worth checking for a small RHS because otherwise we
1499         -- get extra let bindings that may cause an extra iteration of the simplifier to
1500         -- inline back in place.  Quite often the rhs is just a variable or constructor.
1501         -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1502         -- iterations because the version with the let bindings looked big, and so wasn't
1503         -- inlined, but after the join points had been inlined it looked smaller, and so
1504         -- was inlined.
1505         --
1506         -- But since the continuation is absorbed into the rhs, we only do this
1507         -- for a Stop continuation.
1508         --
1509         -- NB: we have to check the size of rhs', not rhs. 
1510         -- Duplicating a small InAlt might invalidate occurrence information
1511         -- However, if it *is* dupable, we return the *un* simplified alternative,
1512         -- because otherwise we'd need to pair it up with an empty subst-env.
1513         -- (Remember we must zap the subst-env before re-simplifying something).
1514         -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1515         returnSmpl ([], alt)
1516
1517     else
1518     let
1519         rhs_ty' = exprType rhs'
1520         (used_bndrs, used_bndrs')
1521            = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr  : bndrs)
1522                                                 (case_bndr' : bndrs'),
1523                          not (isDeadBinder bndr)]
1524                 -- The new binders have lost their occurrence info,
1525                 -- so we have to extract it from the old ones
1526     in
1527     ( if null used_bndrs' 
1528         -- If we try to lift a primitive-typed something out
1529         -- for let-binding-purposes, we will *caseify* it (!),
1530         -- with potentially-disastrous strictness results.  So
1531         -- instead we turn it into a function: \v -> e
1532         -- where v::State# RealWorld#.  The value passed to this function
1533         -- is realworld#, which generates (almost) no code.
1534
1535         -- There's a slight infelicity here: we pass the overall 
1536         -- case_bndr to all the join points if it's used in *any* RHS,
1537         -- because we don't know its usage in each RHS separately
1538
1539         -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1540         -- we make the join point into a function whenever used_bndrs'
1541         -- is empty.  This makes the join-point more CPR friendly. 
1542         -- Consider:    let j = if .. then I# 3 else I# 4
1543         --              in case .. of { A -> j; B -> j; C -> ... }
1544         --
1545         -- Now CPR should not w/w j because it's a thunk, so
1546         -- that means that the enclosing function can't w/w either,
1547         -- which is a lose.  Here's the example that happened in practice:
1548         --      kgmod :: Int -> Int -> Int
1549         --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1550         --                  then 78
1551         --                  else 5
1552
1553         then newId SLIT("w") realWorldStatePrimTy  $ \ rw_id ->
1554              returnSmpl ([rw_id], [Var realWorldPrimId])
1555         else 
1556              returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1557     )
1558         `thenSmpl` \ (final_bndrs', final_args) ->
1559
1560         -- See comment about "$j" name above
1561     newId SLIT("$j") (foldr (mkFunTy . idType) rhs_ty' final_bndrs')    $ \ join_bndr ->
1562
1563         -- Notice that we make the lambdas into one-shot-lambdas.  The
1564         -- join point is sure to be applied at most once, and doing so
1565         -- prevents the body of the join point being floated out by
1566         -- the full laziness pass
1567     returnSmpl ([NonRec join_bndr (mkLams (map setOneShotLambda final_bndrs') rhs')],
1568                 (con, bndrs, mkApps (Var join_bndr) final_args))
1569 \end{code}