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