[project @ 1997-01-06 21:08:42 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 #include "HsVersions.h"
8
9 module Simplify ( simplTopBinds, simplExpr, simplBind ) where
10
11 IMP_Ubiq(){-uitous-}
12 IMPORT_DELOOPER(SmplLoop)               -- paranoia checking
13 IMPORT_1_3(List(partition))
14
15 import BinderInfo
16 import CmdLineOpts      ( SimplifierSwitch(..) )
17 import ConFold          ( completePrim )
18 import CoreUnfold       ( Unfolding, SimpleUnfolding, mkFormSummary, FormSummary(..) )
19 import CostCentre       ( isSccCountCostCentre, cmpCostCentre )
20 import CoreSyn
21 import CoreUtils        ( coreExprType, nonErrorRHSs, maybeErrorApp,
22                           unTagBinders, squashableDictishCcExpr
23                         )
24 import Id               ( idType, idWantsToBeINLINEd, addIdArity, 
25                           getIdDemandInfo, addIdDemandInfo,
26                           GenId{-instance NamedThing-}
27                         )
28 import Name             ( isExported )
29 import IdInfo           ( willBeDemanded, noDemandInfo, DemandInfo, ArityInfo(..),
30                           atLeastArity, unknownArity )
31 import Literal          ( isNoRepLit )
32 import Maybes           ( maybeToBool )
33 --import Name           ( isExported )
34 import PprStyle         ( PprStyle(..) )
35 import PprType          ( GenType{-instance Outputable-} )
36 import Pretty           ( ppAbove )
37 import PrimOp           ( primOpOkForSpeculation, PrimOp(..) )
38 import SimplCase        ( simplCase, bindLargeRhs )
39 import SimplEnv
40 import SimplMonad
41 import SimplVar         ( completeVar )
42 import SimplUtils
43 import Type             ( mkTyVarTy, mkTyVarTys, mkAppTy,
44                           splitFunTy, getFunTy_maybe, eqTy
45                         )
46 import TysWiredIn       ( realWorldStateTy )
47 import Util             ( isSingleton, zipEqual, zipWithEqual, panic, pprPanic, assertPanic )
48 \end{code}
49
50 The controlling flags, and what they do
51 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
52
53 passes:
54 ------
55 -fsimplify              = run the simplifier
56 -ffloat-inwards         = runs the float lets inwards pass
57 -ffloat                 = runs the full laziness pass
58                           (ToDo: rename to -ffull-laziness)
59 -fupdate-analysis       = runs update analyser
60 -fstrictness            = runs strictness analyser
61 -fsaturate-apps         = saturates applications (eta expansion)
62
63 options:
64 -------
65 -ffloat-past-lambda     = OK to do full laziness.
66                           (ToDo: remove, as the full laziness pass is
67                                  useless without this flag, therefore
68                                  it is unnecessary. Just -ffull-laziness
69                                  should be kept.)
70
71 -ffloat-lets-ok         = OK to float lets out of lets if the enclosing
72                           let is strict or if the floating will expose
73                           a WHNF [simplifier].
74
75 -ffloat-primops-ok      = OK to float out of lets cases whose scrutinee
76                           is a primop that cannot fail [simplifier].
77
78 -fcode-duplication-ok   = allows the previous option to work on cases with
79                           multiple branches [simplifier].
80
81 -flet-to-case           = does let-to-case transformation [simplifier].
82
83 -fcase-of-case          = does case of case transformation [simplifier].
84
85 -fpedantic-bottoms      = does not allow:
86                              case x of y -> e  ===>  e[x/y]
87                           (which may turn bottom into non-bottom)
88
89
90                         NOTES ON INLINING
91                         ~~~~~~~~~~~~~~~~~
92
93 Inlining is one of the delicate aspects of the simplifier.  By
94 ``inlining'' we mean replacing an occurrence of a variable ``x'' by
95 the RHS of x's definition.  Thus
96
97         let x = e in ...x...    ===>   let x = e in ...e...
98
99 We have two mechanisms for inlining:
100
101 1.  Unconditional.  The occurrence analyser has pinned an (OneOcc
102 FunOcc NoDupDanger NotInsideSCC n) flag on the variable, saying ``it's
103 certainly safe to inline this variable, and to drop its binding''.
104 (...Umm... if n <= 1; if n > 1, it is still safe, provided you are
105 happy to be duplicating code...) When it encounters such a beast, the
106 simplifer binds the variable to its RHS (in the id_env) and continues.
107 It doesn't even look at the RHS at that stage.  It also drops the
108 binding altogether.
109
110 2.  Conditional.  In all other situations, the simplifer simplifies
111 the RHS anyway, and keeps the new binding.  It also binds the new
112 (cloned) variable to a ``suitable'' Unfolding in the UnfoldEnv.
113
114 Here, ``suitable'' might mean NoUnfolding (if the occurrence
115 info is ManyOcc and the RHS is not a manifest HNF, or UnfoldAlways (if
116 the variable has an INLINE pragma on it).  The idea is that anything
117 in the UnfoldEnv is safe to use, but also has an enclosing binding if
118 you decide not to use it.
119
120 Head normal forms
121 ~~~~~~~~~~~~~~~~~
122 We *never* put a non-HNF unfolding in the UnfoldEnv except in the
123 INLINE-pragma case.
124
125 At one time I thought it would be OK to put non-HNF unfoldings in for
126 variables which occur only once [if they got inlined at that
127 occurrence the RHS of the binding would become dead, so no duplication
128 would occur].   But consider:
129 @
130         let x = <expensive>
131             f = \y -> ...y...y...y...
132         in f x
133 @
134 Now, it seems that @x@ appears only once, but even so it is NOT safe
135 to put @x@ in the UnfoldEnv, because @f@ will be inlined, and will
136 duplicate the references to @x@.
137
138 Because of this, the "unconditional-inline" mechanism above is the
139 only way in which non-HNFs can get inlined.
140
141 INLINE pragmas
142 ~~~~~~~~~~~~~~
143
144 When a variable has an INLINE pragma on it --- which includes wrappers
145 produced by the strictness analyser --- we treat it rather carefully.
146
147 For a start, we are careful not to substitute into its RHS, because
148 that might make it BIG, and the user said "inline exactly this", not
149 "inline whatever you get after inlining other stuff inside me".  For
150 example
151
152         let f = BIG
153         in {-# INLINE y #-} y = f 3
154         in ...y...y...
155
156 Here we don't want to substitute BIG for the (single) occurrence of f,
157 because then we'd duplicate BIG when we inline'd y.  (Exception:
158 things in the UnfoldEnv with UnfoldAlways flags, which originated in
159 other INLINE pragmas.)
160
161 So, we clean out the UnfoldEnv of all SimpleUnfolding inlinings before
162 going into such an RHS.
163
164 What about imports?  They don't really matter much because we only
165 inline relatively small things via imports.
166
167 We augment the the UnfoldEnv with UnfoldAlways guidance if there's an
168 INLINE pragma.  We also do this for the RHSs of recursive decls,
169 before looking at the recursive decls. That way we achieve the effect
170 of inlining a wrapper in the body of its worker, in the case of a
171 mutually-recursive worker/wrapper split.
172
173
174 %************************************************************************
175 %*                                                                      *
176 \subsection[Simplify-simplExpr]{The main function: simplExpr}
177 %*                                                                      *
178 %************************************************************************
179
180 At the top level things are a little different.
181
182   * No cloning (not allowed for exported Ids, unnecessary for the others)
183
184   * No floating.   Case floating is obviously out.  Let floating is
185         theoretically OK, but dangerous because of space leaks.
186         The long-distance let-floater lifts these lets.
187
188 \begin{code}
189 simplTopBinds :: SimplEnv -> [InBinding] -> SmplM [OutBinding]
190
191 simplTopBinds env [] = returnSmpl []
192
193 -- Dead code is now discarded by the occurrence analyser,
194
195 simplTopBinds env (NonRec binder@(in_id,occ_info) rhs : binds)
196   =     -- No cloning necessary at top level
197         -- Process the binding
198     simplRhsExpr env binder rhs                                 `thenSmpl` \ (rhs',arity) ->
199     completeNonRec env binder (in_id `withArity` arity) rhs'    `thenSmpl` \ (new_env, binds1') ->
200
201         -- Process the other bindings
202     simplTopBinds new_env binds `thenSmpl` \ binds2' ->
203
204         -- Glue together and return ...
205     returnSmpl (binds1' ++ binds2')
206
207 simplTopBinds env (Rec pairs : binds)
208   = simplRecursiveGroup env ids pairs   `thenSmpl` \ (bind', new_env) ->
209
210         -- Process the other bindings
211     simplTopBinds new_env binds         `thenSmpl` \ binds' ->
212
213         -- Glue together and return
214     returnSmpl (bind' : binds')
215   where
216     ids = [id | (binder@(id,_), rhs) <- pairs]  -- No cloning necessary at top level
217 \end{code}
218
219 %************************************************************************
220 %*                                                                      *
221 \subsection[Simplify-simplExpr]{The main function: simplExpr}
222 %*                                                                      *
223 %************************************************************************
224
225
226 \begin{code}
227 simplExpr :: SimplEnv
228           -> InExpr -> [OutArg]
229           -> SmplM OutExpr
230 \end{code}
231
232 The expression returned has the same meaning as the input expression
233 applied to the specified arguments.
234
235
236 Variables
237 ~~~~~~~~~
238 Check if there's a macro-expansion, and if so rattle on.  Otherwise do
239 the more sophisticated stuff.
240
241 \begin{code}
242 simplExpr env (Var v) args
243   = case (lookupId env v) of
244       LitArg lit                -- A boring old literal
245         -> ASSERT( null args )
246            returnSmpl (Lit lit)
247
248       VarArg var        -- More interesting!  An id!
249         -> completeVar env var args
250                                 -- Either Id is in the local envt, or it's a global.
251                                 -- In either case we don't need to apply the type
252                                 -- environment to it.
253 \end{code}
254
255 Literals
256 ~~~~~~~~
257
258 \begin{code}
259 simplExpr env (Lit l) [] = returnSmpl (Lit l)
260 #ifdef DEBUG
261 simplExpr env (Lit l) _  = panic "simplExpr:Lit with argument"
262 #endif
263 \end{code}
264
265 Primitive applications are simple.
266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267
268 NB: Prim expects an empty argument list! (Because it should be
269 saturated and not higher-order. ADR)
270
271 \begin{code}
272 simplExpr env (Prim op prim_args) args
273   = ASSERT (null args)
274     let
275         prim_args' = [simplArg env prim_arg | prim_arg <- prim_args]
276         op'        = simpl_op op
277     in
278     completePrim env op' prim_args'
279   where
280     -- PrimOps just need any types in them renamed.
281
282     simpl_op (CCallOp label is_asm may_gc arg_tys result_ty)
283       = let
284             arg_tys'    = map (simplTy env) arg_tys
285             result_ty'  = simplTy env result_ty
286         in
287         CCallOp label is_asm may_gc arg_tys' result_ty'
288
289     simpl_op other_op = other_op
290 \end{code}
291
292 Constructor applications
293 ~~~~~~~~~~~~~~~~~~~~~~~~
294 Nothing to try here.  We only reuse constructors when they appear as the
295 rhs of a let binding (see completeLetBinding).
296
297 \begin{code}
298 simplExpr env (Con con con_args) args
299   = ASSERT( null args )
300     returnSmpl (Con con [simplArg env con_arg | con_arg <- con_args])
301 \end{code}
302
303
304 Applications are easy too:
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~
306 Just stuff 'em in the arg stack
307
308 \begin{code}
309 simplExpr env (App fun arg) args
310   = simplExpr env fun (simplArg env arg : args)
311 \end{code}
312
313 Type lambdas
314 ~~~~~~~~~~~~
315
316 We only eta-reduce a type lambda if all type arguments in the body can
317 be eta-reduced. This requires us to collect up all tyvar parameters so
318 we can pass them all to @mkTyLamTryingEta@.
319
320 \begin{code}
321 simplExpr env (Lam (TyBinder tyvar) body) (TyArg ty : args)
322   = -- ASSERT(not (isPrimType ty))
323     tick TyBetaReduction        `thenSmpl_`
324     simplExpr (extendTyEnv env tyvar ty) body args
325
326 simplExpr env tylam@(Lam (TyBinder tyvar) body) []
327   = cloneTyVarSmpl tyvar                `thenSmpl` \ tyvar' ->
328     let
329         new_env = extendTyEnv env tyvar (mkTyVarTy tyvar')
330     in
331     simplExpr new_env body []           `thenSmpl` \ body' ->
332     returnSmpl (Lam (TyBinder tyvar') body')
333
334 #ifdef DEBUG
335 simplExpr env (Lam (TyBinder _) _) (_ : _)
336   = panic "simplExpr:TyLam with non-TyArg"
337 #endif
338 \end{code}
339
340
341 Ordinary lambdas
342 ~~~~~~~~~~~~~~~~
343
344 There's a complication with lambdas that aren't saturated.
345 Suppose we have:
346
347         (\x. \y. ...x...)
348
349 If we did nothing, x is used inside the \y, so would be marked
350 as dangerous to dup.  But in the common case where the abstraction
351 is applied to two arguments this is over-pessimistic.
352 So instead we don't take account of the \y when dealing with x's usage;
353 instead, the simplifier is careful when partially applying lambdas.
354
355 \begin{code}
356 simplExpr env expr@(Lam (ValBinder binder) body) orig_args
357   = go 0 env expr orig_args
358   where
359     go n env (Lam (ValBinder binder) body) (val_arg : args)
360       | isValArg val_arg                -- The lambda has an argument
361       = tick BetaReduction      `thenSmpl_`
362         go (n+1) (extendIdEnvWithAtom env binder val_arg) body args
363
364     go n env expr@(Lam (ValBinder binder) body) args
365         -- The lambda is un-saturated, so we must zap the occurrence info
366         -- on the arguments we've already beta-reduced into the body of the lambda
367       = ASSERT( null args )     -- Value lambda must match value argument!
368         let
369             new_env = markDangerousOccs env (take n orig_args)
370         in
371         simplValLam new_env expr 0 {- Guaranteed applied to at least 0 args! -}
372                                 `thenSmpl` \ (expr', arity) ->
373         returnSmpl expr'
374
375     go n env non_val_lam_expr args      -- The lambda had enough arguments
376       = simplExpr env non_val_lam_expr args
377 \end{code}
378
379
380 Let expressions
381 ~~~~~~~~~~~~~~~
382
383 \begin{code}
384 simplExpr env (Let bind body) args
385   = simplBind env bind (\env -> simplExpr env body args)
386                        (computeResultType env body args)
387 \end{code}
388
389 Case expressions
390 ~~~~~~~~~~~~~~~~
391
392 \begin{code}
393 simplExpr env expr@(Case scrut alts) args
394   = simplCase env scrut alts (\env rhs -> simplExpr env rhs args)
395                              (computeResultType env expr args)
396 \end{code}
397
398
399 Coercions
400 ~~~~~~~~~
401 \begin{code}
402 simplExpr env (Coerce coercion ty body) args
403   = simplCoerce env coercion ty body args 
404 \end{code}
405
406
407 Set-cost-centre
408 ~~~~~~~~~~~~~~~
409
410 1) Eliminating nested sccs ...
411 We must be careful to maintain the scc counts ...
412
413 \begin{code}
414 simplExpr env (SCC cc1 (SCC cc2 expr)) args
415   | not (isSccCountCostCentre cc2) && case cmpCostCentre cc1 cc2 of { EQ_ -> True; _ -> False }
416         -- eliminate inner scc if no call counts and same cc as outer
417   = simplExpr env (SCC cc1 expr) args
418
419   | not (isSccCountCostCentre cc2) && not (isSccCountCostCentre cc1)
420         -- eliminate outer scc if no call counts associated with either ccs
421   = simplExpr env (SCC cc2 expr) args
422 \end{code}
423
424 2) Moving sccs inside lambdas ...
425   
426 \begin{code}
427 simplExpr env (SCC cc (Lam binder@(ValBinder _) body)) args
428   | not (isSccCountCostCentre cc)
429         -- move scc inside lambda only if no call counts
430   = simplExpr env (Lam binder (SCC cc body)) args
431
432 simplExpr env (SCC cc (Lam binder body)) args
433         -- always ok to move scc inside type/usage lambda
434   = simplExpr env (Lam binder (SCC cc body)) args
435 \end{code}
436
437 3) Eliminating dict sccs ...
438
439 \begin{code}
440 simplExpr env (SCC cc expr) args
441   | squashableDictishCcExpr cc expr
442         -- eliminate dict cc if trivial dict expression
443   = simplExpr env expr args
444 \end{code}
445
446 4) Moving arguments inside the body of an scc ...
447 This moves the cost of doing the application inside the scc
448 (which may include the cost of extracting methods etc)
449
450 \begin{code}
451 simplExpr env (SCC cost_centre body) args
452   = let
453         new_env = setEnclosingCC env cost_centre
454     in
455     simplExpr new_env body args         `thenSmpl` \ body' ->
456     returnSmpl (SCC cost_centre body')
457 \end{code}
458
459 %************************************************************************
460 %*                                                                      *
461 \subsection{Simplify RHS of a Let/Letrec}
462 %*                                                                      *
463 %************************************************************************
464
465 simplRhsExpr does arity-expansion.  That is, given:
466
467         * a right hand side /\ tyvars -> \a1 ... an -> e
468         * the information (stored in BinderInfo) that the function will always
469           be applied to at least k arguments
470
471 it transforms the rhs to
472
473         /\tyvars -> \a1 ... an b(n+1) ... bk -> (e b(n+1) ... bk)
474
475 This is a Very Good Thing!
476
477 \begin{code}
478 simplRhsExpr
479         :: SimplEnv
480         -> InBinder
481         -> InExpr
482         -> SmplM (OutExpr, ArityInfo)
483
484 simplRhsExpr env binder@(id,occ_info) rhs
485   =     -- Deal with the big lambda part
486     ASSERT( null uvars )        -- For now
487
488     mapSmpl cloneTyVarSmpl tyvars                       `thenSmpl` \ tyvars' ->
489     let
490         lam_env  = extendTyEnvList rhs_env (zipEqual "simplRhsExpr" tyvars (mkTyVarTys tyvars'))
491     in
492         -- Deal with the little lambda part
493         -- Note that we call simplLam even if there are no binders,
494         -- in case it can do arity expansion.
495     simplValLam lam_env body (getBinderInfoArity occ_info)      `thenSmpl` \ (lambda', arity) ->
496
497         -- Put it back together
498     returnSmpl (mkTyLam tyvars' lambda', arity)
499   where
500
501     rhs_env |   -- not (switchIsSet env IgnoreINLINEPragma) &&
502                 -- No!  Don't ever inline in a INLINE thing's rhs, because
503                 -- doing so will inline a worker straight back into its wrapper!
504               idWantsToBeINLINEd id
505             = switchOffInlining env
506             | otherwise 
507             = env
508
509         -- Switch off all inlining in the RHS of things that have an INLINE pragma.
510         -- They are going to be inlined wherever they are used, and then all the
511         -- inlining will take effect.  Meanwhile, there isn't
512         -- much point in doing anything to the as-yet-un-INLINEd rhs.
513         -- It's very important to switch off inlining!  Consider:
514         --
515         -- let f = \pq -> BIG
516         -- in
517         -- let g = \y -> f y y
518         --     {-# INLINE g #-}
519         -- in ...g...g...g...g...g...
520         --
521         -- Now, if that's the ONLY occurrence of f, it will be inlined inside g,
522         -- and thence copied multiple times when g is inlined.
523
524         -- Andy disagrees! Example:
525         --      all xs = foldr (&&) True xs
526         --      any p = all . map p  {-# INLINE any #-}
527         --
528         -- Problem: any won't get deforested, and so if it's exported and
529         -- the importer doesn't use the inlining, (eg passes it as an arg)
530         -- then we won't get deforestation at all.
531         -- We havn't solved this problem yet!
532
533     (uvars, tyvars, body) = collectUsageAndTyBinders rhs
534 \end{code}
535
536
537 %************************************************************************
538 %*                                                                      *
539 \subsection{Simplify a lambda abstraction}
540 %*                                                                      *
541 %************************************************************************
542
543 Simplify (\binders -> body) trying eta expansion and reduction, given that
544 the abstraction will always be applied to at least min_no_of_args.
545
546 \begin{code}
547 simplValLam env expr min_no_of_args
548   | not (switchIsSet env SimplDoLambdaEtaExpansion) ||  -- Bale out if eta expansion off
549
550 -- We used to disable eta expansion for thunks, but I don't see why.
551 --    null binders                                  ||  -- or it's a thunk
552
553     null potential_extra_binder_tys                 ||  -- or ain't a function
554     no_of_extra_binders <= 0                            -- or no extra binders needed
555   = cloneIds env binders                `thenSmpl` \ binders' ->
556     let
557         new_env = extendIdEnvWithClones env binders binders'
558     in
559     simplExpr new_env body []           `thenSmpl` \ body' ->
560     returnSmpl (mkValLam binders' body', atLeastArity no_of_binders)
561
562   | otherwise                           -- Eta expansion possible
563   = tick EtaExpansion                   `thenSmpl_`
564     cloneIds env binders                `thenSmpl` \ binders' ->
565     let
566         new_env = extendIdEnvWithClones env binders binders'
567     in
568     newIds extra_binder_tys                             `thenSmpl` \ extra_binders' ->
569     simplExpr new_env body (map VarArg extra_binders')  `thenSmpl` \ body' ->
570     returnSmpl (
571       mkValLam (binders' ++ extra_binders') body',
572       atLeastArity (no_of_binders + no_of_extra_binders)
573     )
574
575   where
576     (binders,body) = collectValBinders expr
577     no_of_binders  = length binders
578     (potential_extra_binder_tys, res_ty)
579         = splitFunTy (simplTy env (coreExprType (unTagBinders body)))
580         -- Note: it's possible that simplValLam will be applied to something
581         -- with a forall type.  Eg when being applied to the rhs of
582         --              let x = wurble
583         -- where wurble has a forall-type, but no big lambdas at the top.
584         -- We could be clever an insert new big lambdas, but we don't bother.
585
586     extra_binder_tys = take no_of_extra_binders potential_extra_binder_tys
587
588     no_of_extra_binders =       -- First, use the info about how many args it's
589                                 -- always applied to in its scope; but ignore this
590                                 -- if it's a thunk!  To see why we ignore it for thunks,
591                                 -- consider     let f = lookup env key in (f 1, f 2)
592                                 -- We'd better not eta expand f just because it is 
593                                 -- always applied!
594                            (if null binders
595                             then 0 
596                             else min_no_of_args - no_of_binders)
597
598                                 -- Next, try seeing if there's a lambda hidden inside
599                                 -- something cheap
600                            `max`
601                            etaExpandCount body
602
603                                 -- Finally, see if it's a state transformer, in which
604                                 -- case we eta-expand on principle! This can waste work,
605                                 -- but usually doesn't
606                            `max`
607                            case potential_extra_binder_tys of
608                                 [ty] | ty `eqTy` realWorldStateTy -> 1
609                                 other                             -> 0
610 \end{code}
611
612
613
614 %************************************************************************
615 %*                                                                      *
616 \subsection[Simplify-coerce]{Coerce expressions}
617 %*                                                                      *
618 %************************************************************************
619
620 \begin{code}
621 -- (coerce (case s of p -> r)) args ==> case s of p -> (coerce r) args
622 simplCoerce env coercion ty expr@(Case scrut alts) args
623   = simplCase env scrut alts (\env rhs -> simplCoerce env coercion ty rhs args)
624                              (computeResultType env expr args)
625
626 -- (coerce (let defns in b)) args  ==> let defns' in (coerce b) args
627 simplCoerce env coercion ty (Let bind body) args
628   = simplBind env bind (\env -> simplCoerce env coercion ty body args)
629                        (computeResultType env body args)
630
631 -- Default case
632 simplCoerce env coercion ty expr args
633   = simplExpr env expr []       `thenSmpl` \ expr' ->
634     returnSmpl (mkGenApp (mkCoerce coercion (simplTy env ty) expr') args)
635   where
636
637         -- Try cancellation; we do this "on the way up" because
638         -- I think that's where it'll bite best
639     mkCoerce (CoerceOut con1) ty1 (Coerce (CoerceIn  con2) ty2 body) | con1 == con2 = body
640     mkCoerce coercion ty  body = Coerce coercion ty body
641 \end{code}
642
643
644 %************************************************************************
645 %*                                                                      *
646 \subsection[Simplify-let]{Let-expressions}
647 %*                                                                      *
648 %************************************************************************
649
650 \begin{code}
651 simplBind :: SimplEnv
652           -> InBinding
653           -> (SimplEnv -> SmplM OutExpr)
654           -> OutType
655           -> SmplM OutExpr
656 \end{code}
657
658 When floating cases out of lets, remember this:
659
660         let x* = case e of alts
661         in <small expr>
662
663 where x* is sure to be demanded or e is a cheap operation that cannot
664 fail, e.g. unboxed addition.  Here we should be prepared to duplicate
665 <small expr>.  A good example:
666
667         let x* = case y of
668                    p1 -> build e1
669                    p2 -> build e2
670         in
671         foldr c n x*
672 ==>
673         case y of
674           p1 -> foldr c n (build e1)
675           p2 -> foldr c n (build e2)
676
677 NEW: We use the same machinery that we use for case-of-case to
678 *always* do case floating from let, that is we let bind and abstract
679 the original let body, and let the occurrence analyser later decide
680 whether the new let should be inlined or not. The example above
681 becomes:
682
683 ==>
684       let join_body x' = foldr c n x'
685         in case y of
686         p1 -> let x* = build e1
687                 in join_body x*
688         p2 -> let x* = build e2
689                 in join_body x*
690
691 note that join_body is a let-no-escape.
692 In this particular example join_body will later be inlined,
693 achieving the same effect.
694 ToDo: check this is OK with andy
695
696
697
698 \begin{code}
699 -- Dead code is now discarded by the occurrence analyser,
700
701 simplBind env (NonRec binder@(id,occ_info) rhs) body_c body_ty
702   | idWantsToBeINLINEd id
703   = complete_bind env rhs       -- Don't messa bout with floating or let-to-case on
704                                 -- INLINE things
705   | otherwise
706   = simpl_bind env rhs
707   where
708     -- Try let-to-case; see notes below about let-to-case
709     simpl_bind env rhs | will_be_demanded &&
710                          try_let_to_case &&
711                          type_ok_for_let_to_case rhs_ty &&
712                          not rhs_is_whnf        -- note: WHNF, but not bottom,  (comment below)
713       = tick Let2Case                           `thenSmpl_`
714         mkIdentityAlts rhs_ty                   `thenSmpl` \ id_alts ->
715         simplCase env rhs id_alts (\env rhs -> complete_bind env rhs) body_ty
716                 -- NB: it's tidier to call complete_bind not simpl_bind, else
717                 -- we nearly end up in a loop.  Consider:
718                 --      let x = rhs in b
719                 -- ==>  case rhs of (p,q) -> let x=(p,q) in b
720                 -- This effectively what the above simplCase call does.
721                 -- Now, the inner let is a let-to-case target again!  Actually, since
722                 -- the RHS is in WHNF it won't happen, but it's a close thing!
723
724     -- Try let-from-let
725     simpl_bind env (Let bind rhs) | let_floating_ok
726       = tick LetFloatFromLet                    `thenSmpl_`
727         simplBind env (fix_up_demandedness will_be_demanded bind)
728                       (\env -> simpl_bind env rhs) body_ty
729
730     -- Try case-from-let; this deals with a strict let of error too
731     simpl_bind env (Case scrut alts) | will_be_demanded || 
732                                        (float_primops && is_cheap_prim_app scrut)
733       = tick CaseFloatFromLet                           `thenSmpl_`
734
735         -- First, bind large let-body if necessary
736         if ok_to_dup || isSingleton (nonErrorRHSs alts)
737         then
738             simplCase env scrut alts (\env rhs -> simpl_bind env rhs) body_ty
739         else
740             bindLargeRhs env [binder] body_ty body_c    `thenSmpl` \ (extra_binding, new_body) ->
741             let
742                 body_c' = \env -> simplExpr env new_body []
743                 case_c  = \env rhs -> simplBind env (NonRec binder rhs) body_c' body_ty
744             in
745             simplCase env scrut alts case_c body_ty     `thenSmpl` \ case_expr ->
746             returnSmpl (Let extra_binding case_expr)
747
748     -- None of the above; simplify rhs and tidy up
749     simpl_bind env rhs = complete_bind env rhs
750  
751     complete_bind env rhs
752       = simplRhsExpr env binder rhs             `thenSmpl` \ (rhs',arity) ->
753         cloneId env binder                      `thenSmpl` \ new_id ->
754         completeNonRec env binder 
755                 (new_id `withArity` arity) rhs' `thenSmpl` \ (new_env, binds) ->
756         body_c new_env                          `thenSmpl` \ body' ->
757         returnSmpl (mkCoLetsAny binds body')
758
759
760         -- All this stuff is computed at the start of the simpl_bind loop
761     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
762     float_primops             = switchIsSet env SimplOkToFloatPrimOps
763     ok_to_dup                 = switchIsSet env SimplOkToDupCode
764     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
765     try_let_to_case           = switchIsSet env SimplLetToCase
766     no_float                  = switchIsSet env SimplNoLetFromStrictLet
767
768     will_be_demanded = willBeDemanded (getIdDemandInfo id)
769     rhs_ty           = idType id
770
771     rhs_is_whnf = case mkFormSummary rhs of
772                         VarForm -> True
773                         ValueForm -> True
774                         other -> False
775
776     let_floating_ok  = (will_be_demanded && not no_float) ||
777                        always_float_let_from_let ||
778                        floatExposesHNF float_lets float_primops ok_to_dup rhs
779 \end{code}
780
781 Let to case
782 ~~~~~~~~~~~
783 It's important to try let-to-case before floating. Consider
784
785         let a*::Int = case v of {p1->e1; p2->e2}
786         in b
787
788 (The * means that a is sure to be demanded.)
789 If we do case-floating first we get this:
790
791         let k = \a* -> b
792         in case v of
793                 p1-> let a*=e1 in k a
794                 p2-> let a*=e2 in k a
795
796 Now watch what happens if we do let-to-case first:
797
798         case (case v of {p1->e1; p2->e2}) of
799           Int a# -> let a*=I# a# in b
800 ===>
801         let k = \a# -> let a*=I# a# in b
802         in case v of
803                 p1 -> case e1 of I# a# -> k a#
804                 p1 -> case e1 of I# a# -> k a#
805
806 The latter is clearly better.  (Remember the reboxing let-decl for a
807 is likely to go away, because after all b is strict in a.)
808
809 We do not do let to case for WHNFs, e.g.
810
811           let x = a:b in ...
812           =/=>
813           case a:b of x in ...
814
815 as this is less efficient.  but we don't mind doing let-to-case for
816 "bottom", as that will allow us to remove more dead code, if anything:
817
818           let x = error in ...
819           ===>
820           case error  of x -> ...
821           ===>
822           error
823
824 Notice that let to case occurs only if x is used strictly in its body
825 (obviously).
826
827
828 Letrec expressions
829 ~~~~~~~~~~~~~~~~~~
830
831 Simplify each RHS, float any let(recs) from the RHSs (if let-floating is
832 on and it'll expose a HNF), and bang the whole resulting mess together
833 into a huge letrec.
834
835 1. Any "macros" should be expanded.  The main application of this
836 macro-expansion is:
837
838         letrec
839                 f = ....g...
840                 g = ....f...
841         in
842         ....f...
843
844 Here we would like the single call to g to be inlined.
845
846 We can spot this easily, because g will be tagged as having just one
847 occurrence.  The "inlineUnconditionally" predicate is just what we want.
848
849 A worry: could this lead to non-termination?  For example:
850
851         letrec
852                 f = ...g...
853                 g = ...f...
854                 h = ...h...
855         in
856         ..h..
857
858 Here, f and g call each other (just once) and neither is used elsewhere.
859 But it's OK:
860
861 * the occurrence analyser will drop any (sub)-group that isn't used at
862   all.
863
864 * If the group is used outside itself (ie in the "in" part), then there
865   can't be a cyle.
866
867 ** IMPORTANT: check that NewOccAnal has the property that a group of
868    bindings like the above has f&g dropped.! ***
869
870
871 2. We'd also like to pull out any top-level let(rec)s from the
872 rhs of the defns:
873
874         letrec
875                 f = let h = ... in \x -> ....h...f...h...
876         in
877         ...f...
878 ====>
879         letrec
880                 h = ...
881                 f = \x -> ....h...f...h...
882         in
883         ...f...
884
885 But floating cases is less easy?  (Don't for now; ToDo?)
886
887
888 3.  We'd like to arrange that the RHSs "know" about members of the
889 group that are bound to constructors.  For example:
890
891     let rec
892        d.Eq      = (==,/=)
893        f a b c d = case d.Eq of (h,_) -> let x = (a,b); y = (c,d) in not (h x y)
894        /= a b    = unpack tuple a, unpack tuple b, call f
895     in d.Eq
896
897 here, by knowing about d.Eq in f's rhs, one could get rid of
898 the case (and break out the recursion completely).
899 [This occurred with more aggressive inlining threshold (4),
900 nofib/spectral/knights]
901
902 How to do it?
903         1: we simplify constructor rhss first.
904         2: we record the "known constructors" in the environment
905         3: we simplify the other rhss, with the knowledge about the constructors
906
907
908
909 \begin{code}
910 simplBind env (Rec pairs) body_c body_ty
911   =     -- Do floating, if necessary
912     let
913         floated_pairs | do_floating = float_pairs pairs
914                       | otherwise   = pairs
915
916         ticks         | do_floating = length floated_pairs - length pairs
917                       | otherwise   = 0
918
919         binders       = map fst floated_pairs
920     in
921     tickN LetFloatFromLet ticks         `thenSmpl_` 
922                 -- It's important to increment the tick counts if we
923                 -- do any floating.  A situation where this turns out
924                 -- to be important is this:
925                 -- Float in produces:
926                 --      letrec  x = let y = Ey in Ex
927                 --      in B
928                 -- Now floating gives this:
929                 --      letrec x = Ex
930                 --             y = Ey
931                 --      in B
932                 --- We now want to iterate once more in case Ey doesn't
933                 -- mention x, in which case the y binding can be pulled
934                 -- out as an enclosing let(rec), which in turn gives
935                 -- the strictness analyser more chance.
936
937     cloneIds env binders                        `thenSmpl` \ ids' ->
938     let
939        env_w_clones = extendIdEnvWithClones env binders ids'
940     in
941     simplRecursiveGroup env_w_clones ids' floated_pairs `thenSmpl` \ (binding, new_env) ->
942
943     body_c new_env                              `thenSmpl` \ body' ->
944
945     returnSmpl (Let binding body')
946
947   where
948     ------------ Floating stuff -------------------
949
950     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
951     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
952     do_floating               = float_lets || always_float_let_from_let
953
954     float_pairs pairs = concat (map float_pair pairs)
955
956     float_pair (binder, rhs)
957         | always_float_let_from_let ||
958           floatExposesHNF True False False rhs
959         = (binder,rhs') : pairs'
960
961         | otherwise
962         = [(binder,rhs)]
963         where
964           (pairs', rhs') = do_float rhs
965
966         -- Float just pulls out any top-level let(rec) bindings
967     do_float :: InExpr -> ([(InBinder,InExpr)], InExpr)
968     do_float (Let (Rec pairs) body)     = (float_pairs pairs    ++ pairs', body')
969                                             where
970                                               (pairs', body') = do_float body
971     do_float (Let (NonRec id rhs) body) = (float_pair (id,rhs) ++ pairs', body')
972                                             where
973                                               (pairs', body') = do_float body
974     do_float other                          = ([], other)
975
976
977 -- The env passed to simplRecursiveGroup already has 
978 -- bindings that clone the variables of the group.
979 simplRecursiveGroup env new_ids pairs 
980   =     -- Add unfoldings to the new_ids corresponding to their RHS
981     let
982        binders         = map fst pairs
983        occs            = map snd binders
984        new_ids_w_pairs = zipEqual "simplRecGp" new_ids pairs
985        rhs_env         = foldl extendEnvForRecBinding 
986                                env new_ids_w_pairs
987     in
988
989     mapSmpl (\(binder,rhs) -> simplRhsExpr rhs_env binder rhs) pairs    `thenSmpl` \ new_rhss_w_arities ->
990
991     let
992        new_pairs = zipWithEqual "simplRecGp" mk_new_pair new_ids new_rhss_w_arities
993        mk_new_pair id (rhs,arity) = (id `withArity` arity, rhs)
994                 -- NB: the new arity isn't used when processing its own
995                 -- right hand sides, nor in the subsequent code
996                 -- The latter is something of a pity, and not hard to fix; but
997                 -- the info will percolate on the next iteration anyway
998
999 {-      THE NEXT FEW LINES ARE PLAIN WRONG
1000        occs_w_new_pairs = zipEqual "simplRecGp" occs new_pairs
1001        new_env          = foldl add_binding env occs_w_new_pairs
1002
1003        add_binding env (occ_info,(new_id,new_rhs)) 
1004           = extendEnvGivenBinding env occ_info new_id new_rhs
1005
1006 Here's why it's wrong: consider
1007         let f x = ...f x'...
1008         in
1009         f 3
1010
1011 If the RHS is small we'll inline f in the body of the let, then
1012 again, then again...URK
1013 -}
1014     in
1015     returnSmpl (Rec new_pairs, rhs_env)
1016 \end{code}
1017
1018
1019 @completeLet@ looks at the simplified post-floating RHS of the
1020 let-expression, and decides what to do.  There's one interesting
1021 aspect to this, namely constructor reuse.  Consider
1022 @
1023         f = \x -> case x of
1024                     (y:ys) -> y:ys
1025                     []     -> ...
1026 @
1027 Is it a good idea to replace the rhs @y:ys@ with @x@?  This depends a
1028 bit on the compiler technology, but in general I believe not. For
1029 example, here's some code from a real program:
1030 @
1031 const.Int.max.wrk{-s2516-} =
1032     \ upk.s3297#  upk.s3298# ->
1033         let {
1034           a.s3299 :: Int
1035           _N_ {-# U(P) #-}
1036           a.s3299 = I#! upk.s3297#
1037         } in
1038           case (const.Int._tagCmp.wrk{-s2513-} upk.s3297# upk.s3298#) of {
1039             _LT -> I#! upk.s3298#
1040             _EQ -> a.s3299
1041             _GT -> a.s3299
1042           }
1043 @
1044 The a.s3299 really isn't doing much good.  We'd be better off inlining
1045 it.  (Actually, let-no-escapery means it isn't as bad as it looks.)
1046
1047 So the current strategy is to inline all known-form constructors, and
1048 only do the reverse (turn a constructor application back into a
1049 variable) when we find a let-expression:
1050 @
1051         let x = C a1 .. an
1052         in
1053         ... (let y = C a1 .. an in ...) ...
1054 @
1055 where it is always good to ditch the binding for y, and replace y by
1056 x.  That's just what completeLetBinding does.
1057
1058
1059 \begin{code}
1060         -- We want to ensure that all let-bound Coerces have 
1061         -- atomic bodies, so they can freely be inlined.
1062 completeNonRec env binder new_id (Coerce coercion ty rhs)
1063   | not (is_atomic rhs)
1064   = newId (coreExprType rhs)                            `thenSmpl` \ inner_id ->
1065     completeNonRec env 
1066                    (inner_id, dangerousArgOcc) inner_id rhs `thenSmpl` \ (env1, binds1) ->
1067         -- Dangerous occ because, like constructor args,
1068         -- it can be duplicated easily
1069     let
1070         atomic_rhs = case lookupId env1 inner_id of
1071                         LitArg l -> Lit l
1072                         VarArg v -> Var v
1073     in
1074     completeNonRec env1 binder new_id
1075                    (Coerce coercion ty atomic_rhs)      `thenSmpl` \ (env2, binds2) ->
1076
1077     returnSmpl (env2, binds1 ++ binds2)
1078         
1079         -- Right hand sides that are constructors
1080         --      let v = C args
1081         --      in
1082         --- ...(let w = C same-args in ...)...
1083         -- Then use v instead of w.      This may save
1084         -- re-constructing an existing constructor.
1085 completeNonRec env binder new_id rhs@(Con con con_args)
1086   | switchIsSet env SimplReuseCon && 
1087     maybeToBool maybe_existing_con &&
1088     not (isExported new_id)             -- Don't bother for exported things
1089                                         -- because we won't be able to drop
1090                                         -- its binding.
1091   = tick ConReused              `thenSmpl_`
1092     returnSmpl (extendIdEnvWithAtom env binder (VarArg it), [NonRec new_id rhs])
1093   where
1094     maybe_existing_con = lookForConstructor env con con_args
1095     Just it            = maybe_existing_con
1096
1097
1098         -- Default case
1099         -- Check for atomic right-hand sides.
1100         -- We used to have a "tick AtomicRhs" in here, but it causes more trouble
1101         -- than it's worth.  For a top-level binding a = b, where a is exported,
1102         -- we can't drop the binding, so we get repeated AtomicRhs ticks
1103 completeNonRec env binder@(id,occ_info) new_id new_rhs
1104  = returnSmpl (new_env , [NonRec new_id new_rhs])
1105  where
1106    new_env | is_atomic eta'd_rhs                -- If rhs (after eta reduction) is atomic
1107            = extendIdEnvWithAtom env binder the_arg
1108
1109            | otherwise                          -- Non-atomic
1110            = extendEnvGivenBinding (extendIdEnvWithClone env binder new_id)
1111                         occ_info new_id new_rhs -- Don't eta if it doesn't eliminate the binding
1112
1113    eta'd_rhs = etaCoreExpr new_rhs
1114    the_arg   = case eta'd_rhs of
1115                   Var v -> VarArg v
1116                   Lit l -> LitArg l
1117 \end{code}
1118
1119 %************************************************************************
1120 %*                                                                      *
1121 \subsection[Simplify-atoms]{Simplifying atoms}
1122 %*                                                                      *
1123 %************************************************************************
1124
1125 \begin{code}
1126 simplArg :: SimplEnv -> InArg -> OutArg
1127
1128 simplArg env (LitArg lit) = LitArg lit
1129 simplArg env (TyArg  ty)  = TyArg  (simplTy env ty)
1130 simplArg env (VarArg id)  = lookupId env id
1131 \end{code}
1132
1133 %************************************************************************
1134 %*                                                                      *
1135 \subsection[Simplify-quickies]{Some local help functions}
1136 %*                                                                      *
1137 %************************************************************************
1138
1139
1140 \begin{code}
1141 -- fix_up_demandedness switches off the willBeDemanded Info field
1142 -- for bindings floated out of a non-demanded let
1143 fix_up_demandedness True {- Will be demanded -} bind
1144    = bind       -- Simple; no change to demand info needed
1145 fix_up_demandedness False {- May not be demanded -} (NonRec binder rhs)
1146    = NonRec (un_demandify binder) rhs
1147 fix_up_demandedness False {- May not be demanded -} (Rec pairs)
1148    = Rec [(un_demandify binder, rhs) | (binder,rhs) <- pairs]
1149
1150 un_demandify (id, occ_info) = (id `addIdDemandInfo` noDemandInfo, occ_info)
1151
1152 is_cheap_prim_app (Prim op _) = primOpOkForSpeculation op
1153 is_cheap_prim_app other       = False
1154
1155 computeResultType :: SimplEnv -> InExpr -> [OutArg] -> OutType
1156 computeResultType env expr args
1157   = go expr_ty' args
1158   where
1159     expr_ty  = coreExprType (unTagBinders expr)
1160     expr_ty' = simplTy env expr_ty
1161
1162     go ty [] = ty
1163     go ty (TyArg ty_arg : args) = go (mkAppTy ty ty_arg) args
1164     go ty (a:args) | isValArg a = case (getFunTy_maybe ty) of
1165                                     Just (_, res_ty) -> go res_ty args
1166                                     Nothing          -> panic "computeResultType"
1167
1168 var `withArity` UnknownArity = var
1169 var `withArity` arity        = var `addIdArity` arity
1170
1171 is_atomic (Var v) = True
1172 is_atomic (Lit l) = not (isNoRepLit l)
1173 is_atomic other   = False
1174 \end{code}
1175