[project @ 1998-03-13 17:36:27 by simonpj]
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 module Simplify ( simplTopBinds, simplExpr, simplBind ) where
8
9 #include "HsVersions.h"
10
11 import BinderInfo
12 import CmdLineOpts      ( SimplifierSwitch(..) )
13 import ConFold          ( completePrim )
14 import CoreUnfold       ( Unfolding, mkFormSummary, 
15                           exprIsTrivial, whnfOrBottom, inlineUnconditionally,
16                           FormSummary(..)
17                         )
18 import CostCentre       ( isSccCountCostCentre, cmpCostCentre, costsAreSubsumed, useCurrentCostCentre )
19 import CoreSyn
20 import CoreUtils        ( coreExprType, nonErrorRHSs, maybeErrorApp,
21                           unTagBinders, squashableDictishCcExpr
22                         )
23 import Id               ( idType, idMustBeINLINEd, idWantsToBeINLINEd, idMustNotBeINLINEd, 
24                           addIdArity, getIdArity,
25                           getIdDemandInfo, addIdDemandInfo
26                         )
27 import Name             ( isExported, isLocallyDefined )
28 import IdInfo           ( willBeDemanded, noDemandInfo, DemandInfo, ArityInfo(..),
29                           atLeastArity, unknownArity )
30 import Literal          ( isNoRepLit )
31 import Maybes           ( maybeToBool )
32 import PrimOp           ( primOpOkForSpeculation, PrimOp(..) )
33 import SimplCase        ( simplCase, bindLargeRhs )
34 import SimplEnv
35 import SimplMonad
36 import SimplVar         ( completeVar, simplBinder, simplBinders, simplTyBinder, simplTyBinders )
37 import SimplUtils
38 import Type             ( mkTyVarTy, mkTyVarTys, mkAppTy, applyTy, applyTys,
39                           mkFunTys, splitAlgTyConApp_maybe,
40                           splitFunTys, splitFunTy_maybe, isUnpointedType
41                         )
42 import TysPrim          ( realWorldStatePrimTy )
43 import Util             ( Eager, appEager, returnEager, runEager, mapEager,
44                           isSingleton, zipEqual, zipWithEqual, mapAndUnzip
45                         )
46 import Outputable       
47 \end{code}
48
49 The controlling flags, and what they do
50 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
51
52 passes:
53 ------
54 -fsimplify              = run the simplifier
55 -ffloat-inwards         = runs the float lets inwards pass
56 -ffloat                 = runs the full laziness pass
57                           (ToDo: rename to -ffull-laziness)
58 -fupdate-analysis       = runs update analyser
59 -fstrictness            = runs strictness analyser
60 -fsaturate-apps         = saturates applications (eta expansion)
61
62 options:
63 -------
64 -ffloat-past-lambda     = OK to do full laziness.
65                           (ToDo: remove, as the full laziness pass is
66                                  useless without this flag, therefore
67                                  it is unnecessary. Just -ffull-laziness
68                                  should be kept.)
69
70 -ffloat-lets-ok         = OK to float lets out of lets if the enclosing
71                           let is strict or if the floating will expose
72                           a WHNF [simplifier].
73
74 -ffloat-primops-ok      = OK to float out of lets cases whose scrutinee
75                           is a primop that cannot fail [simplifier].
76
77 -fcode-duplication-ok   = allows the previous option to work on cases with
78                           multiple branches [simplifier].
79
80 -flet-to-case           = does let-to-case transformation [simplifier].
81
82 -fcase-of-case          = does case of case transformation [simplifier].
83
84 -fpedantic-bottoms      = does not allow:
85                              case x of y -> e  ===>  e[x/y]
86                           (which may turn bottom into non-bottom)
87
88
89                         NOTES ON INLINING
90                         ~~~~~~~~~~~~~~~~~
91
92 Inlining is one of the delicate aspects of the simplifier.  By
93 ``inlining'' we mean replacing an occurrence of a variable ``x'' by
94 the RHS of x's definition.  Thus
95
96         let x = e in ...x...    ===>   let x = e in ...e...
97
98 We have two mechanisms for inlining:
99
100 1.  Unconditional.  The occurrence analyser has pinned an (OneOcc
101 FunOcc NoDupDanger NotInsideSCC n) flag on the variable, saying ``it's
102 certainly safe to inline this variable, and to drop its binding''.
103 (...Umm... if n <= 1; if n > 1, it is still safe, provided you are
104 happy to be duplicating code...) When it encounters such a beast, the
105 simplifer binds the variable to its RHS (in the id_env) and continues.
106 It doesn't even look at the RHS at that stage.  It also drops the
107 binding altogether.
108
109 2.  Conditional.  In all other situations, the simplifer simplifies
110 the RHS anyway, and keeps the new binding.  It also binds the new
111 (cloned) variable to a ``suitable'' Unfolding in the UnfoldEnv.
112
113 Here, ``suitable'' might mean NoUnfolding (if the occurrence
114 info is ManyOcc and the RHS is not a manifest HNF, or UnfoldAlways (if
115 the variable has an INLINE pragma on it).  The idea is that anything
116 in the UnfoldEnv is safe to use, but also has an enclosing binding if
117 you decide not to use it.
118
119 Head normal forms
120 ~~~~~~~~~~~~~~~~~
121 We *never* put a non-HNF unfolding in the UnfoldEnv except in the
122 INLINE-pragma case.
123
124 At one time I thought it would be OK to put non-HNF unfoldings in for
125 variables which occur only once [if they got inlined at that
126 occurrence the RHS of the binding would become dead, so no duplication
127 would occur].   But consider:
128 @
129         let x = <expensive>
130             f = \y -> ...y...y...y...
131         in f x
132 @
133 Now, it seems that @x@ appears only once, but even so it is NOT safe
134 to put @x@ in the UnfoldEnv, because @f@ will be inlined, and will
135 duplicate the references to @x@.
136
137 Because of this, the "unconditional-inline" mechanism above is the
138 only way in which non-HNFs can get inlined.
139
140 INLINE pragmas
141 ~~~~~~~~~~~~~~
142
143 When a variable has an INLINE pragma on it --- which includes wrappers
144 produced by the strictness analyser --- we treat it rather carefully.
145
146 For a start, we are careful not to substitute into its RHS, because
147 that might make it BIG, and the user said "inline exactly this", not
148 "inline whatever you get after inlining other stuff inside me".  For
149 example
150
151         let f = BIG
152         in {-# INLINE y #-} y = f 3
153         in ...y...y...
154
155 Here we don't want to substitute BIG for the (single) occurrence of f,
156 because then we'd duplicate BIG when we inline'd y.  (Exception:
157 things in the UnfoldEnv with UnfoldAlways flags, which originated in
158 other INLINE pragmas.)
159
160 So, we clean out the UnfoldEnv of all SimpleUnfolding inlinings before
161 going into such an RHS.
162
163 What about imports?  They don't really matter much because we only
164 inline relatively small things via imports.
165
166 We augment the the UnfoldEnv with UnfoldAlways guidance if there's an
167 INLINE pragma.  We also do this for the RHSs of recursive decls,
168 before looking at the recursive decls. That way we achieve the effect
169 of inlining a wrapper in the body of its worker, in the case of a
170 mutually-recursive worker/wrapper split.
171
172
173 %************************************************************************
174 %*                                                                      *
175 \subsection[Simplify-simplExpr]{The main function: simplExpr}
176 %*                                                                      *
177 %************************************************************************
178
179 At the top level things are a little different.
180
181   * No cloning (not allowed for exported Ids, unnecessary for the others)
182   * Floating is done a bit differently (no case floating; check for leaks; handle letrec)
183
184 \begin{code}
185 simplTopBinds :: SimplEnv -> [InBinding] -> SmplM [OutBinding]
186
187 -- Dead code is now discarded by the occurrence analyser,
188
189 simplTopBinds env binds
190   = mapSmpl (floatBind env True) binds  `thenSmpl` \ binds_s ->
191     simpl_top_binds env (concat binds_s)
192   where
193     simpl_top_binds env [] = returnSmpl []
194
195     simpl_top_binds env (NonRec binder@(in_id,occ_info) rhs : binds)
196       =         --- No cloning necessary at top level
197         simplBinder env binder                                          `thenSmpl` \ (env1, out_id) ->
198         simplRhsExpr env binder rhs out_id                              `thenSmpl` \ (rhs',arity) ->
199         completeNonRec env1 binder (out_id `withArity` arity) rhs'      `thenSmpl` \ (new_env, binds1') ->
200         simpl_top_binds new_env binds                                   `thenSmpl` \ binds2' ->
201         returnSmpl (binds1' ++ binds2')
202
203     simpl_top_binds env (Rec pairs : binds)
204       =         -- No cloning necessary at top level, but we nevertheless
205                 -- add the Ids to the environment.  This makes sure that
206                 -- info carried on the Id (such as arity info) gets propagated
207                 -- to occurrences.
208                 --
209                 -- This may seem optional, but I found an occasion when it Really matters.
210                 -- Consider     foo{n} = ...foo...
211                 --              baz* = foo
212                 --
213                 -- where baz* is exported and foo isn't.  Then when we do "indirection-shorting"
214                 -- in tidyCore, we need the {no-inline} pragma from foo to attached to the final
215                 -- thing:       baz*{n} = ...baz...
216                 --
217                 -- Sure we could have made the indirection-shorting a bit cleverer, but
218                 -- propagating pragma info is a Good Idea anyway.
219         simplBinders env (map fst pairs)        `thenSmpl` \ (env1, out_ids) ->
220         simplRecursiveGroup env1 out_ids pairs  `thenSmpl` \ (bind', new_env) ->
221         simpl_top_binds new_env binds           `thenSmpl` \ binds' ->
222         returnSmpl (Rec bind' : binds')
223 \end{code}
224
225 %************************************************************************
226 %*                                                                      *
227 \subsection[Simplify-simplExpr]{The main function: simplExpr}
228 %*                                                                      *
229 %************************************************************************
230
231
232 \begin{code}
233 simplExpr :: SimplEnv
234           -> InExpr -> [OutArg]
235           -> OutType            -- Type of (e args); i.e. type of overall result
236           -> SmplM OutExpr
237 \end{code}
238
239 The expression returned has the same meaning as the input expression
240 applied to the specified arguments.
241
242
243 Variables
244 ~~~~~~~~~
245 Check if there's a macro-expansion, and if so rattle on.  Otherwise do
246 the more sophisticated stuff.
247
248 \begin{code}
249 simplExpr env (Var var) args result_ty
250   = case lookupIdSubst env var of
251   
252       Just (SubstExpr ty_subst id_subst expr)
253         -> simplExpr (setSubstEnvs env ty_subst id_subst) expr args result_ty
254
255       Just (SubstLit lit)               -- A boring old literal
256         -> ASSERT( null args )
257            returnSmpl (Lit lit)
258
259       Just (SubstVar var')              -- More interesting!  An id!
260         -> completeVar env var' args result_ty
261
262       Nothing  -- Not in the substitution; hand off to completeVar
263         -> completeVar env var args result_ty 
264 \end{code}
265
266 Literals
267 ~~~~~~~~
268
269 \begin{code}
270 simplExpr env (Lit l) [] result_ty = returnSmpl (Lit l)
271 #ifdef DEBUG
272 simplExpr env (Lit l) _  _ = panic "simplExpr:Lit with argument"
273 #endif
274 \end{code}
275
276 Primitive applications are simple.
277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
278
279 NB: Prim expects an empty argument list! (Because it should be
280 saturated and not higher-order. ADR)
281
282 \begin{code}
283 simplExpr env (Prim op prim_args) args result_ty
284   = ASSERT (null args)
285     mapEager (simplArg env) prim_args   `appEager` \ prim_args' ->
286     simpl_op op                         `appEager` \ op' ->
287     completePrim env op' prim_args'
288   where
289     -- PrimOps just need any types in them renamed.
290
291     simpl_op (CCallOp label is_asm may_gc arg_tys result_ty)
292       = mapEager (simplTy env) arg_tys  `appEager` \ arg_tys' ->
293         simplTy env result_ty           `appEager` \ result_ty' ->
294         returnEager (CCallOp label is_asm may_gc arg_tys' result_ty')
295
296     simpl_op other_op = returnEager other_op
297 \end{code}
298
299 Constructor applications
300 ~~~~~~~~~~~~~~~~~~~~~~~~
301 Nothing to try here.  We only reuse constructors when they appear as the
302 rhs of a let binding (see completeLetBinding).
303
304 \begin{code}
305 simplExpr env (Con con con_args) args result_ty
306   = ASSERT( null args )
307     mapEager (simplArg env) con_args    `appEager` \ con_args' ->
308     returnSmpl (Con con con_args')
309 \end{code}
310
311
312 Applications are easy too:
313 ~~~~~~~~~~~~~~~~~~~~~~~~~~
314 Just stuff 'em in the arg stack
315
316 \begin{code}
317 simplExpr env (App fun arg) args result_ty
318   = simplArg env arg    `appEager` \ arg' ->
319     simplExpr env fun (arg' : args) result_ty
320 \end{code}
321
322 Type lambdas
323 ~~~~~~~~~~~~
324
325 First the case when it's applied to an argument.
326
327 \begin{code}
328 simplExpr env (Lam (TyBinder tyvar) body) (TyArg ty : args) result_ty
329   = tick TyBetaReduction        `thenSmpl_`
330     simplExpr (bindTyVar env tyvar ty) body args result_ty
331 \end{code}
332
333 \begin{code}
334 simplExpr env tylam@(Lam (TyBinder tyvar) body) [] result_ty
335   = simplTyBinder env tyvar     `thenSmpl` \ (new_env, tyvar') ->
336     let
337         new_result_ty = applyTy result_ty (mkTyVarTy tyvar')
338     in
339     simplExpr new_env body [] new_result_ty             `thenSmpl` \ body' ->
340     returnSmpl (Lam (TyBinder tyvar') body')
341
342 #ifdef DEBUG
343 simplExpr env (Lam (TyBinder _) _) (_ : _) result_ty
344   = panic "simplExpr:TyLam with non-TyArg"
345 #endif
346 \end{code}
347
348
349 Ordinary lambdas
350 ~~~~~~~~~~~~~~~~
351
352 There's a complication with lambdas that aren't saturated.
353 Suppose we have:
354
355         (\x. \y. ...x...)
356
357 If we did nothing, x is used inside the \y, so would be marked
358 as dangerous to dup.  But in the common case where the abstraction
359 is applied to two arguments this is over-pessimistic.
360 So instead we don't take account of the \y when dealing with x's usage;
361 instead, the simplifier is careful when partially applying lambdas.
362
363 \begin{code}
364 simplExpr env expr@(Lam (ValBinder binder) body) orig_args result_ty
365   = go 0 env expr orig_args
366   where
367     go n env (Lam (ValBinder binder) body) (val_arg : args)
368       | isValArg val_arg                -- The lambda has an argument
369       = tick BetaReduction      `thenSmpl_`
370         go (n+1) (bindIdToAtom env binder val_arg) body args
371
372     go n env expr@(Lam (ValBinder binder) body) args
373         -- The lambda is un-saturated, so we must zap the occurrence info
374         -- on the arguments we've already beta-reduced into the body of the lambda
375       = ASSERT( null args )     -- Value lambda must match value argument!
376         let
377             new_env = markDangerousOccs env orig_args
378         in
379         simplValLam new_env expr 0 {- Guaranteed applied to at least 0 args! -} result_ty 
380                                 `thenSmpl` \ (expr', arity) ->
381         returnSmpl expr'
382
383     go n env non_val_lam_expr args      -- The lambda had enough arguments
384       = simplExpr env non_val_lam_expr args result_ty
385 \end{code}
386
387
388 Let expressions
389 ~~~~~~~~~~~~~~~
390
391 \begin{code}
392 simplExpr env (Let bind body) args result_ty
393   = simplBind env bind (\env -> simplExpr env body args result_ty) result_ty
394 \end{code}
395
396 Case expressions
397 ~~~~~~~~~~~~~~~~
398
399 \begin{code}
400 simplExpr env expr@(Case scrut alts) args result_ty
401   = simplCase env scrut alts (\env rhs -> simplExpr env rhs args result_ty) result_ty
402 \end{code}
403
404
405 Coercions
406 ~~~~~~~~~
407 \begin{code}
408 simplExpr env (Coerce coercion ty body) args result_ty
409   = simplCoerce env coercion ty body args result_ty
410 \end{code}
411
412
413 Set-cost-centre
414 ~~~~~~~~~~~~~~~
415
416 1) Eliminating nested sccs ...
417 We must be careful to maintain the scc counts ...
418
419 \begin{code}
420 simplExpr env (SCC cc1 (SCC cc2 expr)) args result_ty
421   | not (isSccCountCostCentre cc2) && case cmpCostCentre cc1 cc2 of { EQ -> True; _ -> False }
422         -- eliminate inner scc if no call counts and same cc as outer
423   = simplExpr env (SCC cc1 expr) args result_ty
424
425   | not (isSccCountCostCentre cc2) && not (isSccCountCostCentre cc1)
426         -- eliminate outer scc if no call counts associated with either ccs
427   = simplExpr env (SCC cc2 expr) args result_ty
428 \end{code}
429
430 2) Moving sccs inside lambdas ...
431   
432 \begin{code}
433 simplExpr env (SCC cc (Lam binder@(ValBinder _) body)) args result_ty
434   | not (isSccCountCostCentre cc)
435         -- move scc inside lambda only if no call counts
436   = simplExpr env (Lam binder (SCC cc body)) args result_ty
437
438 simplExpr env (SCC cc (Lam binder body)) args result_ty
439         -- always ok to move scc inside type/usage lambda
440   = simplExpr env (Lam binder (SCC cc body)) args result_ty
441 \end{code}
442
443 3) Eliminating dict sccs ...
444
445 \begin{code}
446 simplExpr env (SCC cc expr) args result_ty
447   | squashableDictishCcExpr cc expr
448         -- eliminate dict cc if trivial dict expression
449   = simplExpr env expr args result_ty
450 \end{code}
451
452 4) Moving arguments inside the body of an scc ...
453 This moves the cost of doing the application inside the scc
454 (which may include the cost of extracting methods etc)
455
456 \begin{code}
457 simplExpr env (SCC cost_centre body) args result_ty
458   = let
459         new_env = setEnclosingCC env cost_centre
460     in
461     simplExpr new_env body args result_ty               `thenSmpl` \ body' ->
462     returnSmpl (SCC cost_centre body')
463 \end{code}
464
465 %************************************************************************
466 %*                                                                      *
467 \subsection{Simplify RHS of a Let/Letrec}
468 %*                                                                      *
469 %************************************************************************
470
471 simplRhsExpr does arity-expansion.  That is, given:
472
473         * a right hand side /\ tyvars -> \a1 ... an -> e
474         * the information (stored in BinderInfo) that the function will always
475           be applied to at least k arguments
476
477 it transforms the rhs to
478
479         /\tyvars -> \a1 ... an b(n+1) ... bk -> (e b(n+1) ... bk)
480
481 This is a Very Good Thing!
482
483 \begin{code}
484 simplRhsExpr
485         :: SimplEnv
486         -> InBinder
487         -> InExpr
488         -> OutId                -- The new binder (used only for its type)
489         -> SmplM (OutExpr, ArityInfo)
490 \end{code}
491
492
493 \begin{code}
494 simplRhsExpr env binder@(id,occ_info) rhs new_id
495   | maybeToBool (splitAlgTyConApp_maybe rhs_ty)
496         -- Deal with the data type case, in which case the elaborate
497         -- eta-expansion nonsense is really quite a waste of time.
498   = simplExpr rhs_env rhs [] rhs_ty             `thenSmpl` \ rhs' ->
499     returnSmpl (rhs', ArityExactly 0)
500
501   | otherwise   -- OK, use the big hammer
502   =     -- Deal with the big lambda part
503     simplTyBinders rhs_env tyvars                       `thenSmpl` \ (lam_env, tyvars') ->
504     let
505         body_ty  = applyTys rhs_ty (mkTyVarTys tyvars')
506     in
507         -- Deal with the little lambda part
508         -- Note that we call simplLam even if there are no binders,
509         -- in case it can do arity expansion.
510     simplValLam lam_env body (getBinderInfoArity occ_info) body_ty      `thenSmpl` \ (lambda', arity) ->
511
512         -- Put on the big lambdas, trying to float out any bindings caught inside
513     mkRhsTyLam tyvars' lambda'                                  `thenSmpl` \ rhs' ->
514
515     returnSmpl (rhs', arity)
516   where
517     rhs_ty  = idType new_id
518     rhs_env | idWantsToBeINLINEd id     -- Don't ever inline in a INLINE thing's rhs
519             = switchOffInlining env1    -- See comments with switchOffInlining
520             | otherwise 
521             = env1
522
523         -- The top level "enclosing CC" is "SUBSUMED".  But the enclosing CC
524         -- for the rhs of top level defs is "OST_CENTRE".  Consider
525         --      f = \x -> e
526         --      g = \y -> let v = f y in scc "x" (v ...)
527         -- Here we want to inline "f", since its CC is SUBSUMED, but we don't
528         -- want to inline "v" since its CC is dynamically determined.
529
530     current_cc = getEnclosingCC env
531     env1 | costsAreSubsumed current_cc = setEnclosingCC env useCurrentCostCentre
532          | otherwise                   = env
533
534     (tyvars, body) = collectTyBinders rhs
535 \end{code}
536
537
538 ----------------------------------------------------------------
539         An old special case that is now nuked.
540
541 First a special case for variable right-hand sides
542         v = w
543 It's OK to simplify the RHS, but it's often a waste of time.  Often
544 these v = w things persist because v is exported, and w is used 
545 elsewhere.  So if we're not careful we'll eta expand the rhs, only
546 to eta reduce it in competeNonRec.
547
548 If we leave the binding unchanged, we will certainly replace v by w at 
549 every occurrence of v, which is good enough.  
550
551 In fact, it's *better* to replace v by w than to inline w in v's rhs,
552 even if this is the only occurrence of w.  Why? Because w might have
553 IdInfo (such as strictness) that v doesn't.
554
555 Furthermore, there might be other uses of w; if so, inlining w in 
556 v's rhs will duplicate w's rhs, whereas replacing v by w doesn't.
557
558 HOWEVER, we have to be careful if w is something that *must* be
559 inlined.  In particular, its binding may have been dropped.  Here's
560 an example that actually happened:
561         let x = let y = e in y
562      in f x
563 The "let y" was floated out, and then (since y occurs once in a
564 definitely inlinable position) the binding was dropped, leaving
565         {y=e} let x = y in f x
566 But now using the reasoning of this little section, 
567 y wasn't inlined, because it was a let x=y form.
568
569
570                 HOWEVER
571
572 This "optimisation" turned out to be a bad idea.  If there's are
573 top-level exported bindings like
574
575         y = I# 3#
576         x = y
577
578 then y wasn't getting inlined in x's rhs, and we were getting
579 bad code.  So I've removed the special case from here, and
580 instead we only try eta reduction and constructor reuse 
581 in completeNonRec if the thing is *not* exported.
582
583
584 \begin{pseudocode}
585 simplRhsExpr env binder@(id,occ_info) (Var v) new_id
586  | maybeToBool maybe_stop_at_var
587  = returnSmpl (Var the_var, getIdArity the_var)
588  where
589    maybe_stop_at_var 
590      = case (runEager $ lookupId env v) of
591          VarArg v' | not (must_unfold v') -> Just v'
592          other                            -> Nothing
593
594    Just the_var = maybe_stop_at_var
595
596    must_unfold v' =  idMustBeINLINEd v'
597                   || case lookupOutIdEnv env v' of
598                         Just (_, _, InUnfolding _ _) -> True
599                         other                        -> False
600 \end{pseudocode}
601         
602                 End of old, nuked, special case.
603 ------------------------------------------------------------------
604
605
606 %************************************************************************
607 %*                                                                      *
608 \subsection{Simplify a lambda abstraction}
609 %*                                                                      *
610 %************************************************************************
611
612 Simplify (\binders -> body) trying eta expansion and reduction, given that
613 the abstraction will always be applied to at least min_no_of_args.
614
615 \begin{code}
616 simplValLam env expr min_no_of_args expr_ty
617   | not (switchIsSet env SimplDoLambdaEtaExpansion) ||  -- Bale out if eta expansion off
618
619     exprIsTrivial expr                              ||  -- or it's a trivial RHS
620         -- No eta expansion for trivial RHSs
621         -- It's rather a Bad Thing to expand
622         --      g = f alpha beta
623         -- to
624         --      g = \a b c -> f alpha beta a b c
625         --
626         -- The original RHS is "trivial" (exprIsTrivial), because it generates
627         -- no code (renames f to g).  But the new RHS isn't.
628
629     null potential_extra_binder_tys                 ||  -- or ain't a function
630     no_of_extra_binders <= 0                            -- or no extra binders needed
631   = simplBinders env binders            `thenSmpl` \ (new_env, binders') ->
632     simplExpr new_env body [] body_ty   `thenSmpl` \ body' ->
633     returnSmpl (mkValLam binders' body', final_arity)
634
635   | otherwise                           -- Eta expansion possible
636   = -- A SSERT( no_of_extra_binders <= length potential_extra_binder_tys )
637     (if not ( no_of_extra_binders <= length potential_extra_binder_tys ) then
638         pprTrace "simplValLam" (vcat [ppr expr, 
639                                           ppr expr_ty,
640                                           ppr binders,
641                                           int no_of_extra_binders,
642                                           ppr potential_extra_binder_tys])
643     else \x -> x) $
644
645     tick EtaExpansion                   `thenSmpl_`
646     simplBinders env binders            `thenSmpl` \ (new_env, binders') ->
647     newIds extra_binder_tys                                             `thenSmpl` \ extra_binders' ->
648     simplExpr new_env body (map VarArg extra_binders') etad_body_ty     `thenSmpl` \ body' ->
649     returnSmpl (
650       mkValLam (binders' ++ extra_binders') body',
651       final_arity
652     )
653
654   where
655     (binders,body)             = collectValBinders expr
656     no_of_binders              = length binders
657     (arg_tys, res_ty)          = splitFunTys expr_ty
658     potential_extra_binder_tys = (if not (no_of_binders <= length arg_tys) then
659                                         pprTrace "simplValLam" (vcat [ppr expr, 
660                                                                           ppr expr_ty,
661                                                                           ppr binders])
662                                   else \x->x) $
663                                  drop no_of_binders arg_tys
664     body_ty                    = mkFunTys potential_extra_binder_tys res_ty
665
666         -- Note: it's possible that simplValLam will be applied to something
667         -- with a forall type.  Eg when being applied to the rhs of
668         --              let x = wurble
669         -- where wurble has a forall-type, but no big lambdas at the top.
670         -- We could be clever an insert new big lambdas, but we don't bother.
671
672     etad_body_ty        = mkFunTys (drop no_of_extra_binders potential_extra_binder_tys) res_ty
673     extra_binder_tys    = take no_of_extra_binders potential_extra_binder_tys
674     final_arity         = atLeastArity (no_of_binders + no_of_extra_binders)
675
676     no_of_extra_binders =       -- First, use the info about how many args it's
677                                 -- always applied to in its scope; but ignore this
678                                 -- info for thunks. To see why we ignore it for thunks,
679                                 -- consider     let f = lookup env key in (f 1, f 2)
680                                 -- We'd better not eta expand f just because it is 
681                                 -- always applied!
682                            (min_no_of_args - no_of_binders)
683
684                                 -- Next, try seeing if there's a lambda hidden inside
685                                 -- something cheap.
686                                 -- etaExpandCount can reuturn a huge number (like 10000!) if
687                                 -- it finds that the body is a call to "error"; hence
688                                 -- the use of "min" here.
689                            `max`
690                            (etaExpandCount body `min` length potential_extra_binder_tys)
691
692                                 -- Finally, see if it's a state transformer, in which
693                                 -- case we eta-expand on principle! This can waste work,
694                                 -- but usually doesn't
695                            `max`
696                            case potential_extra_binder_tys of
697                                 [ty] | ty == realWorldStatePrimTy -> 1
698                                 other                             -> 0
699 \end{code}
700
701
702
703 %************************************************************************
704 %*                                                                      *
705 \subsection[Simplify-coerce]{Coerce expressions}
706 %*                                                                      *
707 %************************************************************************
708
709 \begin{code}
710 -- (coerce (case s of p -> r)) args ==> case s of p -> (coerce r) args
711 simplCoerce env coercion ty expr@(Case scrut alts) args result_ty
712   = simplCase env scrut alts (\env rhs -> simplCoerce env coercion ty rhs args result_ty) result_ty
713
714 -- (coerce (let defns in b)) args  ==> let defns' in (coerce b) args
715 simplCoerce env coercion ty (Let bind body) args result_ty
716   = simplBind env bind (\env -> simplCoerce env coercion ty body args result_ty) result_ty
717
718 -- Default case
719 simplCoerce env coercion ty expr args result_ty
720   = simplTy env ty                      `appEager` \ ty' ->
721     simplTy env expr_ty                 `appEager` \ expr_ty' ->
722     simplExpr env expr [] expr_ty'      `thenSmpl` \ expr' ->
723     returnSmpl (mkGenApp (mkCoerce coercion ty' expr') args)
724   where
725     expr_ty = coreExprType (unTagBinders expr)  -- Rather like simplCase other_scrut
726
727         -- Try cancellation; we do this "on the way up" because
728         -- I think that's where it'll bite best
729     mkCoerce (CoerceOut con1) ty1 (Coerce (CoerceIn  con2) ty2 body) | con1 == con2 = body
730     mkCoerce coercion ty  body = Coerce coercion ty body
731 \end{code}
732
733
734 %************************************************************************
735 %*                                                                      *
736 \subsection[Simplify-bind]{Binding groups}
737 %*                                                                      *
738 %************************************************************************
739
740 \begin{code}
741 simplBind :: SimplEnv
742           -> InBinding
743           -> (SimplEnv -> SmplM OutExpr)
744           -> OutType
745           -> SmplM OutExpr
746
747 simplBind env (NonRec binder rhs) body_c body_ty = simplNonRec env binder rhs body_c body_ty
748 simplBind env (Rec pairs)         body_c body_ty = simplRec    env pairs      body_c body_ty
749 \end{code}
750
751
752 %************************************************************************
753 %*                                                                      *
754 \subsection[Simplify-let]{Let-expressions}
755 %*                                                                      *
756 %************************************************************************
757
758 Float switches
759 ~~~~~~~~~~~~~~
760 The booleans controlling floating have to be set with a little care.
761 Here's one performance bug I found:
762
763         let x = let y = let z = case a# +# 1 of {b# -> E1}
764                         in E2
765                 in E3
766         in E4
767
768 Now, if E2, E3 aren't HNFs we won't float the y-binding or the z-binding.
769 Before case_floating_ok included float_exposes_hnf, the case expression was floated
770 *one level per simplifier iteration* outwards.  So it made th s
771
772
773 Floating case from let
774 ~~~~~~~~~~~~~~~~~~~~~~
775 When floating cases out of lets, remember this:
776
777         let x* = case e of alts
778         in <small expr>
779
780 where x* is sure to be demanded or e is a cheap operation that cannot
781 fail, e.g. unboxed addition.  Here we should be prepared to duplicate
782 <small expr>.  A good example:
783
784         let x* = case y of
785                    p1 -> build e1
786                    p2 -> build e2
787         in
788         foldr c n x*
789 ==>
790         case y of
791           p1 -> foldr c n (build e1)
792           p2 -> foldr c n (build e2)
793
794 NEW: We use the same machinery that we use for case-of-case to
795 *always* do case floating from let, that is we let bind and abstract
796 the original let body, and let the occurrence analyser later decide
797 whether the new let should be inlined or not. The example above
798 becomes:
799
800 ==>
801       let join_body x' = foldr c n x'
802         in case y of
803         p1 -> let x* = build e1
804                 in join_body x*
805         p2 -> let x* = build e2
806                 in join_body x*
807
808 note that join_body is a let-no-escape.
809 In this particular example join_body will later be inlined,
810 achieving the same effect.
811 ToDo: check this is OK with andy
812
813
814 Let to case: two points
815 ~~~~~~~~~~~
816
817 Point 1.  We defer let-to-case for all data types except single-constructor
818 ones.  Suppose we change
819
820         let x* = e in b
821 to
822         case e of x -> b
823
824 It can be the case that we find that b ultimately contains ...(case x of ..)....
825 and this is the only occurrence of x.  Then if we've done let-to-case
826 we can't inline x, which is a real pain.  On the other hand, we lose no
827 transformations by not doing this transformation, because the relevant
828 case-of-X transformations are also implemented by simpl_bind.
829
830 If x is a single-constructor type, then we go ahead anyway, giving
831
832         case e of (y,z) -> let x = (y,z) in b
833
834 because now we can squash case-on-x wherever they occur in b.
835
836 We do let-to-case on multi-constructor types in the tidy-up phase
837 (tidyCoreExpr) mainly so that the code generator doesn't need to
838 spot the demand-flag.
839
840
841 Point 2.  It's important to try let-to-case before doing the
842 strict-let-of-case transformation, which happens in the next equation
843 for simpl_bind.
844
845         let a*::Int = case v of {p1->e1; p2->e2}
846         in b
847
848 (The * means that a is sure to be demanded.)
849 If we do case-floating first we get this:
850
851         let k = \a* -> b
852         in case v of
853                 p1-> let a*=e1 in k a
854                 p2-> let a*=e2 in k a
855
856 Now watch what happens if we do let-to-case first:
857
858         case (case v of {p1->e1; p2->e2}) of
859           Int a# -> let a*=I# a# in b
860 ===>
861         let k = \a# -> let a*=I# a# in b
862         in case v of
863                 p1 -> case e1 of I# a# -> k a#
864                 p1 -> case e2 of I# a# -> k a#
865
866 The latter is clearly better.  (Remember the reboxing let-decl for a
867 is likely to go away, because after all b is strict in a.)
868
869 We do not do let to case for WHNFs, e.g.
870
871           let x = a:b in ...
872           =/=>
873           case a:b of x in ...
874
875 as this is less efficient.  but we don't mind doing let-to-case for
876 "bottom", as that will allow us to remove more dead code, if anything:
877
878           let x = error in ...
879           ===>
880           case error  of x -> ...
881           ===>
882           error
883
884 Notice that let to case occurs only if x is used strictly in its body
885 (obviously).
886
887
888 \begin{code}
889 -- Dead code is now discarded by the occurrence analyser,
890
891 simplNonRec env binder@(id,_) rhs body_c body_ty
892   | inlineUnconditionally ok_to_dup binder
893   =     -- The binder is used in definitely-inline way in the body
894         -- So add it to the environment, drop the binding, and continue
895     body_c (bindIdToExpr env binder rhs)
896
897   | idWantsToBeINLINEd id
898   = complete_bind env rhs       -- Don't mess about with floating or let-to-case on
899                                 -- INLINE things
900
901         -- Do let-to-case right away for unpointed types
902         -- These shouldn't occur much, but do occur right after desugaring,
903         -- because we havn't done dependency analysis at that point, so
904         -- we can't trivially do let-to-case (because there may be some unboxed
905         -- things bound in letrecs that aren't really recursive).
906   | isUnpointedType rhs_ty && not rhs_is_whnf
907   = simplCase env rhs (PrimAlts [] (BindDefault binder (Var id)))
908                       (\env rhs -> complete_bind env rhs) body_ty
909
910         -- Try let-to-case; see notes below about let-to-case
911   | try_let_to_case &&
912     will_be_demanded &&
913     (  rhs_is_bot
914     || (not rhs_is_whnf && singleConstructorType rhs_ty)
915                 -- Don't do let-to-case if the RHS is a constructor application.
916                 -- Even then only do it for single constructor types. 
917                 -- For other types we defer doing it until the tidy-up phase at
918                 -- the end of simplification.
919     )
920   = tick Let2Case                               `thenSmpl_`
921     simplCase env rhs (AlgAlts [] (BindDefault binder (Var id)))
922                       (\env rhs -> complete_bind env rhs) body_ty
923                 -- OLD COMMENT:  [now the new RHS is only "x" so there's less worry]
924                 -- NB: it's tidier to call complete_bind not simpl_bind, else
925                 -- we nearly end up in a loop.  Consider:
926                 --      let x = rhs in b
927                 -- ==>  case rhs of (p,q) -> let x=(p,q) in b
928                 -- This effectively what the above simplCase call does.
929                 -- Now, the inner let is a let-to-case target again!  Actually, since
930                 -- the RHS is in WHNF it won't happen, but it's a close thing!
931
932   | otherwise
933   = simpl_bind env rhs
934   where
935     -- Try let-from-let
936     simpl_bind env (Let bind rhs) | let_floating_ok
937       = tick LetFloatFromLet                    `thenSmpl_`
938         simplBind env (if will_be_demanded then bind 
939                                            else un_demandify_bind bind)
940                       (\env -> simpl_bind env rhs) body_ty
941
942     -- Try case-from-let; this deals with a strict let of error too
943     simpl_bind env (Case scrut alts) | case_floating_ok scrut
944       = tick CaseFloatFromLet                           `thenSmpl_`
945
946         -- First, bind large let-body if necessary
947         if ok_to_dup || isSingleton (nonErrorRHSs alts)
948         then
949             simplCase env scrut alts (\env rhs -> simpl_bind env rhs) body_ty
950         else
951             bindLargeRhs env [binder] body_ty body_c    `thenSmpl` \ (extra_binding, new_body) ->
952             let
953                 body_c' = \env -> simplExpr env new_body [] body_ty
954                 case_c  = \env rhs -> simplNonRec env binder rhs body_c' body_ty
955             in
956             simplCase env scrut alts case_c body_ty     `thenSmpl` \ case_expr ->
957             returnSmpl (Let extra_binding case_expr)
958
959     -- None of the above; simplify rhs and tidy up
960     simpl_bind env rhs = complete_bind env rhs
961  
962     complete_bind env rhs
963       = simplBinder env binder                  `thenSmpl` \ (env_w_clone, new_id) ->
964         simplRhsExpr env binder rhs new_id      `thenSmpl` \ (rhs',arity) ->
965         completeNonRec env_w_clone binder 
966                 (new_id `withArity` arity) rhs' `thenSmpl` \ (new_env, binds) ->
967         body_c new_env                          `thenSmpl` \ body' ->
968         returnSmpl (mkCoLetsAny binds body')
969
970
971         -- All this stuff is computed at the start of the simpl_bind loop
972     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
973     float_primops             = switchIsSet env SimplOkToFloatPrimOps
974     ok_to_dup                 = switchIsSet env SimplOkToDupCode
975     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
976     try_let_to_case           = switchIsSet env SimplLetToCase
977     no_float                  = switchIsSet env SimplNoLetFromStrictLet
978
979     demand_info      = getIdDemandInfo id
980     will_be_demanded = willBeDemanded demand_info
981     rhs_ty           = idType id
982
983     form        = mkFormSummary rhs
984     rhs_is_bot  = case form of
985                         BottomForm -> True
986                         other      -> False
987     rhs_is_whnf = case form of
988                         VarForm -> True
989                         ValueForm -> True
990                         other -> False
991
992     float_exposes_hnf = floatExposesHNF float_lets float_primops ok_to_dup rhs
993
994     let_floating_ok  = (will_be_demanded && not no_float) ||
995                        always_float_let_from_let ||
996                        float_exposes_hnf
997
998     case_floating_ok scrut = (will_be_demanded && not no_float) || 
999                              (float_exposes_hnf && is_cheap_prim_app scrut && float_primops)
1000         -- See note below 
1001 \end{code}
1002
1003
1004 @completeNonRec@ looks at the simplified post-floating RHS of the
1005 let-expression, with a view to turning
1006         x = e
1007 into
1008         x = y
1009 where y is just a variable.  Now we can eliminate the binding
1010 altogether, and replace x by y throughout.
1011
1012 There are two cases when we can do this:
1013
1014         * When e is a constructor application, and we have
1015           another variable in scope bound to the same
1016           constructor application.  [This is just a special
1017           case of common-subexpression elimination.]
1018
1019         * When e can be eta-reduced to a variable.  E.g.
1020                 x = \a b -> y a b
1021
1022
1023 HOWEVER, if x is exported, we don't attempt this at all.  Why not?
1024 Because then we can't remove the x=y binding, in which case we 
1025 have just made things worse, perhaps a lot worse.
1026
1027 \begin{code}
1028 completeNonRec env binder new_id new_rhs
1029   = returnSmpl (env', [NonRec b r | (b,r) <- binds])
1030   where
1031     (env', binds) = completeBind env binder new_id new_rhs
1032
1033
1034 completeBind :: SimplEnv 
1035              -> InBinder -> OutId -> OutExpr            -- Id and RHS
1036              -> (SimplEnv, [(OutId, OutExpr)])          -- Final envt and binding(s)
1037
1038 completeBind env binder@(_,occ_info) new_id new_rhs
1039   | idMustNotBeINLINEd new_id           -- Occurrence analyser says "don't inline"
1040   = (env, new_binds)
1041
1042   |  atomic_rhs                 -- If rhs (after eta reduction) is atomic
1043   && not (isExported new_id)    -- and binder isn't exported
1044   =     -- Drop the binding completely
1045     let
1046         env1 = notInScope env new_id
1047         env2 = bindIdToAtom env1 binder the_arg
1048     in
1049     (env2, [])
1050
1051   |  atomic_rhs                 -- Rhs is atomic, and new_id is exported
1052   && case eta'd_rhs of { Var v -> isLocallyDefined v && not (isExported v); other -> False }
1053   =     -- The local variable v will be eliminated next time round
1054         -- in favour of new_id, so it's a waste to replace all new_id's with v's
1055         -- this time round.
1056         -- This case is an optional improvement; saves a simplifier iteration
1057     (env, [(new_id, eta'd_rhs)])
1058
1059   | otherwise                           -- Non-atomic
1060   = let
1061         env1 = extendEnvGivenBinding env occ_info new_id new_rhs
1062     in 
1063     (env1, new_binds)
1064              
1065   where
1066     new_binds  = [(new_id, new_rhs)]
1067     atomic_rhs = is_atomic eta'd_rhs
1068     eta'd_rhs  = case lookForConstructor env new_rhs of 
1069                    Just v -> Var v
1070                    other  -> etaCoreExpr new_rhs
1071
1072     the_arg    = case eta'd_rhs of
1073                           Var v -> VarArg v
1074                           Lit l -> LitArg l
1075 \end{code}
1076
1077 ----------------------------------------------------------------------------
1078         A digression on constructor CSE
1079
1080 Consider
1081 @
1082         f = \x -> case x of
1083                     (y:ys) -> y:ys
1084                     []     -> ...
1085 @
1086 Is it a good idea to replace the rhs @y:ys@ with @x@?  This depends a
1087 bit on the compiler technology, but in general I believe not. For
1088 example, here's some code from a real program:
1089 @
1090 const.Int.max.wrk{-s2516-} =
1091     \ upk.s3297#  upk.s3298# ->
1092         let {
1093           a.s3299 :: Int
1094           _N_ {-# U(P) #-}
1095           a.s3299 = I#! upk.s3297#
1096         } in
1097           case (const.Int._tagCmp.wrk{-s2513-} upk.s3297# upk.s3298#) of {
1098             _LT -> I#! upk.s3298#
1099             _EQ -> a.s3299
1100             _GT -> a.s3299
1101           }
1102 @
1103 The a.s3299 really isn't doing much good.  We'd be better off inlining
1104 it.  (Actually, let-no-escapery means it isn't as bad as it looks.)
1105
1106 So the current strategy is to inline all known-form constructors, and
1107 only do the reverse (turn a constructor application back into a
1108 variable) when we find a let-expression:
1109 @
1110         let x = C a1 .. an
1111         in
1112         ... (let y = C a1 .. an in ...) ...
1113 @
1114 where it is always good to ditch the binding for y, and replace y by
1115 x.
1116                 End of digression
1117 ----------------------------------------------------------------------------
1118
1119 ----------------------------------------------------------------------------
1120                 A digression on "optimising" coercions
1121
1122    The trouble is that we kept transforming
1123                 let x = coerce e
1124                     y = coerce x
1125                 in ...
1126    to
1127                 let x' = coerce e
1128                     y' = coerce x'
1129                 in ...
1130    and counting a couple of ticks for this non-transformation
1131 \begin{pseudocode}
1132         -- We want to ensure that all let-bound Coerces have 
1133         -- atomic bodies, so they can freely be inlined.
1134 completeNonRec env binder new_id (Coerce coercion ty rhs)
1135   | not (is_atomic rhs)
1136   = newId (coreExprType rhs)                            `thenSmpl` \ inner_id ->
1137     completeNonRec env 
1138                    (inner_id, dangerousArgOcc) inner_id rhs `thenSmpl` \ (env1, binds1) ->
1139         -- Dangerous occ because, like constructor args,
1140         -- it can be duplicated easily
1141     let
1142         atomic_rhs = case runEager $ lookupId env1 inner_id of
1143                         LitArg l -> Lit l
1144                         VarArg v -> Var v
1145     in
1146     completeNonRec env1 binder new_id
1147                    (Coerce coercion ty atomic_rhs)      `thenSmpl` \ (env2, binds2) ->
1148
1149     returnSmpl (env2, binds1 ++ binds2)
1150 \end{pseudocode}
1151 ----------------------------------------------------------------------------
1152
1153
1154
1155 %************************************************************************
1156 %*                                                                      *
1157 \subsection[Simplify-letrec]{Letrec-expressions}
1158 %*                                                                      *
1159 %************************************************************************
1160
1161 Letrec expressions
1162 ~~~~~~~~~~~~~~~~~~
1163 Here's the game plan
1164
1165 1. Float any let(rec)s out of the RHSs
1166 2. Clone all the Ids and extend the envt with these clones
1167 3. Simplify one binding at a time, adding each binding to the
1168    environment once it's done.
1169
1170 This relies on the occurrence analyser to
1171         a) break all cycles with an Id marked MustNotBeInlined
1172         b) sort the decls into topological order
1173 The former prevents infinite inlinings, and the latter means
1174 that we get maximum benefit from working top to bottom.
1175
1176
1177 \begin{code}
1178 simplRec env pairs body_c body_ty
1179   =     -- Do floating, if necessary
1180     floatBind env False (Rec pairs)     `thenSmpl` \ [Rec pairs'] ->
1181     let
1182         binders = map fst pairs'
1183     in
1184     simplBinders env binders                            `thenSmpl` \ (env_w_clones, ids') ->
1185     simplRecursiveGroup env_w_clones ids' pairs'        `thenSmpl` \ (pairs', new_env) ->
1186
1187     body_c new_env                                      `thenSmpl` \ body' ->
1188
1189     returnSmpl (Let (Rec pairs') body')
1190 \end{code}
1191
1192 \begin{code}
1193 -- The env passed to simplRecursiveGroup already has 
1194 -- bindings that clone the variables of the group.
1195 simplRecursiveGroup env new_ids []
1196   = returnSmpl ([], env)
1197
1198 simplRecursiveGroup env (new_id : new_ids) ((binder, rhs) : pairs)
1199   | inlineUnconditionally ok_to_dup binder
1200   =     -- Single occurrence, so drop binding and extend env with the inlining
1201         -- This is a little delicate, because what if the unique occurrence
1202         -- is *before* this binding?  This'll never happen, because
1203         -- either it'll be marked "never inline" or else its occurrence will
1204         -- occur after its binding in the group.
1205         --
1206         -- If these claims aren't right Core Lint will spot an unbound
1207         -- variable.  A quick fix is to delete this clause for simplRecursiveGroup
1208     let
1209         new_env = bindIdToExpr env binder rhs
1210     in
1211     simplRecursiveGroup new_env new_ids pairs
1212
1213   | otherwise
1214   = simplRhsExpr env binder rhs new_id          `thenSmpl` \ (new_rhs, arity) ->
1215     let
1216         new_id'   = new_id `withArity` arity
1217         (new_env, new_binds') = completeBind env binder new_id' new_rhs
1218     in
1219     simplRecursiveGroup new_env new_ids pairs   `thenSmpl` \ (new_pairs, final_env) ->
1220     returnSmpl (new_binds' ++ new_pairs, final_env)   
1221   where
1222     ok_to_dup = switchIsSet env SimplOkToDupCode
1223 \end{code}
1224
1225
1226
1227 \begin{code}
1228 floatBind :: SimplEnv
1229           -> Bool                               -- True <=> Top level
1230           -> InBinding
1231           -> SmplM [InBinding]
1232
1233 floatBind env top_level bind
1234   | not float_lets ||
1235     n_extras == 0
1236   = returnSmpl [bind]
1237
1238   | otherwise      
1239   = tickN LetFloatFromLet n_extras              `thenSmpl_` 
1240                 -- It's important to increment the tick counts if we
1241                 -- do any floating.  A situation where this turns out
1242                 -- to be important is this:
1243                 -- Float in produces:
1244                 --      letrec  x = let y = Ey in Ex
1245                 --      in B
1246                 -- Now floating gives this:
1247                 --      letrec x = Ex
1248                 --             y = Ey
1249                 --      in B
1250                 --- We now want to iterate once more in case Ey doesn't
1251                 -- mention x, in which case the y binding can be pulled
1252                 -- out as an enclosing let(rec), which in turn gives
1253                 -- the strictness analyser more chance.
1254     returnSmpl binds'
1255
1256   where
1257     binds'   = fltBind bind
1258     n_extras = sum (map no_of_binds binds') - no_of_binds bind 
1259
1260     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
1261     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
1262
1263         -- fltBind guarantees not to return leaky floats
1264         -- and all the binders of the floats have had their demand-info zapped
1265     fltBind (NonRec bndr rhs)
1266       = binds ++ [NonRec bndr rhs'] 
1267       where
1268         (binds, rhs') = fltRhs rhs
1269     
1270     fltBind (Rec pairs)
1271       = [Rec pairs']
1272       where
1273         pairs' = concat [ let
1274                                 (binds, rhs') = fltRhs rhs
1275                           in
1276                           foldr get_pairs [(bndr, rhs')] binds
1277                         | (bndr, rhs) <- pairs
1278                         ]
1279
1280         get_pairs (NonRec bndr rhs) rest = (bndr,rhs) :  rest
1281         get_pairs (Rec pairs)       rest = pairs      ++ rest
1282     
1283         -- fltRhs has same invariant as fltBind
1284     fltRhs rhs
1285       |  (always_float_let_from_let ||
1286           floatExposesHNF True False False rhs)
1287       = fltExpr rhs
1288     
1289       | otherwise
1290       = ([], rhs)
1291     
1292     
1293         -- fltExpr has same invariant as fltBind
1294     fltExpr (Let bind body)
1295       | not top_level || binds_wont_leak
1296             -- fltExpr guarantees not to return leaky floats
1297       = (binds' ++ body_binds, body')
1298       where
1299         binds_wont_leak     = all leakFreeBind binds'
1300         (body_binds, body') = fltExpr body
1301         binds'              = fltBind (un_demandify_bind bind)
1302     
1303     fltExpr expr = ([], expr)
1304
1305 -- Crude but effective
1306 no_of_binds (NonRec _ _) = 1
1307 no_of_binds (Rec pairs)  = length pairs
1308
1309 leakFreeBind (NonRec bndr rhs) = leakFree bndr rhs
1310 leakFreeBind (Rec pairs)       = and [leakFree bndr rhs | (bndr, rhs) <- pairs]
1311
1312 leakFree (id,_) rhs = case getIdArity id of
1313                         ArityAtLeast n | n > 0 -> True
1314                         ArityExactly n | n > 0 -> True
1315                         other                  -> whnfOrBottom (mkFormSummary rhs)
1316 \end{code}
1317
1318
1319 %************************************************************************
1320 %*                                                                      *
1321 \subsection[Simplify-atoms]{Simplifying atoms}
1322 %*                                                                      *
1323 %************************************************************************
1324
1325 \begin{code}
1326 simplArg :: SimplEnv -> InArg -> Eager ans OutArg
1327
1328 simplArg env (LitArg lit) = returnEager (LitArg lit)
1329 simplArg env (TyArg  ty)  = simplTy env ty      `appEager` \ ty' -> 
1330                             returnEager (TyArg ty')
1331 simplArg env arg@(VarArg id)
1332   = case lookupIdSubst env id of
1333         Just (SubstVar id')   -> returnEager (VarArg id')
1334         Just (SubstLit lit)   -> returnEager (LitArg lit)
1335         Just (SubstExpr _ __) -> panic "simplArg"
1336         Nothing               -> case lookupOutIdEnv env id of
1337                                   Just (id', _, _) -> returnEager (VarArg id')
1338                                   Nothing          -> returnEager arg
1339 \end{code}
1340
1341 %************************************************************************
1342 %*                                                                      *
1343 \subsection[Simplify-quickies]{Some local help functions}
1344 %*                                                                      *
1345 %************************************************************************
1346
1347
1348 \begin{code}
1349 -- un_demandify_bind switches off the willBeDemanded Info field
1350 -- for bindings floated out of a non-demanded let
1351 un_demandify_bind (NonRec binder rhs)
1352    = NonRec (un_demandify_bndr binder) rhs
1353 un_demandify_bind (Rec pairs)
1354    = Rec [(un_demandify_bndr binder, rhs) | (binder,rhs) <- pairs]
1355
1356 un_demandify_bndr (id, occ_info) = (id `addIdDemandInfo` noDemandInfo, occ_info)
1357
1358 is_cheap_prim_app (Prim op _) = primOpOkForSpeculation op
1359 is_cheap_prim_app other       = False
1360
1361 computeResultType :: SimplEnv -> InType -> [OutArg] -> OutType
1362 computeResultType env expr_ty orig_args
1363   = simplTy env expr_ty         `appEager` \ expr_ty' ->
1364     let
1365         go ty [] = ty
1366         go ty (TyArg ty_arg : args) = go (mkAppTy ty ty_arg) args
1367         go ty (a:args) | isValArg a = case (splitFunTy_maybe ty) of
1368                                         Just (_, res_ty) -> go res_ty args
1369                                         Nothing          -> 
1370                                             pprPanic "computeResultType" (vcat [
1371                                                                         ppr (a:args),
1372                                                                         ppr orig_args,
1373                                                                         ppr expr_ty',
1374                                                                         ppr ty])
1375     in
1376     go expr_ty' orig_args
1377
1378
1379 var `withArity` UnknownArity = var
1380 var `withArity` arity        = var `addIdArity` arity
1381
1382 is_atomic (Var v) = True
1383 is_atomic (Lit l) = not (isNoRepLit l)
1384 is_atomic other   = False
1385 \end{code}
1386