[project @ 1997-01-17 00:32:23 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 mess about 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) | case_floating_ok scrut
732       = tick CaseFloatFromLet                           `thenSmpl_`
733
734         -- First, bind large let-body if necessary
735         if ok_to_dup || isSingleton (nonErrorRHSs alts)
736         then
737             simplCase env scrut alts (\env rhs -> simpl_bind env rhs) body_ty
738         else
739             bindLargeRhs env [binder] body_ty body_c    `thenSmpl` \ (extra_binding, new_body) ->
740             let
741                 body_c' = \env -> simplExpr env new_body []
742                 case_c  = \env rhs -> simplBind env (NonRec binder rhs) body_c' body_ty
743             in
744             simplCase env scrut alts case_c body_ty     `thenSmpl` \ case_expr ->
745             returnSmpl (Let extra_binding case_expr)
746
747     -- None of the above; simplify rhs and tidy up
748     simpl_bind env rhs = complete_bind env rhs
749  
750     complete_bind env rhs
751       = simplRhsExpr env binder rhs             `thenSmpl` \ (rhs',arity) ->
752         cloneId env binder                      `thenSmpl` \ new_id ->
753         completeNonRec env binder 
754                 (new_id `withArity` arity) rhs' `thenSmpl` \ (new_env, binds) ->
755         body_c new_env                          `thenSmpl` \ body' ->
756         returnSmpl (mkCoLetsAny binds body')
757
758
759         -- All this stuff is computed at the start of the simpl_bind loop
760     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
761     float_primops             = switchIsSet env SimplOkToFloatPrimOps
762     ok_to_dup                 = switchIsSet env SimplOkToDupCode
763     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
764     try_let_to_case           = switchIsSet env SimplLetToCase
765     no_float                  = switchIsSet env SimplNoLetFromStrictLet
766
767     will_be_demanded = willBeDemanded (getIdDemandInfo id)
768     rhs_ty           = idType id
769
770     rhs_is_whnf = case mkFormSummary rhs of
771                         VarForm -> True
772                         ValueForm -> True
773                         other -> False
774
775     float_exposes_hnf = floatExposesHNF float_lets float_primops ok_to_dup rhs
776
777     let_floating_ok  = (will_be_demanded && not no_float) ||
778                        always_float_let_from_let ||
779                        float_exposes_hnf
780
781     case_floating_ok scrut = (will_be_demanded && not no_float) || 
782                              (float_exposes_hnf && is_cheap_prim_app scrut && float_primops)
783         -- See note below 
784 \end{code}
785
786 Float switches
787 ~~~~~~~~~~~~~~
788 The booleans controlling floating have to be set with a little care.
789 Here's one performance bug I found:
790
791         let x = let y = let z = case a# +# 1 of {b# -> E1}
792                         in E2
793                 in E3
794         in E4
795
796 Now, if E2, E3 aren't HNFs we won't float the y-binding or the z-binding.
797 Before case_floating_ok included float_exposes_hnf, the case expression was floated
798 *one level per simplifier iteration* outwards.  So it made th s
799
800 Let to case
801 ~~~~~~~~~~~
802 It's important to try let-to-case before floating. Consider
803
804         let a*::Int = case v of {p1->e1; p2->e2}
805         in b
806
807 (The * means that a is sure to be demanded.)
808 If we do case-floating first we get this:
809
810         let k = \a* -> b
811         in case v of
812                 p1-> let a*=e1 in k a
813                 p2-> let a*=e2 in k a
814
815 Now watch what happens if we do let-to-case first:
816
817         case (case v of {p1->e1; p2->e2}) of
818           Int a# -> let a*=I# a# in b
819 ===>
820         let k = \a# -> let a*=I# a# in b
821         in case v of
822                 p1 -> case e1 of I# a# -> k a#
823                 p1 -> case e2 of I# a# -> k a#
824
825 The latter is clearly better.  (Remember the reboxing let-decl for a
826 is likely to go away, because after all b is strict in a.)
827
828 We do not do let to case for WHNFs, e.g.
829
830           let x = a:b in ...
831           =/=>
832           case a:b of x in ...
833
834 as this is less efficient.  but we don't mind doing let-to-case for
835 "bottom", as that will allow us to remove more dead code, if anything:
836
837           let x = error in ...
838           ===>
839           case error  of x -> ...
840           ===>
841           error
842
843 Notice that let to case occurs only if x is used strictly in its body
844 (obviously).
845
846
847 Letrec expressions
848 ~~~~~~~~~~~~~~~~~~
849
850 Simplify each RHS, float any let(recs) from the RHSs (if let-floating is
851 on and it'll expose a HNF), and bang the whole resulting mess together
852 into a huge letrec.
853
854 1. Any "macros" should be expanded.  The main application of this
855 macro-expansion is:
856
857         letrec
858                 f = ....g...
859                 g = ....f...
860         in
861         ....f...
862
863 Here we would like the single call to g to be inlined.
864
865 We can spot this easily, because g will be tagged as having just one
866 occurrence.  The "inlineUnconditionally" predicate is just what we want.
867
868 A worry: could this lead to non-termination?  For example:
869
870         letrec
871                 f = ...g...
872                 g = ...f...
873                 h = ...h...
874         in
875         ..h..
876
877 Here, f and g call each other (just once) and neither is used elsewhere.
878 But it's OK:
879
880 * the occurrence analyser will drop any (sub)-group that isn't used at
881   all.
882
883 * If the group is used outside itself (ie in the "in" part), then there
884   can't be a cyle.
885
886 ** IMPORTANT: check that NewOccAnal has the property that a group of
887    bindings like the above has f&g dropped.! ***
888
889
890 2. We'd also like to pull out any top-level let(rec)s from the
891 rhs of the defns:
892
893         letrec
894                 f = let h = ... in \x -> ....h...f...h...
895         in
896         ...f...
897 ====>
898         letrec
899                 h = ...
900                 f = \x -> ....h...f...h...
901         in
902         ...f...
903
904 But floating cases is less easy?  (Don't for now; ToDo?)
905
906
907 3.  We'd like to arrange that the RHSs "know" about members of the
908 group that are bound to constructors.  For example:
909
910     let rec
911        d.Eq      = (==,/=)
912        f a b c d = case d.Eq of (h,_) -> let x = (a,b); y = (c,d) in not (h x y)
913        /= a b    = unpack tuple a, unpack tuple b, call f
914     in d.Eq
915
916 here, by knowing about d.Eq in f's rhs, one could get rid of
917 the case (and break out the recursion completely).
918 [This occurred with more aggressive inlining threshold (4),
919 nofib/spectral/knights]
920
921 How to do it?
922         1: we simplify constructor rhss first.
923         2: we record the "known constructors" in the environment
924         3: we simplify the other rhss, with the knowledge about the constructors
925
926
927
928 \begin{code}
929 simplBind env (Rec pairs) body_c body_ty
930   =     -- Do floating, if necessary
931     let
932         floated_pairs | do_floating = float_pairs pairs
933                       | otherwise   = pairs
934
935         ticks         | do_floating = length floated_pairs - length pairs
936                       | otherwise   = 0
937
938         binders       = map fst floated_pairs
939     in
940     tickN LetFloatFromLet ticks         `thenSmpl_` 
941                 -- It's important to increment the tick counts if we
942                 -- do any floating.  A situation where this turns out
943                 -- to be important is this:
944                 -- Float in produces:
945                 --      letrec  x = let y = Ey in Ex
946                 --      in B
947                 -- Now floating gives this:
948                 --      letrec x = Ex
949                 --             y = Ey
950                 --      in B
951                 --- We now want to iterate once more in case Ey doesn't
952                 -- mention x, in which case the y binding can be pulled
953                 -- out as an enclosing let(rec), which in turn gives
954                 -- the strictness analyser more chance.
955
956     cloneIds env binders                        `thenSmpl` \ ids' ->
957     let
958        env_w_clones = extendIdEnvWithClones env binders ids'
959     in
960     simplRecursiveGroup env_w_clones ids' floated_pairs `thenSmpl` \ (binding, new_env) ->
961
962     body_c new_env                              `thenSmpl` \ body' ->
963
964     returnSmpl (Let binding body')
965
966   where
967     ------------ Floating stuff -------------------
968
969     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
970     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
971     do_floating               = float_lets || always_float_let_from_let
972
973     float_pairs pairs = concat (map float_pair pairs)
974
975     float_pair (binder, rhs)
976         | always_float_let_from_let ||
977           floatExposesHNF True False False rhs
978         = (binder,rhs') : pairs'
979
980         | otherwise
981         = [(binder,rhs)]
982         where
983           (pairs', rhs') = do_float rhs
984
985         -- Float just pulls out any top-level let(rec) bindings
986     do_float :: InExpr -> ([(InBinder,InExpr)], InExpr)
987     do_float (Let (Rec pairs) body)     = (float_pairs pairs    ++ pairs', body')
988                                             where
989                                               (pairs', body') = do_float body
990     do_float (Let (NonRec id rhs) body) = (float_pair (id,rhs) ++ pairs', body')
991                                             where
992                                               (pairs', body') = do_float body
993     do_float other                          = ([], other)
994
995
996 -- The env passed to simplRecursiveGroup already has 
997 -- bindings that clone the variables of the group.
998 simplRecursiveGroup env new_ids pairs 
999   =     -- Add unfoldings to the new_ids corresponding to their RHS
1000     let
1001        binders         = map fst pairs
1002        occs            = map snd binders
1003        new_ids_w_pairs = zipEqual "simplRecGp" new_ids pairs
1004        rhs_env         = foldl extendEnvForRecBinding 
1005                                env new_ids_w_pairs
1006     in
1007
1008     mapSmpl (\(binder,rhs) -> simplRhsExpr rhs_env binder rhs) pairs    `thenSmpl` \ new_rhss_w_arities ->
1009
1010     let
1011        new_pairs = zipWithEqual "simplRecGp" mk_new_pair new_ids new_rhss_w_arities
1012        mk_new_pair id (rhs,arity) = (id `withArity` arity, rhs)
1013                 -- NB: the new arity isn't used when processing its own
1014                 -- right hand sides, nor in the subsequent code
1015                 -- The latter is something of a pity, and not hard to fix; but
1016                 -- the info will percolate on the next iteration anyway
1017
1018 {-      THE NEXT FEW LINES ARE PLAIN WRONG
1019        occs_w_new_pairs = zipEqual "simplRecGp" occs new_pairs
1020        new_env          = foldl add_binding env occs_w_new_pairs
1021
1022        add_binding env (occ_info,(new_id,new_rhs)) 
1023           = extendEnvGivenBinding env occ_info new_id new_rhs
1024
1025 Here's why it's wrong: consider
1026         let f x = ...f x'...
1027         in
1028         f 3
1029
1030 If the RHS is small we'll inline f in the body of the let, then
1031 again, then again...URK
1032 -}
1033     in
1034     returnSmpl (Rec new_pairs, rhs_env)
1035 \end{code}
1036
1037
1038 @completeLet@ looks at the simplified post-floating RHS of the
1039 let-expression, and decides what to do.  There's one interesting
1040 aspect to this, namely constructor reuse.  Consider
1041 @
1042         f = \x -> case x of
1043                     (y:ys) -> y:ys
1044                     []     -> ...
1045 @
1046 Is it a good idea to replace the rhs @y:ys@ with @x@?  This depends a
1047 bit on the compiler technology, but in general I believe not. For
1048 example, here's some code from a real program:
1049 @
1050 const.Int.max.wrk{-s2516-} =
1051     \ upk.s3297#  upk.s3298# ->
1052         let {
1053           a.s3299 :: Int
1054           _N_ {-# U(P) #-}
1055           a.s3299 = I#! upk.s3297#
1056         } in
1057           case (const.Int._tagCmp.wrk{-s2513-} upk.s3297# upk.s3298#) of {
1058             _LT -> I#! upk.s3298#
1059             _EQ -> a.s3299
1060             _GT -> a.s3299
1061           }
1062 @
1063 The a.s3299 really isn't doing much good.  We'd be better off inlining
1064 it.  (Actually, let-no-escapery means it isn't as bad as it looks.)
1065
1066 So the current strategy is to inline all known-form constructors, and
1067 only do the reverse (turn a constructor application back into a
1068 variable) when we find a let-expression:
1069 @
1070         let x = C a1 .. an
1071         in
1072         ... (let y = C a1 .. an in ...) ...
1073 @
1074 where it is always good to ditch the binding for y, and replace y by
1075 x.  That's just what completeLetBinding does.
1076
1077
1078 \begin{code}
1079         -- We want to ensure that all let-bound Coerces have 
1080         -- atomic bodies, so they can freely be inlined.
1081 completeNonRec env binder new_id (Coerce coercion ty rhs)
1082   | not (is_atomic rhs)
1083   = newId (coreExprType rhs)                            `thenSmpl` \ inner_id ->
1084     completeNonRec env 
1085                    (inner_id, dangerousArgOcc) inner_id rhs `thenSmpl` \ (env1, binds1) ->
1086         -- Dangerous occ because, like constructor args,
1087         -- it can be duplicated easily
1088     let
1089         atomic_rhs = case lookupId env1 inner_id of
1090                         LitArg l -> Lit l
1091                         VarArg v -> Var v
1092     in
1093     completeNonRec env1 binder new_id
1094                    (Coerce coercion ty atomic_rhs)      `thenSmpl` \ (env2, binds2) ->
1095
1096     returnSmpl (env2, binds1 ++ binds2)
1097         
1098         -- Right hand sides that are constructors
1099         --      let v = C args
1100         --      in
1101         --- ...(let w = C same-args in ...)...
1102         -- Then use v instead of w.      This may save
1103         -- re-constructing an existing constructor.
1104 completeNonRec env binder new_id rhs@(Con con con_args)
1105   | switchIsSet env SimplReuseCon && 
1106     maybeToBool maybe_existing_con &&
1107     not (isExported new_id)             -- Don't bother for exported things
1108                                         -- because we won't be able to drop
1109                                         -- its binding.
1110   = tick ConReused              `thenSmpl_`
1111     returnSmpl (extendIdEnvWithAtom env binder (VarArg it), [NonRec new_id rhs])
1112   where
1113     maybe_existing_con = lookForConstructor env con con_args
1114     Just it            = maybe_existing_con
1115
1116
1117         -- Default case
1118         -- Check for atomic right-hand sides.
1119         -- We used to have a "tick AtomicRhs" in here, but it causes more trouble
1120         -- than it's worth.  For a top-level binding a = b, where a is exported,
1121         -- we can't drop the binding, so we get repeated AtomicRhs ticks
1122 completeNonRec env binder@(id,occ_info) new_id new_rhs
1123  = returnSmpl (new_env , [NonRec new_id new_rhs])
1124  where
1125    new_env | is_atomic eta'd_rhs                -- If rhs (after eta reduction) is atomic
1126            = extendIdEnvWithAtom env binder the_arg
1127
1128            | otherwise                          -- Non-atomic
1129            = extendEnvGivenBinding (extendIdEnvWithClone env binder new_id)
1130                         occ_info new_id new_rhs -- Don't eta if it doesn't eliminate the binding
1131
1132    eta'd_rhs = etaCoreExpr new_rhs
1133    the_arg   = case eta'd_rhs of
1134                   Var v -> VarArg v
1135                   Lit l -> LitArg l
1136 \end{code}
1137
1138 %************************************************************************
1139 %*                                                                      *
1140 \subsection[Simplify-atoms]{Simplifying atoms}
1141 %*                                                                      *
1142 %************************************************************************
1143
1144 \begin{code}
1145 simplArg :: SimplEnv -> InArg -> OutArg
1146
1147 simplArg env (LitArg lit) = LitArg lit
1148 simplArg env (TyArg  ty)  = TyArg  (simplTy env ty)
1149 simplArg env (VarArg id)  = lookupId env id
1150 \end{code}
1151
1152 %************************************************************************
1153 %*                                                                      *
1154 \subsection[Simplify-quickies]{Some local help functions}
1155 %*                                                                      *
1156 %************************************************************************
1157
1158
1159 \begin{code}
1160 -- fix_up_demandedness switches off the willBeDemanded Info field
1161 -- for bindings floated out of a non-demanded let
1162 fix_up_demandedness True {- Will be demanded -} bind
1163    = bind       -- Simple; no change to demand info needed
1164 fix_up_demandedness False {- May not be demanded -} (NonRec binder rhs)
1165    = NonRec (un_demandify binder) rhs
1166 fix_up_demandedness False {- May not be demanded -} (Rec pairs)
1167    = Rec [(un_demandify binder, rhs) | (binder,rhs) <- pairs]
1168
1169 un_demandify (id, occ_info) = (id `addIdDemandInfo` noDemandInfo, occ_info)
1170
1171 is_cheap_prim_app (Prim op _) = primOpOkForSpeculation op
1172 is_cheap_prim_app other       = False
1173
1174 computeResultType :: SimplEnv -> InExpr -> [OutArg] -> OutType
1175 computeResultType env expr args
1176   = go expr_ty' args
1177   where
1178     expr_ty  = coreExprType (unTagBinders expr)
1179     expr_ty' = simplTy env expr_ty
1180
1181     go ty [] = ty
1182     go ty (TyArg ty_arg : args) = go (mkAppTy ty ty_arg) args
1183     go ty (a:args) | isValArg a = case (getFunTy_maybe ty) of
1184                                     Just (_, res_ty) -> go res_ty args
1185                                     Nothing          -> panic "computeResultType"
1186
1187 var `withArity` UnknownArity = var
1188 var `withArity` arity        = var `addIdArity` arity
1189
1190 is_atomic (Var v) = True
1191 is_atomic (Lit l) = not (isNoRepLit l)
1192 is_atomic other   = False
1193 \end{code}
1194