[project @ 2001-10-23 08:58:30 by simonpj]
[ghc-hetmet.git] / ghc / compiler / stranal / DmdAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4
5                         -----------------
6                         A demand analysis
7                         -----------------
8
9 \begin{code}
10 module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs, 
11                  both {- needed by WwLib -}
12    ) where
13
14 #include "HsVersions.h"
15
16 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_MaxWorkerArgs )
17 import NewDemand        -- All of it
18 import CoreSyn
19 import PprCore  
20 import CoreUtils        ( exprIsValue, exprArity )
21 import DataCon          ( dataConTyCon )
22 import TyCon            ( isProductTyCon, isRecursiveTyCon )
23 import Id               ( Id, idType, idDemandInfo, 
24                           isDataConId, isGlobalId, idArity,
25                           idNewStrictness, idNewStrictness_maybe, getNewStrictness, setIdNewStrictness,
26                           idNewDemandInfo, setIdNewDemandInfo, newStrictnessFromOld )
27 import IdInfo           ( newDemand )
28 import Var              ( Var )
29 import VarEnv
30 import UniqFM           ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
31                           keysUFM, minusUFM, ufmToList, filterUFM )
32 import Type             ( isUnLiftedType )
33 import CoreLint         ( showPass, endPass )
34 import Util             ( mapAndUnzip, mapAccumL, mapAccumR )
35 import BasicTypes       ( Arity, TopLevelFlag(..), isTopLevel )
36 import Maybes           ( orElse, expectJust )
37 import Outputable
38 \end{code}
39
40 To think about
41
42 * set a noinline pragma on bottoming Ids
43
44 * Consider f x = x+1 `fatbar` error (show x)
45   We'd like to unbox x, even if that means reboxing it in the error case.
46
47 \begin{code}
48 instance Outputable TopLevelFlag where
49   ppr flag = empty
50 \end{code}
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{Top level stuff}
55 %*                                                                      *
56 %************************************************************************
57
58 \begin{code}
59 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
60 dmdAnalPgm dflags binds
61   = do {
62         showPass dflags "Demand analysis" ;
63         let { binds_plus_dmds = do_prog binds ;
64               dmd_changes = get_changes binds_plus_dmds } ;
65         endPass dflags "Demand analysis" 
66                 Opt_D_dump_stranal binds_plus_dmds ;
67 #ifdef DEBUG
68         -- Only if DEBUG is on, because only then is the old strictness analyser run
69         printDump (text "Changes in demands" $$ dmd_changes) ;
70 #endif
71         return binds_plus_dmds
72     }
73   where
74     do_prog :: [CoreBind] -> [CoreBind]
75     do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
76
77 dmdAnalTopBind :: SigEnv
78                -> CoreBind 
79                -> (SigEnv, CoreBind)
80 dmdAnalTopBind sigs (NonRec id rhs)
81   = let
82         (sigs', _, (id', rhs')) = dmdAnalRhs TopLevel sigs (id, rhs)
83     in
84     (sigs', NonRec id' rhs')    
85
86 dmdAnalTopBind sigs (Rec pairs)
87   = let
88         (sigs', _, pairs')  = dmdFix TopLevel sigs pairs
89     in
90     (sigs', Rec pairs')
91 \end{code}
92
93 \begin{code}
94 dmdAnalTopRhs :: CoreExpr -> (StrictSig, CoreExpr)
95 -- Analyse the RHS and return
96 --      a) appropriate strictness info
97 --      b) the unfolding (decorated with stricntess info)
98 dmdAnalTopRhs rhs
99   = (sig, rhs')
100   where
101     arity          = exprArity rhs
102     (rhs_ty, rhs') = dmdAnal emptySigEnv (vanillaCall arity) rhs
103     (_, sig)       = mkSigTy rhs rhs_ty
104 \end{code}
105
106 %************************************************************************
107 %*                                                                      *
108 \subsection{The analyser itself}        
109 %*                                                                      *
110 %************************************************************************
111
112 \begin{code}
113 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
114
115 dmdAnal sigs Abs  e = (topDmdType, e)
116 dmdAnal sigs Bot  e = (botDmdType, e)
117
118 dmdAnal sigs Lazy e = let 
119                         (res_ty, e') = dmdAnal sigs Eval e
120                       in
121                       (deferType res_ty, e')
122         -- It's important not to analyse e with a lazy demand because
123         -- a) When we encounter   case s of (a,b) -> 
124         --      we demand s with U(d1d2)... but if the overall demand is lazy
125         --      that is wrong, and we'd need to reduce the demand on s,
126         --      which is inconvenient
127         -- b) More important, consider
128         --      f (let x = R in x+x), where f is lazy
129         --    We still want to mark x as demanded, because it will be when we
130         --    enter the let.  If we analyse f's arg with a Lazy demand, we'll
131         --    just mark x as Lazy
132         -- c) The application rule wouldn't be right either
133         --    Evaluating (f x) in a L demand does *not* cause
134         --    evaluation of f in a C(L) demand!
135
136
137 dmdAnal sigs dmd (Lit lit)
138   = (topDmdType, Lit lit)
139
140 dmdAnal sigs dmd (Var var)
141   = (dmdTransform sigs var dmd, Var var)
142
143 dmdAnal sigs dmd (Note n e)
144   = (dmd_ty, Note n e')
145   where
146     (dmd_ty, e') = dmdAnal sigs dmd' e  
147     dmd' = case n of
148              Coerce _ _ -> Eval   -- This coerce usually arises from a recursive
149              other      -> dmd    -- newtype, and we don't want to look inside them
150                                   -- for exactly the same reason that we don't look
151                                   -- inside recursive products -- we might not reach
152                                   -- a fixpoint.  So revert to a vanilla Eval demand
153
154 dmdAnal sigs dmd (App fun (Type ty))
155   = (fun_ty, App fun' (Type ty))
156   where
157     (fun_ty, fun') = dmdAnal sigs dmd fun
158
159 -- Lots of the other code is there to make this
160 -- beautiful, compositional, application rule :-)
161 dmdAnal sigs dmd e@(App fun arg)        -- Non-type arguments
162   = let                         -- [Type arg handled above]
163         (fun_ty, fun')    = dmdAnal sigs (Call dmd) fun
164         (arg_ty, arg')    = dmdAnal sigs arg_dmd arg
165         (arg_dmd, res_ty) = splitDmdTy fun_ty
166     in
167     (res_ty `bothType` arg_ty, App fun' arg')
168
169 dmdAnal sigs dmd (Lam var body)
170   | isTyVar var
171   = let   
172         (body_ty, body') = dmdAnal sigs dmd body
173     in
174     (body_ty, Lam var body')
175
176   | Call body_dmd <- dmd        -- A call demand: good!
177   = let 
178         (body_ty, body') = dmdAnal sigs body_dmd body
179         (lam_ty, var')   = annotateLamIdBndr body_ty var
180     in
181     (lam_ty, Lam var' body')
182
183   | otherwise   -- Not enough demand on the lambda; but do the body
184   = let         -- anyway to annotate it and gather free var info
185         (body_ty, body') = dmdAnal sigs Eval body
186         (lam_ty, var')   = annotateLamIdBndr body_ty var
187     in
188     (deferType lam_ty, Lam var' body')
189
190 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
191   | let tycon = dataConTyCon dc,
192     isProductTyCon tycon,
193     not (isRecursiveTyCon tycon)
194   = let
195         (alt_ty, alt')           = dmdAnalAlt sigs dmd alt
196         (alt_ty1, case_bndr')    = annotateBndr alt_ty case_bndr
197         (_, bndrs', _)           = alt'
198
199         -- Figure out whether the demand on the case binder is used, and use
200         -- that to set the scrut_dmd.  This is utterly essential.
201         -- Consider     f x = case x of y { (a,b) -> k y a }
202         -- If we just take scrut_demand = U(L,A), then we won't pass x to the
203         -- worker, so the worker will rebuild 
204         --      x = (a, absent-error)
205         -- and that'll crash.
206         -- So at one stage I had:
207         --      dead_case_bndr           = isAbsentDmd (idNewDemandInfo case_bndr')
208         --      keepity | dead_case_bndr = Drop
209         --              | otherwise      = Keep         
210         --
211         -- But then consider
212         --      case x of y { (a,b) -> h y + a }
213         -- where h : U(LL) -> T
214         -- The above code would compute a Keep for x, since y is not Abs, which is silly
215         -- The insight is, of course, that a demand on y is a demand on the
216         -- scrutinee, so we need to `both` it with the scrut demand
217
218         scrut_dmd                = mkSeq Drop [idNewDemandInfo b | b <- bndrs', isId b]
219                                    `both`
220                                    idNewDemandInfo case_bndr'
221
222         (scrut_ty, scrut')       = dmdAnal sigs scrut_dmd scrut
223     in
224     (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
225
226 dmdAnal sigs dmd (Case scrut case_bndr alts)
227   = let
228         (alt_tys, alts')        = mapAndUnzip (dmdAnalAlt sigs dmd) alts
229         (scrut_ty, scrut')      = dmdAnal sigs Eval scrut
230         (alt_ty, case_bndr')    = annotateBndr (foldr1 lubType alt_tys) case_bndr
231     in
232 --    pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
233     (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
234
235 dmdAnal sigs dmd (Let (NonRec id rhs) body) 
236   = let
237         (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs NotTopLevel sigs (id, rhs)
238         (body_ty, body')              = dmdAnal sigs' dmd body
239         (body_ty1, id2)               = annotateBndr body_ty id1
240         body_ty2                      = addLazyFVs body_ty1 lazy_fv
241     in
242 --    pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env))
243     (body_ty2, Let (NonRec id2 rhs') body')    
244
245 dmdAnal sigs dmd (Let (Rec pairs) body) 
246   = let
247         bndrs                    = map fst pairs
248         (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
249         (body_ty, body')         = dmdAnal sigs' dmd body
250         body_ty1                 = addLazyFVs body_ty lazy_fv
251     in
252     sigs' `seq` body_ty `seq`
253     let
254         (body_ty2, _) = annotateBndrs body_ty1 bndrs
255                 -- Don't bother to add demand info to recursive
256                 -- binders as annotateBndr does; 
257                 -- being recursive, we can't treat them strictly.
258                 -- But we do need to remove the binders from the result demand env
259     in
260     (body_ty2,  Let (Rec pairs') body')
261
262
263 dmdAnalAlt sigs dmd (con,bndrs,rhs) 
264   = let 
265         (rhs_ty, rhs')   = dmdAnal sigs dmd rhs
266         (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
267     in
268     (alt_ty, (con, bndrs', rhs'))
269 \end{code}
270
271 %************************************************************************
272 %*                                                                      *
273 \subsection{Bindings}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278 dmdFix :: TopLevelFlag
279        -> SigEnv                -- Does not include bindings for this binding
280        -> [(Id,CoreExpr)]
281        -> (SigEnv, DmdEnv,
282            [(Id,CoreExpr)])     -- Binders annotated with stricness info
283
284 dmdFix top_lvl sigs orig_pairs
285   = loop 1 initial_sigs orig_pairs
286   where
287     bndrs        = map fst orig_pairs
288     initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs]
289     
290     loop :: Int
291          -> SigEnv                      -- Already contains the current sigs
292          -> [(Id,CoreExpr)]             
293          -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
294     loop n sigs pairs
295       | all (same_sig sigs sigs') bndrs 
296       = (sigs', lazy_fv, pairs')
297                 -- Note: use pairs', not pairs.   pairs' is the result of 
298                 -- processing the RHSs with sigs (= sigs'), whereas pairs 
299                 -- is the result of processing the RHSs with the *previous* 
300                 -- iteration of sigs.
301       | n >= 10       = pprTrace "dmdFix loop" (ppr n <+> (vcat 
302                                 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
303                                   text "env:" <+> ppr (ufmToList sigs),
304                                   text "binds:" <+> pprCoreBinding (Rec pairs)]))
305                               (emptySigEnv, emptyDmdEnv, orig_pairs)    -- Safe output
306       | otherwise    = loop (n+1) sigs' pairs'
307       where
308                 -- Use the new signature to do the next pair
309                 -- The occurrence analyser has arranged them in a good order
310                 -- so this can significantly reduce the number of iterations needed
311         ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
312         
313     my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
314         = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
315           -- (new_sig `seq` 
316           --    pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' ) 
317           ((sigs', lazy_fv'), pair')
318           --     )
319         where
320           (sigs', lazy_fv1, pair') = dmdAnalRhs top_lvl sigs (id,rhs)
321           lazy_fv'                 = plusUFM_C both lazy_fv lazy_fv1   
322           -- old_sig               = lookup sigs id
323           -- new_sig               = lookup sigs' id
324            
325         -- Get an initial strictness signature from the Id
326         -- itself.  That way we make use of earlier iterations
327         -- of the fixpoint algorithm.  (Cunning plan.)
328         -- Note that the cunning plan extends to the DmdEnv too,
329         -- since it is part of the strictness signature
330     initial_sig id = idNewStrictness_maybe id `orElse` botSig
331
332     same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
333     lookup sigs var = case lookupVarEnv sigs var of
334                         Just (sig,_) -> sig
335
336 dmdAnalRhs :: TopLevelFlag 
337         -> SigEnv -> (Id, CoreExpr)
338         -> (SigEnv,  DmdEnv, (Id, CoreExpr))
339 -- Process the RHS of the binding, add the strictness signature
340 -- to the Id, and augment the environment with the signature as well.
341
342 dmdAnalRhs top_lvl sigs (id, rhs)
343  = (sigs', lazy_fv, (id', rhs'))
344  where
345   arity             = exprArity rhs   -- The idArity may not be up to date
346   (rhs_ty, rhs')    = dmdAnal sigs (vanillaCall arity) rhs
347   (lazy_fv, sig_ty) = WARN( arity /= dmdTypeDepth rhs_ty, ppr id )
348                       mkSigTy rhs rhs_ty
349   id'               = id `setIdNewStrictness` sig_ty
350   sigs'             = extendSigEnv top_lvl sigs id sig_ty
351 \end{code}
352
353 %************************************************************************
354 %*                                                                      *
355 \subsection{Strictness signatures and types}
356 %*                                                                      *
357 %************************************************************************
358
359 \begin{code}
360 mkSigTy :: CoreExpr -> DmdType -> (DmdEnv, StrictSig)
361 -- Take a DmdType and turn it into a StrictSig
362 mkSigTy rhs (DmdType fv dmds res) 
363   = (lazy_fv, mkStrictSig dmd_ty)
364   where
365     dmd_ty = DmdType strict_fv final_dmds res'
366
367     lazy_fv   = filterUFM (not . isStrictDmd) fv
368     strict_fv = filterUFM isStrictDmd         fv
369         -- We put the strict FVs in the DmdType of the Id, so 
370         -- that at its call sites we unleash demands on its strict fvs.
371         -- An example is 'roll' in imaginary/wheel-sieve2
372         -- Something like this:
373         --      roll x = letrec 
374         --                   go y = if ... then roll (x-1) else x+1
375         --               in 
376         --               go ms
377         -- We want to see that roll is strict in x, which is because
378         -- go is called.   So we put the DmdEnv for x in go's DmdType.
379         --
380         -- Another example:
381         --      f :: Int -> Int -> Int
382         --      f x y = let t = x+1
383         --          h z = if z==0 then t else 
384         --                if z==1 then x+1 else
385         --                x + h (z-1)
386         --      in
387         --      h y
388         -- Calling h does indeed evaluate x, but we can only see
389         -- that if we unleash a demand on x at the call site for t.
390         --
391         -- Incidentally, here's a place where lambda-lifting h would
392         -- lose the cigar --- we couldn't see the joint strictness in t/x
393         --
394         --      ON THE OTHER HAND
395         -- We don't want to put *all* the fv's from the RHS into the
396         -- DmdType, because that makes fixpointing very slow --- the 
397         -- DmdType gets full of lazy demands that are slow to converge.
398
399     lazified_dmds = map funArgDemand dmds
400         -- Get rid of defers in the arguments
401     final_dmds = setUnpackStrategy lazified_dmds
402         -- Set the unpacking strategy
403         
404     res' = case res of
405                 RetCPR | not (exprIsValue rhs) -> TopRes
406                 other                          -> res
407         -- If the rhs is a thunk, we forget the CPR info, because
408         -- it is presumably shared (else it would have been inlined, and 
409         -- so we'd lose sharing if w/w'd it into a function.
410         --
411         --      DONE IN OLD CPR ANALYSER, BUT NOT YET HERE
412         -- Also, if the strictness analyser has figured out that it's strict,
413         -- the let-to-case transformation will happen, so again it's good.
414         -- (CPR analysis runs before the simplifier has had a chance to do
415         --  the let-to-case transform.)
416         -- This made a big difference to PrelBase.modInt, which had something like
417         --      modInt = \ x -> let r = ... -> I# v in
418         --                      ...body strict in r...
419         -- r's RHS isn't a value yet; but modInt returns r in various branches, so
420         -- if r doesn't have the CPR property then neither does modInt
421 \end{code}
422
423 The unpack strategy determines whether we'll *really* unpack the argument,
424 or whether we'll just remember its strictness.  If unpacking would give
425 rise to a *lot* of worker args, we may decide not to unpack after all.
426
427 \begin{code}
428 setUnpackStrategy :: [Demand] -> [Demand]
429 setUnpackStrategy ds
430   = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
431   where
432     go :: Int                   -- Max number of args available for sub-components of [Demand]
433        -> [Demand]
434        -> (Int, [Demand])       -- Args remaining after subcomponents of [Demand] are unpacked
435
436     go n (Seq keep cs : ds) 
437         | n' >= 0    = Seq keep cs' `cons` go n'' ds
438         | otherwise  = Eval `cons` go n ds
439         where
440           (n'',cs') = go n' cs
441           n' = n + box - non_abs_args
442           box = case keep of
443                    Keep -> 0
444                    Drop -> 1    -- Add one to the budget if we drop the top-level arg
445           non_abs_args = nonAbsentArgs cs
446                 -- Delete # of non-absent args to which we'll now be committed
447                                 
448     go n (d:ds) = d `cons` go n ds
449     go n []     = (n,[])
450
451     cons d (n,ds) = (n, d:ds)
452
453 nonAbsentArgs :: [Demand] -> Int
454 nonAbsentArgs []         = 0
455 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
456 nonAbsentArgs (d   : ds) = 1 + nonAbsentArgs ds
457 \end{code}
458
459
460 %************************************************************************
461 %*                                                                      *
462 \subsection{Strictness signatures and types}
463 %*                                                                      *
464 %************************************************************************
465
466 \begin{code}
467 splitDmdTy :: DmdType -> (Demand, DmdType)
468 -- Split off one function argument
469 -- We already have a suitable demand on all
470 -- free vars, so no need to add more!
471 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
472 splitDmdTy ty@(DmdType fv [] TopRes)      = (Lazy, ty)
473 splitDmdTy ty@(DmdType fv [] BotRes)      = (Bot,  ty)
474         -- NB: Bot not Abs
475 splitDmdTy ty@(DmdType fv [] RetCPR)      = panic "splitDmdTy"
476         -- We should not be applying a product as a function!
477 \end{code}
478
479 \begin{code}
480 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
481
482 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
483   | isTopLevel top_lvl = dmd_ty         -- Don't record top level things
484   | otherwise          = DmdType (extendVarEnv fv var dmd) ds res
485
486 addLazyFVs (DmdType fv ds res) lazy_fvs
487   = DmdType both_fv1 ds res
488   where
489     both_fv = (plusUFM_C both fv lazy_fvs)
490     both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
491         -- This modifyEnv is vital.  Consider
492         --      let f = \x -> (x,y)
493         --      in  error (f 3)
494         -- Here, y is treated as a lazy-fv of f, but we must `both` that L
495         -- demand with the bottom coming up from 'error'
496         -- 
497         -- I got a loop in the fixpointer without this, due to an interaction
498         -- with the lazy_fv filtering in mkSigTy.  Roughly, it was
499         --      letrec f n x 
500         --          = letrec g y = x `fatbar` 
501         --                         letrec h z = z + ...g...
502         --                         in h (f (n-1) x)
503         --      in ...
504         -- In the initial iteration for f, f=Bot
505         -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
506         -- is lazy.  Now consider the fixpoint iteration for g, esp the demands it
507         -- places on its free variables.  Suppose it places none.  Then the
508         --      x `fatbar` ...call to h...
509         -- will give a x->V demand for x.  That turns into a L demand for x,
510         -- which floats out of the defn for h.  Without the modifyEnv, that
511         -- L demand doesn't get both'd with the Bot coming up from the inner
512         -- call to f.  So we just get an L demand for x for g.
513         --
514         -- A better way to say this is that the lazy-fv filtering should give the
515         -- same answer as putting the lazy fv demands in the function's type.
516
517 annotateBndr :: DmdType -> Var -> (DmdType, Var)
518 -- The returned env has the var deleted
519 -- The returned var is annotated with demand info
520 -- No effect on the argument demands
521 annotateBndr dmd_ty@(DmdType fv ds res) var
522   | isTyVar var = (dmd_ty, var)
523   | otherwise   = (DmdType fv' ds res, setIdNewDemandInfo var hacked_dmd)
524   where
525     (fv', dmd) = removeFV fv var res
526     hacked_dmd | isUnLiftedType (idType var) = unliftedDemand dmd
527                | otherwise                   = dmd
528
529 annotateBndrs = mapAccumR annotateBndr
530
531 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
532 -- For lambdas we add the demand to the argument demands
533 -- Only called for Ids
534   = ASSERT( isId id )
535     (DmdType fv' (hacked_dmd:ds) res, setIdNewDemandInfo id hacked_dmd)
536   where
537     (fv', dmd) = removeFV fv id res
538     hacked_dmd | isUnLiftedType (idType id) = unliftedDemand dmd
539                | otherwise                  = funArgDemand dmd
540         -- This call to funArgDemand is vital, because otherwise we label
541         -- a lambda binder with demand 'B'.  But in terms of calling
542         -- conventions that's Abs, because we don't pass it.  But
543         -- when we do a w/w split we get
544         --      fw x = (\x y:B -> ...) x (error "oops")
545         -- And then the simplifier things the 'B' is a strict demand
546         -- and evaluates the (error "oops").  Sigh
547
548 removeFV fv var res = (fv', dmd)
549                 where
550                   fv' = fv `delVarEnv` var
551                   dmd = lookupVarEnv fv var `orElse` deflt
552                   deflt | isBotRes res = Bot
553                         | otherwise    = Abs
554 \end{code}
555
556 %************************************************************************
557 %*                                                                      *
558 \subsection{Strictness signatures}
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 type SigEnv  = VarEnv (StrictSig, TopLevelFlag)
564         -- We use the SigEnv to tell us whether to
565         -- record info about a variable in the DmdEnv
566         -- We do so if it's a LocalId, but not top-level
567         --
568         -- The DmdEnv gives the demand on the free vars of the function
569         -- when it is given enough args to satisfy the strictness signature
570
571 emptySigEnv  = emptyVarEnv
572
573 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
574 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
575
576 extendSigEnvList = extendVarEnvList
577
578 dmdTransform :: SigEnv          -- The strictness environment
579              -> Id              -- The function
580              -> Demand          -- The demand on the function
581              -> DmdType         -- The demand type of the function in this context
582         -- Returned DmdEnv includes the demand on 
583         -- this function plus demand on its free variables
584
585 dmdTransform sigs var dmd
586
587 ------  DATA CONSTRUCTOR
588   | isDataConId var,            -- Data constructor
589     Seq k ds <- res_dmd         -- and the demand looks inside its fields
590   = let 
591         StrictSig dmd_ty    = idNewStrictness var       -- It must have a strictness sig
592         DmdType _ _ con_res = dmd_ty
593         arity               = idArity var
594     in
595     if arity == call_depth then         -- Saturated, so unleash the demand
596         let 
597                 -- ds can be empty, when we are just seq'ing the thing
598                 -- If so we must make up a suitable bunch of demands
599            dmd_ds | null ds   = replicate arity Abs
600                   | otherwise = ASSERT( length ds == arity ) ds
601
602            arg_ds = case k of
603                         Keep  -> bothLazy_s dmd_ds
604                         Drop  -> dmd_ds
605                         Defer -> pprTrace "dmdTransform: surprising!" (ppr var) 
606                                         -- I don't think this can happen
607                                  dmd_ds
608                 -- Important!  If we Keep the constructor application, then
609                 -- we need the demands the constructor places (always lazy)
610                 -- If not, we don't need to.  For example:
611                 --      f p@(x,y) = (p,y)       -- S(AL)
612                 --      g a b     = f (a,b)
613                 -- It's vital that we don't calculate Absent for a!
614         in
615         mkDmdType emptyDmdEnv arg_ds con_res
616                 -- Must remember whether it's a product, hence con_res, not TopRes
617     else
618         topDmdType
619
620 ------  IMPORTED FUNCTION
621   | isGlobalId var,             -- Imported function
622     let StrictSig dmd_ty = getNewStrictness var
623   = if dmdTypeDepth dmd_ty <= call_depth then   -- Saturated, so unleash the demand
624         dmd_ty
625     else
626         topDmdType
627
628 ------  LOCAL LET/REC BOUND THING
629   | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
630   = let
631         fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty 
632               | otherwise                         = deferType dmd_ty
633         -- NB: it's important to use deferType, and not just return topDmdType
634         -- Consider     let { f x y = p + x } in f 1
635         -- The application isn't saturated, but we must nevertheless propagate 
636         --      a lazy demand for p!  
637     in
638     addVarDmd top_lvl fn_ty var dmd
639
640 ------  LOCAL NON-LET/REC BOUND THING
641   | otherwise                   -- Default case
642   = unitVarDmd var dmd
643
644   where
645     (call_depth, res_dmd) = splitCallDmd dmd
646 \end{code}
647
648
649 %************************************************************************
650 %*                                                                      *
651 \subsection{Demands}
652 %*                                                                      *
653 %************************************************************************
654
655 \begin{code}
656 splitCallDmd :: Demand -> (Int, Demand)
657 splitCallDmd (Call d) = case splitCallDmd d of
658                           (n, r) -> (n+1, r)
659 splitCallDmd d        = (0, d)
660
661 vanillaCall :: Arity -> Demand
662 vanillaCall 0 = Eval
663 vanillaCall n = Call (vanillaCall (n-1))
664
665 deferType :: DmdType -> DmdType
666 deferType (DmdType fv _ _) = DmdType (mapVarEnv defer fv) [] TopRes
667         -- Notice that we throw away info about both arguments and results
668         -- For example,   f = let ... in \x -> x
669         -- We don't want to get a stricness type V->T for f.
670         -- Peter??
671
672 ---------------
673 bothLazy :: Demand -> Demand
674 bothLazy   = both Lazy
675 bothLazy_s :: [Demand] -> [Demand]
676 bothLazy_s = map bothLazy
677
678 funArgDemand :: Demand -> Demand
679 -- The 'Defer' demands are just Lazy at function boundaries
680 -- Ugly!  Ask John how to improve it.
681 funArgDemand (Seq Defer ds) = Lazy
682 funArgDemand (Seq k     ds) = Seq k (map funArgDemand ds)
683 funArgDemand Err            = Eval      -- Args passed to a bottoming function
684 funArgDemand Bot            = Abs       -- Don't pass args that are consumed by bottom/err
685 funArgDemand d              = d
686
687 unliftedDemand :: Demand -> Demand
688 -- Same idea, but for unlifted types the domain is much simpler:
689 -- Either we use it (Lazy) or we don't (Abs)
690 unliftedDemand Bot   = Abs
691 unliftedDemand Abs   = Abs
692 unliftedDemand other = Lazy
693 \end{code}
694
695 \begin{code}
696 betterStrictness :: StrictSig -> StrictSig -> Bool
697 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
698
699 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
700
701 betterDemand :: Demand -> Demand -> Bool
702 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
703 betterDemand d1 d2 = (d1 `lub` d2) == d2
704
705 squashDmdEnv (StrictSig (DmdType fv ds res)) = StrictSig (DmdType emptyDmdEnv ds res)
706 \end{code}
707
708 \begin{code}
709 -------------------------
710 -- Consider (if x then y else []) with demand V
711 -- Then the first branch gives {y->V} and the second
712 -- *implicitly* has {y->A}.  So we must put {y->(V `lub` A)}
713 -- in the result env.
714 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
715   = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2)
716   where
717     lub_fv  = plusUFM_C lub fv1 fv2
718     lub_fv1 = modifyEnv (not (isBotRes r1)) defer fv2 fv1 lub_fv
719     lub_fv2 = modifyEnv (not (isBotRes r2)) defer fv1 fv2 lub_fv1
720         -- lub is the identity for Bot
721
722 -----------------------------------
723 -- (t1 `bothType` t2) takes the argument/result info from t1,
724 -- using t2 just for its free-var info
725 -- NB: Don't forget about r2!  It might be BotRes, which is
726 --     a bottom demand on all the in-scope variables.
727 -- Peter: can this be done more neatly?
728 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
729   = DmdType both_fv2 ds1 (r1 `bothRes` r2)
730   where
731     both_fv  = plusUFM_C both fv1 fv2
732     both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
733     both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
734         -- both is the identity for Abs
735 \end{code}
736
737
738 \begin{code}
739 lubRes BotRes r      = r
740 lubRes r      BotRes = r
741 lubRes RetCPR RetCPR = RetCPR
742 lubRes r1     r2     = TopRes
743
744 -- If either diverges, the whole thing does
745 -- Otherwise take CPR info from the first
746 bothRes r1 BotRes = BotRes
747 bothRes r1 r2     = r1
748 \end{code}
749
750 \begin{code}
751 -- A Seq can have an empty list of demands, in the polymorphic case.
752 lubs [] ds2 = ds2
753 lubs ds1 [] = ds1
754 lubs ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith lub ds1 ds2
755
756 -----------------------------------
757 -- A Seq can have an empty list of demands, in the polymorphic case.
758 boths [] ds2  = ds2
759 boths ds1 []  = ds1
760 boths ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith both ds1 ds2
761 \end{code}
762
763 \begin{code}
764 modifyEnv :: Bool                       -- No-op if False
765           -> (Demand -> Demand)         -- The zapper
766           -> DmdEnv -> DmdEnv           -- Env1 and Env2
767           -> DmdEnv -> DmdEnv           -- Transform this env
768         -- Zap anything in Env1 but not in Env2
769         -- Assume: dom(env) includes dom(Env1) and dom(Env2)
770
771 modifyEnv need_to_modify zapper env1 env2 env
772   | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
773   | otherwise      = env
774   where
775     zap uniq env = addToUFM_Directly env uniq (zapper current_val)
776                  where
777                    current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
778 \end{code}
779
780
781 %************************************************************************
782 %*                                                                      *
783 \subsection{LUB and BOTH}
784 %*                                                                      *
785 %************************************************************************
786
787
788 \begin{code}
789 lub :: Demand -> Demand -> Demand
790
791 lub Bot d = d
792
793 lub Err Bot = Err 
794 lub Err Abs = Lazy      -- E.g. f x = if ... then True else error x
795 lub Err d   = d 
796
797 lub Lazy d = Lazy
798
799 lub Abs  d = defer d
800
801 lub Eval Abs                           = Lazy
802 lub Eval Lazy                          = Lazy
803 lub Eval (Seq Drop ds) | not (null ds) = Seq Drop [Lazy | d <- ds]
804 lub Eval d                             = Eval
805         -- For the Seq case, consier
806         --      f n []     = n
807         --      f n (x:xs) = f (n+x) xs
808         -- Here we want to do better than just V for n.  It's
809         -- unboxed in the (x:xs) case, and we might be prepared to
810         -- rebox it in the [] case.
811         -- But if we don't use *any* of the components, give up
812         -- and revert to V
813
814 lub (Call d1) (Call d2) = Call (lub d1 d2)
815 lub d1@(Call _) d2      = d2 `lub` d1
816
817 lub (Seq k1 ds1) (Seq k2 ds2)
818   = Seq (k1 `lub_keep` k2) (lub_ds k1 ds1 k2 ds2)
819   where
820         ------------------
821     lub_ds Keep ds1 Keep ds2                 = ds1 `lubs` ds2
822     lub_ds Keep ds1 non_keep ds2 | null ds1  = [Lazy | d <- ds2]
823                                  | otherwise = bothLazy_s ds1 `lubs` ds2
824
825     lub_ds non_keep ds1 Keep ds2 | null ds2  = [Lazy | d <- ds1]
826                                  | otherwise = ds1 `lubs` bothLazy_s ds2
827
828     lub_ds k1 ds1 k2 ds2                     = ds1 `lubs` ds2
829
830         ------------------
831     lub_keep Keep k     = k
832
833     lub_keep Drop Defer = Defer
834     lub_keep Drop k     = Drop
835
836     lub_keep Defer k    = Defer
837
838 lub d1@(Seq _ _) d2 = d2 `lub` d1
839
840 ---------------
841 both :: Demand -> Demand -> Demand
842
843 both Bot Bot = Bot
844 both Bot Abs = Bot
845 both Bot d   = Err
846
847 both Err d = Err
848
849 both Abs d   = d
850
851 both Lazy Bot            = Err
852 both Lazy Err            = Err
853 both Lazy Eval           = Eval
854 both Lazy (Call d)       = Call d
855 both Lazy (Seq Defer ds) = Lazy
856 both Lazy (Seq k ds)     = Seq Keep ds
857 both Lazy d              = Lazy
858
859 -- For the (Eval `both` Bot) case, consider
860 --      f x = error x
861 -- From 'error' itself we get demand Bot on x
862 -- From the arg demand on x we get Eval
863 -- So we want Eval `both` Bot to be Err.
864 -- That's what Err is *for*
865 both Eval Bot        = Err
866 both Eval Err        = Err
867 both Eval (Seq k ds) = Seq Keep ds
868 both Eval d          = Eval
869
870 both (Call d1)   (Call d2) = Call (d1 `both` d2)
871 both d1@(Call _) d2        = d2 `both` d1
872
873 both (Seq k1 ds1) (Seq k2 ds2)
874   = Seq (k1 `both_keep` k2) (both_ds k1 ds1 k2 ds2)
875   where
876         ----------------
877     both_keep Keep k2 = Keep
878
879     both_keep Drop Keep = Keep
880     both_keep Drop k2   = Drop
881
882     both_keep Defer k2  = k2
883
884         ----------------
885     both_ds Defer ds1 Defer     ds2 = ds1 `boths` ds2
886     both_ds Defer ds1 non_defer ds2 = map defer ds1 `boths` ds2
887
888     both_ds non_defer ds1 Defer ds2 = ds1 `boths` map defer ds2
889
890     both_ds k1 ds1 k2 ds2           = ds1 `boths` ds2
891
892 both d1@(Seq _ _) d2 = d2 `both` d1
893 \end{code}
894
895
896 %************************************************************************
897 %*                                                                      *
898 \subsection{Miscellaneous
899 %*                                                                      *
900 %************************************************************************
901
902
903 \begin{code}
904 get_changes binds = vcat (map get_changes_bind binds)
905
906 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
907 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
908
909 get_changes_pr (id,rhs) 
910   = get_changes_var id $$ get_changes_expr rhs
911
912 get_changes_var var
913   | isId var  = get_changes_str var $$ get_changes_dmd var
914   | otherwise = empty
915
916 get_changes_expr (Type t)     = empty
917 get_changes_expr (Var v)      = empty
918 get_changes_expr (Lit l)      = empty
919 get_changes_expr (Note n e)   = get_changes_expr e
920 get_changes_expr (App e1 e2)  = get_changes_expr e1 $$ get_changes_expr e2
921 get_changes_expr (Lam b e)    = {- get_changes_var b $$ -} get_changes_expr e
922 get_changes_expr (Let b e)    = get_changes_bind b $$ get_changes_expr e
923 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
924
925 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
926
927 get_changes_str id
928   | new_better && old_better = empty
929   | new_better               = message "BETTER"
930   | old_better               = message "WORSE"
931   | otherwise                = message "INCOMPARABLE" 
932   where
933     message word = text word <+> text "strictness for" <+> ppr id <+> info
934     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
935     new = squashDmdEnv (idNewStrictness id)     -- Don't report diffs in the env
936     old = newStrictnessFromOld id
937     old_better = old `betterStrictness` new
938     new_better = new `betterStrictness` old
939
940 get_changes_dmd id
941   | isUnLiftedType (idType id) = empty  -- Not useful
942   | new_better && old_better = empty
943   | new_better               = message "BETTER"
944   | old_better               = message "WORSE"
945   | otherwise                = message "INCOMPARABLE" 
946   where
947     message word = text word <+> text "demand for" <+> ppr id <+> info
948     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
949     new = funArgDemand (idNewDemandInfo id)     -- FunArgDemand to avoid spurious improvements
950     old = newDemand (idDemandInfo id)
951     new_better = new `betterDemand` old 
952     old_better = old `betterDemand` new
953 \end{code}