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