127fa7800faf1527875b7e648d53fd7081098998
[ghc-hetmet.git] / 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 DynFlags         ( DynFlags, DynFlag(..) )
17 import StaticFlags      ( opt_MaxWorkerArgs )
18 import NewDemand        -- All of it
19 import CoreSyn
20 import PprCore  
21 import CoreUtils        ( exprIsHNF, exprIsTrivial, exprArity )
22 import DataCon          ( dataConTyCon )
23 import TyCon            ( isProductTyCon, isRecursiveTyCon )
24 import Id               ( Id, idType, idInlinePragma,
25                           isDataConWorkId, isGlobalId, idArity,
26 #ifdef OLD_STRICTNESS
27                           idDemandInfo,  idStrictness, idCprInfo, idName,
28 #endif
29                           idNewStrictness, idNewStrictness_maybe,
30                           setIdNewStrictness, idNewDemandInfo,
31                           idNewDemandInfo_maybe,
32                           setIdNewDemandInfo
33                         )
34 #ifdef OLD_STRICTNESS
35 import IdInfo           ( newStrictnessFromOld, newDemand )
36 #endif
37 import Var              ( Var )
38 import VarEnv
39 import TysWiredIn       ( unboxedPairDataCon )
40 import TysPrim          ( realWorldStatePrimTy )
41 import UniqFM           ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
42                           keysUFM, minusUFM, ufmToList, filterUFM )
43 import Type             ( isUnLiftedType, coreEqType )
44 import CoreLint         ( showPass, endPass )
45 import Util             ( mapAndUnzip, mapAccumL, mapAccumR, lengthIs )
46 import BasicTypes       ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
47                           RecFlag(..), isRec )
48 import Maybes           ( orElse, expectJust )
49 import Outputable
50 \end{code}
51
52 To think about
53
54 * set a noinline pragma on bottoming Ids
55
56 * Consider f x = x+1 `fatbar` error (show x)
57   We'd like to unbox x, even if that means reboxing it in the error case.
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Top level stuff}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
68 dmdAnalPgm dflags binds
69   = do {
70         showPass dflags "Demand analysis" ;
71         let { binds_plus_dmds = do_prog binds } ;
72
73         endPass dflags "Demand analysis" 
74                 Opt_D_dump_stranal binds_plus_dmds ;
75 #ifdef OLD_STRICTNESS
76         -- Only if OLD_STRICTNESS is on, because only then is the old
77         -- strictness analyser run
78         let { dmd_changes = get_changes binds_plus_dmds } ;
79         printDump (text "Changes in demands" $$ dmd_changes) ;
80 #endif
81         return binds_plus_dmds
82     }
83   where
84     do_prog :: [CoreBind] -> [CoreBind]
85     do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
86
87 dmdAnalTopBind :: SigEnv
88                -> CoreBind 
89                -> (SigEnv, CoreBind)
90 dmdAnalTopBind sigs (NonRec id rhs)
91   = let
92         (    _, _, (_,   rhs1)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs)
93         (sigs2, _, (id2, rhs2)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs1)
94                 -- Do two passes to improve CPR information
95                 -- See comments with ignore_cpr_info in mk_sig_ty
96                 -- and with extendSigsWithLam
97     in
98     (sigs2, NonRec id2 rhs2)    
99
100 dmdAnalTopBind sigs (Rec pairs)
101   = let
102         (sigs', _, pairs')  = dmdFix TopLevel sigs pairs
103                 -- We get two iterations automatically
104                 -- c.f. the NonRec case above
105     in
106     (sigs', Rec pairs')
107 \end{code}
108
109 \begin{code}
110 dmdAnalTopRhs :: CoreExpr -> (StrictSig, CoreExpr)
111 -- Analyse the RHS and return
112 --      a) appropriate strictness info
113 --      b) the unfolding (decorated with stricntess info)
114 dmdAnalTopRhs rhs
115   = (sig, rhs2)
116   where
117     call_dmd       = vanillaCall (exprArity rhs)
118     (_,      rhs1) = dmdAnal emptySigEnv call_dmd rhs
119     (rhs_ty, rhs2) = dmdAnal emptySigEnv call_dmd rhs1
120     sig            = mkTopSigTy rhs rhs_ty
121         -- Do two passes; see notes with extendSigsWithLam
122         -- Otherwise we get bogus CPR info for constructors like
123         --      newtype T a = MkT a
124         -- The constructor looks like (\x::T a -> x), modulo the coerce
125         -- extendSigsWithLam will optimistically give x a CPR tag the 
126         -- first time, which is wrong in the end.
127 \end{code}
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection{The analyser itself}        
132 %*                                                                      *
133 %************************************************************************
134
135 \begin{code}
136 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
137
138 dmdAnal sigs Abs  e = (topDmdType, e)
139
140 dmdAnal sigs dmd e 
141   | not (isStrictDmd dmd)
142   = let 
143         (res_ty, e') = dmdAnal sigs evalDmd e
144     in
145     (deferType res_ty, e')
146         -- It's important not to analyse e with a lazy demand because
147         -- a) When we encounter   case s of (a,b) -> 
148         --      we demand s with U(d1d2)... but if the overall demand is lazy
149         --      that is wrong, and we'd need to reduce the demand on s,
150         --      which is inconvenient
151         -- b) More important, consider
152         --      f (let x = R in x+x), where f is lazy
153         --    We still want to mark x as demanded, because it will be when we
154         --    enter the let.  If we analyse f's arg with a Lazy demand, we'll
155         --    just mark x as Lazy
156         -- c) The application rule wouldn't be right either
157         --    Evaluating (f x) in a L demand does *not* cause
158         --    evaluation of f in a C(L) demand!
159
160
161 dmdAnal sigs dmd (Lit lit)
162   = (topDmdType, Lit lit)
163
164 dmdAnal sigs dmd (Var var)
165   = (dmdTransform sigs var dmd, Var var)
166
167 dmdAnal sigs dmd (Note n e)
168   = (dmd_ty, Note n e')
169   where
170     (dmd_ty, e') = dmdAnal sigs dmd' e  
171     dmd' = case n of
172              Coerce _ _ -> evalDmd  -- This coerce usually arises from a recursive
173              other      -> dmd      -- newtype, and we don't want to look inside them
174                                     -- for exactly the same reason that we don't look
175                                     -- inside recursive products -- we might not reach
176                                     -- a fixpoint.  So revert to a vanilla Eval demand
177
178 dmdAnal sigs dmd (App fun (Type ty))
179   = (fun_ty, App fun' (Type ty))
180   where
181     (fun_ty, fun') = dmdAnal sigs dmd fun
182
183 -- Lots of the other code is there to make this
184 -- beautiful, compositional, application rule :-)
185 dmdAnal sigs dmd e@(App fun arg)        -- Non-type arguments
186   = let                         -- [Type arg handled above]
187         (fun_ty, fun')    = dmdAnal sigs (Call dmd) fun
188         (arg_ty, arg')    = dmdAnal sigs arg_dmd arg
189         (arg_dmd, res_ty) = splitDmdTy fun_ty
190     in
191     (res_ty `bothType` arg_ty, App fun' arg')
192
193 dmdAnal sigs dmd (Lam var body)
194   | isTyVar var
195   = let   
196         (body_ty, body') = dmdAnal sigs dmd body
197     in
198     (body_ty, Lam var body')
199
200   | Call body_dmd <- dmd        -- A call demand: good!
201   = let 
202         sigs'            = extendSigsWithLam sigs var
203         (body_ty, body') = dmdAnal sigs' body_dmd body
204         (lam_ty, var')   = annotateLamIdBndr body_ty var
205     in
206     (lam_ty, Lam var' body')
207
208   | otherwise   -- Not enough demand on the lambda; but do the body
209   = let         -- anyway to annotate it and gather free var info
210         (body_ty, body') = dmdAnal sigs evalDmd body
211         (lam_ty, var')   = annotateLamIdBndr body_ty var
212     in
213     (deferType lam_ty, Lam var' body')
214
215 dmdAnal sigs dmd (Case scrut case_bndr ty [alt@(DataAlt dc,bndrs,rhs)])
216   | let tycon = dataConTyCon dc,
217     isProductTyCon tycon,
218     not (isRecursiveTyCon tycon)
219   = let
220         sigs_alt              = extendSigEnv NotTopLevel sigs case_bndr case_bndr_sig
221         (alt_ty, alt')        = dmdAnalAlt sigs_alt dmd alt
222         (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
223         (_, bndrs', _)        = alt'
224         case_bndr_sig         = cprSig
225                 -- Inside the alternative, the case binder has the CPR property.
226                 -- Meaning that a case on it will successfully cancel.
227                 -- Example:
228                 --      f True  x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
229                 --      f False x = I# 3
230                 --      
231                 -- We want f to have the CPR property:
232                 --      f b x = case fw b x of { r -> I# r }
233                 --      fw True  x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
234                 --      fw False x = 3
235
236         -- Figure out whether the demand on the case binder is used, and use
237         -- that to set the scrut_dmd.  This is utterly essential.
238         -- Consider     f x = case x of y { (a,b) -> k y a }
239         -- If we just take scrut_demand = U(L,A), then we won't pass x to the
240         -- worker, so the worker will rebuild 
241         --      x = (a, absent-error)
242         -- and that'll crash.
243         -- So at one stage I had:
244         --      dead_case_bndr           = isAbsentDmd (idNewDemandInfo case_bndr')
245         --      keepity | dead_case_bndr = Drop
246         --              | otherwise      = Keep         
247         --
248         -- But then consider
249         --      case x of y { (a,b) -> h y + a }
250         -- where h : U(LL) -> T
251         -- The above code would compute a Keep for x, since y is not Abs, which is silly
252         -- The insight is, of course, that a demand on y is a demand on the
253         -- scrutinee, so we need to `both` it with the scrut demand
254
255         scrut_dmd          = Eval (Prod [idNewDemandInfo b | b <- bndrs', isId b])
256                                    `both`
257                              idNewDemandInfo case_bndr'
258
259         (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut
260     in
261     (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' ty [alt'])
262
263 dmdAnal sigs dmd (Case scrut case_bndr ty alts)
264   = let
265         (alt_tys, alts')        = mapAndUnzip (dmdAnalAlt sigs dmd) alts
266         (scrut_ty, scrut')      = dmdAnal sigs evalDmd scrut
267         (alt_ty, case_bndr')    = annotateBndr (foldr1 lubType alt_tys) case_bndr
268     in
269 --    pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
270     (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' ty alts')
271
272 dmdAnal sigs dmd (Let (NonRec id rhs) body) 
273   = let
274         (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs NotTopLevel NonRecursive sigs (id, rhs)
275         (body_ty, body')              = dmdAnal sigs' dmd body
276         (body_ty1, id2)               = annotateBndr body_ty id1
277         body_ty2                      = addLazyFVs body_ty1 lazy_fv
278     in
279         -- If the actual demand is better than the vanilla call
280         -- demand, you might think that we might do better to re-analyse 
281         -- the RHS with the stronger demand.
282         -- But (a) That seldom happens, because it means that *every* path in 
283         --         the body of the let has to use that stronger demand
284         -- (b) It often happens temporarily in when fixpointing, because
285         --     the recursive function at first seems to place a massive demand.
286         --     But we don't want to go to extra work when the function will
287         --     probably iterate to something less demanding.  
288         -- In practice, all the times the actual demand on id2 is more than
289         -- the vanilla call demand seem to be due to (b).  So we don't
290         -- bother to re-analyse the RHS.
291     (body_ty2, Let (NonRec id2 rhs') body')    
292
293 dmdAnal sigs dmd (Let (Rec pairs) body) 
294   = let
295         bndrs                    = map fst pairs
296         (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
297         (body_ty, body')         = dmdAnal sigs' dmd body
298         body_ty1                 = addLazyFVs body_ty lazy_fv
299     in
300     sigs' `seq` body_ty `seq`
301     let
302         (body_ty2, _) = annotateBndrs body_ty1 bndrs
303                 -- Don't bother to add demand info to recursive
304                 -- binders as annotateBndr does; 
305                 -- being recursive, we can't treat them strictly.
306                 -- But we do need to remove the binders from the result demand env
307     in
308     (body_ty2,  Let (Rec pairs') body')
309
310
311 dmdAnalAlt sigs dmd (con,bndrs,rhs) 
312   = let 
313         (rhs_ty, rhs')   = dmdAnal sigs dmd rhs
314         (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
315         final_alt_ty | io_hack_reqd = alt_ty `lubType` topDmdType
316                      | otherwise    = alt_ty
317
318         -- There's a hack here for I/O operations.  Consider
319         --      case foo x s of { (# s, r #) -> y }
320         -- Is this strict in 'y'.  Normally yes, but what if 'foo' is an I/O
321         -- operation that simply terminates the program (not in an erroneous way)?
322         -- In that case we should not evaluate y before the call to 'foo'.
323         -- Hackish solution: spot the IO-like situation and add a virtual branch,
324         -- as if we had
325         --      case foo x s of 
326         --         (# s, r #) -> y 
327         --         other      -> return ()
328         -- So the 'y' isn't necessarily going to be evaluated
329         --
330         -- A more complete example where this shows up is:
331         --      do { let len = <expensive> ;
332         --         ; when (...) (exitWith ExitSuccess)
333         --         ; print len }
334
335         io_hack_reqd = con == DataAlt unboxedPairDataCon &&
336                        idType (head bndrs) `coreEqType` realWorldStatePrimTy
337     in  
338     (final_alt_ty, (con, bndrs', rhs'))
339 \end{code}
340
341 %************************************************************************
342 %*                                                                      *
343 \subsection{Bindings}
344 %*                                                                      *
345 %************************************************************************
346
347 \begin{code}
348 dmdFix :: TopLevelFlag
349        -> SigEnv                -- Does not include bindings for this binding
350        -> [(Id,CoreExpr)]
351        -> (SigEnv, DmdEnv,
352            [(Id,CoreExpr)])     -- Binders annotated with stricness info
353
354 dmdFix top_lvl sigs orig_pairs
355   = loop 1 initial_sigs orig_pairs
356   where
357     bndrs        = map fst orig_pairs
358     initial_sigs = extendSigEnvList sigs [(id, (initialSig id, top_lvl)) | id <- bndrs]
359     
360     loop :: Int
361          -> SigEnv                      -- Already contains the current sigs
362          -> [(Id,CoreExpr)]             
363          -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
364     loop n sigs pairs
365       | found_fixpoint
366       = (sigs', lazy_fv, pairs')
367                 -- Note: use pairs', not pairs.   pairs' is the result of 
368                 -- processing the RHSs with sigs (= sigs'), whereas pairs 
369                 -- is the result of processing the RHSs with the *previous* 
370                 -- iteration of sigs.
371
372       | n >= 10  = pprTrace "dmdFix loop" (ppr n <+> (vcat 
373                                 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
374                                   text "env:" <+> ppr (ufmToList sigs),
375                                   text "binds:" <+> pprCoreBinding (Rec pairs)]))
376                               (emptySigEnv, lazy_fv, orig_pairs)        -- Safe output
377                         -- The lazy_fv part is really important!  orig_pairs has no strictness
378                         -- info, including nothing about free vars.  But if we have
379                         --      letrec f = ....y..... in ...f...
380                         -- where 'y' is free in f, we must record that y is mentioned, 
381                         -- otherwise y will get recorded as absent altogether
382
383       | otherwise    = loop (n+1) sigs' pairs'
384       where
385         found_fixpoint = all (same_sig sigs sigs') bndrs 
386                 -- Use the new signature to do the next pair
387                 -- The occurrence analyser has arranged them in a good order
388                 -- so this can significantly reduce the number of iterations needed
389         ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
390         
391     my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
392         = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
393           -- (new_sig `seq` 
394           --    pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' ) 
395           ((sigs', lazy_fv'), pair')
396           --     )
397         where
398           (sigs', lazy_fv1, pair') = dmdAnalRhs top_lvl Recursive sigs (id,rhs)
399           lazy_fv'                 = plusUFM_C both lazy_fv lazy_fv1   
400           -- old_sig               = lookup sigs id
401           -- new_sig               = lookup sigs' id
402            
403     same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
404     lookup sigs var = case lookupVarEnv sigs var of
405                         Just (sig,_) -> sig
406
407         -- Get an initial strictness signature from the Id
408         -- itself.  That way we make use of earlier iterations
409         -- of the fixpoint algorithm.  (Cunning plan.)
410         -- Note that the cunning plan extends to the DmdEnv too,
411         -- since it is part of the strictness signature
412 initialSig id = idNewStrictness_maybe id `orElse` botSig
413
414 dmdAnalRhs :: TopLevelFlag -> RecFlag
415         -> SigEnv -> (Id, CoreExpr)
416         -> (SigEnv,  DmdEnv, (Id, CoreExpr))
417 -- Process the RHS of the binding, add the strictness signature
418 -- to the Id, and augment the environment with the signature as well.
419
420 dmdAnalRhs top_lvl rec_flag sigs (id, rhs)
421  = (sigs', lazy_fv, (id', rhs'))
422  where
423   arity              = idArity id   -- The idArity should be up to date
424                                     -- The simplifier was run just beforehand
425   (rhs_dmd_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
426   (lazy_fv, sig_ty)  = WARN( arity /= dmdTypeDepth rhs_dmd_ty && not (exprIsTrivial rhs), ppr id )
427                                 -- The RHS can be eta-reduced to just a variable, 
428                                 -- in which case we should not complain. 
429                        mkSigTy top_lvl rec_flag id rhs rhs_dmd_ty
430   id'                = id `setIdNewStrictness` sig_ty
431   sigs'              = extendSigEnv top_lvl sigs id sig_ty
432 \end{code}
433
434 %************************************************************************
435 %*                                                                      *
436 \subsection{Strictness signatures and types}
437 %*                                                                      *
438 %************************************************************************
439
440 \begin{code}
441 mkTopSigTy :: CoreExpr -> DmdType -> StrictSig
442         -- Take a DmdType and turn it into a StrictSig
443         -- NB: not used for never-inline things; hence False
444 mkTopSigTy rhs dmd_ty = snd (mk_sig_ty False False rhs dmd_ty)
445
446 mkSigTy :: TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
447 mkSigTy top_lvl rec_flag id rhs dmd_ty 
448   = mk_sig_ty never_inline thunk_cpr_ok rhs dmd_ty
449   where
450     never_inline = isNeverActive (idInlinePragma id)
451     maybe_id_dmd = idNewDemandInfo_maybe id
452         -- Is Nothing the first time round
453
454     thunk_cpr_ok
455         | isTopLevel top_lvl       = False      -- Top level things don't get
456                                                 -- their demandInfo set at all
457         | isRec rec_flag           = False      -- Ditto recursive things
458         | Just dmd <- maybe_id_dmd = isStrictDmd dmd
459         | otherwise                = True       -- Optimistic, first time round
460                                                 -- See notes below
461 \end{code}
462
463 The thunk_cpr_ok stuff [CPR-AND-STRICTNESS]
464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
465 If the rhs is a thunk, we usually forget the CPR info, because
466 it is presumably shared (else it would have been inlined, and 
467 so we'd lose sharing if w/w'd it into a function.
468
469 However, if the strictness analyser has figured out (in a previous 
470 iteration) that it's strict, then we DON'T need to forget the CPR info.
471 Instead we can retain the CPR info and do the thunk-splitting transform 
472 (see WorkWrap.splitThunk).
473
474 This made a big difference to PrelBase.modInt, which had something like
475         modInt = \ x -> let r = ... -> I# v in
476                         ...body strict in r...
477 r's RHS isn't a value yet; but modInt returns r in various branches, so
478 if r doesn't have the CPR property then neither does modInt
479 Another case I found in practice (in Complex.magnitude), looks like this:
480                 let k = if ... then I# a else I# b
481                 in ... body strict in k ....
482 (For this example, it doesn't matter whether k is returned as part of
483 the overall result; but it does matter that k's RHS has the CPR property.)  
484 Left to itself, the simplifier will make a join point thus:
485                 let $j k = ...body strict in k...
486                 if ... then $j (I# a) else $j (I# b)
487 With thunk-splitting, we get instead
488                 let $j x = let k = I#x in ...body strict in k...
489                 in if ... then $j a else $j b
490 This is much better; there's a good chance the I# won't get allocated.
491
492 The difficulty with this is that we need the strictness type to
493 look at the body... but we now need the body to calculate the demand
494 on the variable, so we can decide whether its strictness type should
495 have a CPR in it or not.  Simple solution: 
496         a) use strictness info from the previous iteration
497         b) make sure we do at least 2 iterations, by doing a second
498            round for top-level non-recs.  Top level recs will get at
499            least 2 iterations except for totally-bottom functions
500            which aren't very interesting anyway.
501
502 NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
503
504 The Nothing case in thunk_cpr_ok [CPR-AND-STRICTNESS]
505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506 Demand info now has a 'Nothing' state, just like strictness info.
507 The analysis works from 'dangerous' towards a 'safe' state; so we 
508 start with botSig for 'Nothing' strictness infos, and we start with
509 "yes, it's demanded" for 'Nothing' in the demand info.  The
510 fixpoint iteration will sort it all out.
511
512 We can't start with 'not-demanded' because then consider
513         f x = let 
514                   t = ... I# x
515               in
516               if ... then t else I# y else f x'
517
518 In the first iteration we'd have no demand info for x, so assume
519 not-demanded; then we'd get TopRes for f's CPR info.  Next iteration
520 we'd see that t was demanded, and so give it the CPR property, but by
521 now f has TopRes, so it will stay TopRes.  Instead, with the Nothing
522 setting the first time round, we say 'yes t is demanded' the first
523 time.
524
525 However, this does mean that for non-recursive bindings we must
526 iterate twice to be sure of not getting over-optimistic CPR info,
527 in the case where t turns out to be not-demanded.  This is handled
528 by dmdAnalTopBind.
529
530
531 \begin{code}
532 mk_sig_ty never_inline thunk_cpr_ok rhs (DmdType fv dmds res) 
533   = (lazy_fv, mkStrictSig dmd_ty)
534   where
535     dmd_ty = DmdType strict_fv final_dmds res'
536
537     lazy_fv   = filterUFM (not . isStrictDmd) fv
538     strict_fv = filterUFM isStrictDmd         fv
539         -- We put the strict FVs in the DmdType of the Id, so 
540         -- that at its call sites we unleash demands on its strict fvs.
541         -- An example is 'roll' in imaginary/wheel-sieve2
542         -- Something like this:
543         --      roll x = letrec 
544         --                   go y = if ... then roll (x-1) else x+1
545         --               in 
546         --               go ms
547         -- We want to see that roll is strict in x, which is because
548         -- go is called.   So we put the DmdEnv for x in go's DmdType.
549         --
550         -- Another example:
551         --      f :: Int -> Int -> Int
552         --      f x y = let t = x+1
553         --          h z = if z==0 then t else 
554         --                if z==1 then x+1 else
555         --                x + h (z-1)
556         --      in
557         --      h y
558         -- Calling h does indeed evaluate x, but we can only see
559         -- that if we unleash a demand on x at the call site for t.
560         --
561         -- Incidentally, here's a place where lambda-lifting h would
562         -- lose the cigar --- we couldn't see the joint strictness in t/x
563         --
564         --      ON THE OTHER HAND
565         -- We don't want to put *all* the fv's from the RHS into the
566         -- DmdType, because that makes fixpointing very slow --- the 
567         -- DmdType gets full of lazy demands that are slow to converge.
568
569     final_dmds = setUnpackStrategy dmds
570         -- Set the unpacking strategy
571         
572     res' = case res of
573                 RetCPR | ignore_cpr_info -> TopRes
574                 other                    -> res
575     ignore_cpr_info = not (exprIsHNF rhs || thunk_cpr_ok)
576 \end{code}
577
578 The unpack strategy determines whether we'll *really* unpack the argument,
579 or whether we'll just remember its strictness.  If unpacking would give
580 rise to a *lot* of worker args, we may decide not to unpack after all.
581
582 \begin{code}
583 setUnpackStrategy :: [Demand] -> [Demand]
584 setUnpackStrategy ds
585   = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
586   where
587     go :: Int                   -- Max number of args available for sub-components of [Demand]
588        -> [Demand]
589        -> (Int, [Demand])       -- Args remaining after subcomponents of [Demand] are unpacked
590
591     go n (Eval (Prod cs) : ds) 
592         | n' >= 0   = Eval (Prod cs') `cons` go n'' ds
593         | otherwise = Box (Eval (Prod cs)) `cons` go n ds
594         where
595           (n'',cs') = go n' cs
596           n' = n + 1 - non_abs_args
597                 -- Add one to the budget 'cos we drop the top-level arg
598           non_abs_args = nonAbsentArgs cs
599                 -- Delete # of non-absent args to which we'll now be committed
600                                 
601     go n (d:ds) = d `cons` go n ds
602     go n []     = (n,[])
603
604     cons d (n,ds) = (n, d:ds)
605
606 nonAbsentArgs :: [Demand] -> Int
607 nonAbsentArgs []         = 0
608 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
609 nonAbsentArgs (d   : ds) = 1 + nonAbsentArgs ds
610 \end{code}
611
612
613 %************************************************************************
614 %*                                                                      *
615 \subsection{Strictness signatures and types}
616 %*                                                                      *
617 %************************************************************************
618
619 \begin{code}
620 splitDmdTy :: DmdType -> (Demand, DmdType)
621 -- Split off one function argument
622 -- We already have a suitable demand on all
623 -- free vars, so no need to add more!
624 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
625 splitDmdTy ty@(DmdType fv [] res_ty)      = (resTypeArgDmd res_ty, ty)
626 \end{code}
627
628 \begin{code}
629 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
630
631 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
632   | isTopLevel top_lvl = dmd_ty         -- Don't record top level things
633   | otherwise          = DmdType (extendVarEnv fv var dmd) ds res
634
635 addLazyFVs (DmdType fv ds res) lazy_fvs
636   = DmdType both_fv1 ds res
637   where
638     both_fv = (plusUFM_C both fv lazy_fvs)
639     both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
640         -- This modifyEnv is vital.  Consider
641         --      let f = \x -> (x,y)
642         --      in  error (f 3)
643         -- Here, y is treated as a lazy-fv of f, but we must `both` that L
644         -- demand with the bottom coming up from 'error'
645         -- 
646         -- I got a loop in the fixpointer without this, due to an interaction
647         -- with the lazy_fv filtering in mkSigTy.  Roughly, it was
648         --      letrec f n x 
649         --          = letrec g y = x `fatbar` 
650         --                         letrec h z = z + ...g...
651         --                         in h (f (n-1) x)
652         --      in ...
653         -- In the initial iteration for f, f=Bot
654         -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
655         -- is lazy.  Now consider the fixpoint iteration for g, esp the demands it
656         -- places on its free variables.  Suppose it places none.  Then the
657         --      x `fatbar` ...call to h...
658         -- will give a x->V demand for x.  That turns into a L demand for x,
659         -- which floats out of the defn for h.  Without the modifyEnv, that
660         -- L demand doesn't get both'd with the Bot coming up from the inner
661         -- call to f.  So we just get an L demand for x for g.
662         --
663         -- A better way to say this is that the lazy-fv filtering should give the
664         -- same answer as putting the lazy fv demands in the function's type.
665
666 annotateBndr :: DmdType -> Var -> (DmdType, Var)
667 -- The returned env has the var deleted
668 -- The returned var is annotated with demand info
669 -- No effect on the argument demands
670 annotateBndr dmd_ty@(DmdType fv ds res) var
671   | isTyVar var = (dmd_ty, var)
672   | otherwise   = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
673   where
674     (fv', dmd) = removeFV fv var res
675
676 annotateBndrs = mapAccumR annotateBndr
677
678 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
679 -- For lambdas we add the demand to the argument demands
680 -- Only called for Ids
681   = ASSERT( isId id )
682     (DmdType fv' (hacked_dmd:ds) res, setIdNewDemandInfo id hacked_dmd)
683   where
684     (fv', dmd) = removeFV fv id res
685     hacked_dmd = argDemand dmd
686         -- This call to argDemand is vital, because otherwise we label
687         -- a lambda binder with demand 'B'.  But in terms of calling
688         -- conventions that's Abs, because we don't pass it.  But
689         -- when we do a w/w split we get
690         --      fw x = (\x y:B -> ...) x (error "oops")
691         -- And then the simplifier things the 'B' is a strict demand
692         -- and evaluates the (error "oops").  Sigh
693
694 removeFV fv id res = (fv', zapUnlifted id dmd)
695                 where
696                   fv' = fv `delVarEnv` id
697                   dmd = lookupVarEnv fv id `orElse` deflt
698                   deflt | isBotRes res = Bot
699                         | otherwise    = Abs
700
701 -- For unlifted-type variables, we are only 
702 -- interested in Bot/Abs/Box Abs
703 zapUnlifted is Bot = Bot
704 zapUnlifted id Abs = Abs
705 zapUnlifted id dmd | isUnLiftedType (idType id) = lazyDmd
706                    | otherwise                  = dmd
707 \end{code}
708
709 %************************************************************************
710 %*                                                                      *
711 \subsection{Strictness signatures}
712 %*                                                                      *
713 %************************************************************************
714
715 \begin{code}
716 type SigEnv  = VarEnv (StrictSig, TopLevelFlag)
717         -- We use the SigEnv to tell us whether to
718         -- record info about a variable in the DmdEnv
719         -- We do so if it's a LocalId, but not top-level
720         --
721         -- The DmdEnv gives the demand on the free vars of the function
722         -- when it is given enough args to satisfy the strictness signature
723
724 emptySigEnv  = emptyVarEnv
725
726 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
727 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
728
729 extendSigEnvList = extendVarEnvList
730
731 extendSigsWithLam :: SigEnv -> Id -> SigEnv
732 -- Extend the SigEnv when we meet a lambda binder
733 -- If the binder is marked demanded with a product demand, then give it a CPR 
734 -- signature, because in the likely event that this is a lambda on a fn defn 
735 -- [we only use this when the lambda is being consumed with a call demand],
736 -- it'll be w/w'd and so it will be CPR-ish.  E.g.
737 --      f = \x::(Int,Int).  if ...strict in x... then
738 --                              x
739 --                          else
740 --                              (a,b)
741 -- We want f to have the CPR property because x does, by the time f has been w/w'd
742 --
743 -- Also note that we only want to do this for something that
744 -- definitely has product type, else we may get over-optimistic 
745 -- CPR results (e.g. from \x -> x!).
746
747 extendSigsWithLam sigs id
748   = case idNewDemandInfo_maybe id of
749         Nothing               -> extendVarEnv sigs id (cprSig, NotTopLevel)
750                 -- Optimistic in the Nothing case;
751                 -- See notes [CPR-AND-STRICTNESS]
752         Just (Eval (Prod ds)) -> extendVarEnv sigs id (cprSig, NotTopLevel)
753         other                 -> sigs
754
755
756 dmdTransform :: SigEnv          -- The strictness environment
757              -> Id              -- The function
758              -> Demand          -- The demand on the function
759              -> DmdType         -- The demand type of the function in this context
760         -- Returned DmdEnv includes the demand on 
761         -- this function plus demand on its free variables
762
763 dmdTransform sigs var dmd
764
765 ------  DATA CONSTRUCTOR
766   | isDataConWorkId var         -- Data constructor
767   = let 
768         StrictSig dmd_ty    = idNewStrictness var       -- It must have a strictness sig
769         DmdType _ _ con_res = dmd_ty
770         arity               = idArity var
771     in
772     if arity == call_depth then         -- Saturated, so unleash the demand
773         let 
774                 -- Important!  If we Keep the constructor application, then
775                 -- we need the demands the constructor places (always lazy)
776                 -- If not, we don't need to.  For example:
777                 --      f p@(x,y) = (p,y)       -- S(AL)
778                 --      g a b     = f (a,b)
779                 -- It's vital that we don't calculate Absent for a!
780            dmd_ds = case res_dmd of
781                         Box (Eval ds) -> mapDmds box ds
782                         Eval ds       -> ds
783                         other         -> Poly Top
784
785                 -- ds can be empty, when we are just seq'ing the thing
786                 -- If so we must make up a suitable bunch of demands
787            arg_ds = case dmd_ds of
788                       Poly d  -> replicate arity d
789                       Prod ds -> ASSERT( ds `lengthIs` arity ) ds
790
791         in
792         mkDmdType emptyDmdEnv arg_ds con_res
793                 -- Must remember whether it's a product, hence con_res, not TopRes
794     else
795         topDmdType
796
797 ------  IMPORTED FUNCTION
798   | isGlobalId var,             -- Imported function
799     let StrictSig dmd_ty = idNewStrictness var
800   = if dmdTypeDepth dmd_ty <= call_depth then   -- Saturated, so unleash the demand
801         dmd_ty
802     else
803         topDmdType
804
805 ------  LOCAL LET/REC BOUND THING
806   | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
807   = let
808         fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty 
809               | otherwise                         = deferType dmd_ty
810         -- NB: it's important to use deferType, and not just return topDmdType
811         -- Consider     let { f x y = p + x } in f 1
812         -- The application isn't saturated, but we must nevertheless propagate 
813         --      a lazy demand for p!  
814     in
815     addVarDmd top_lvl fn_ty var dmd
816
817 ------  LOCAL NON-LET/REC BOUND THING
818   | otherwise                   -- Default case
819   = unitVarDmd var dmd
820
821   where
822     (call_depth, res_dmd) = splitCallDmd dmd
823 \end{code}
824
825
826 %************************************************************************
827 %*                                                                      *
828 \subsection{Demands}
829 %*                                                                      *
830 %************************************************************************
831
832 \begin{code}
833 splitCallDmd :: Demand -> (Int, Demand)
834 splitCallDmd (Call d) = case splitCallDmd d of
835                           (n, r) -> (n+1, r)
836 splitCallDmd d        = (0, d)
837
838 vanillaCall :: Arity -> Demand
839 vanillaCall 0 = evalDmd
840 vanillaCall n = Call (vanillaCall (n-1))
841
842 deferType :: DmdType -> DmdType
843 deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
844         -- Notice that we throw away info about both arguments and results
845         -- For example,   f = let ... in \x -> x
846         -- We don't want to get a stricness type V->T for f.
847         -- Peter??
848
849 deferEnv :: DmdEnv -> DmdEnv
850 deferEnv fv = mapVarEnv defer fv
851
852
853 ----------------
854 argDemand :: Demand -> Demand
855 -- The 'Defer' demands are just Lazy at function boundaries
856 -- Ugly!  Ask John how to improve it.
857 argDemand Top       = lazyDmd
858 argDemand (Defer d) = lazyDmd
859 argDemand (Eval ds) = Eval (mapDmds argDemand ds)
860 argDemand (Box Bot) = evalDmd
861 argDemand (Box d)   = box (argDemand d)
862 argDemand Bot       = Abs       -- Don't pass args that are consumed (only) by bottom
863 argDemand d         = d
864 \end{code}
865
866 \begin{code}
867 -------------------------
868 -- Consider (if x then y else []) with demand V
869 -- Then the first branch gives {y->V} and the second
870 --  *implicitly* has {y->A}.  So we must put {y->(V `lub` A)}
871 -- in the result env.
872 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
873   = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
874   where
875     lub_fv  = plusUFM_C lub fv1 fv2
876     lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
877     lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
878         -- lub is the identity for Bot
879
880         -- Extend the shorter argument list to match the longer
881     lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
882     lub_ds []       []       = []
883     lub_ds ds1      []       = map (`lub` resTypeArgDmd r2) ds1
884     lub_ds []       ds2      = map (resTypeArgDmd r1 `lub`) ds2
885
886 -----------------------------------
887 -- (t1 `bothType` t2) takes the argument/result info from t1,
888 -- using t2 just for its free-var info
889 -- NB: Don't forget about r2!  It might be BotRes, which is
890 --     a bottom demand on all the in-scope variables.
891 -- Peter: can this be done more neatly?
892 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
893   = DmdType both_fv2 ds1 (r1 `bothRes` r2)
894   where
895     both_fv  = plusUFM_C both fv1 fv2
896     both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
897     both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
898         -- both is the identity for Abs
899 \end{code}
900
901
902 \begin{code}
903 lubRes BotRes r      = r
904 lubRes r      BotRes = r
905 lubRes RetCPR RetCPR = RetCPR
906 lubRes r1     r2     = TopRes
907
908 -- If either diverges, the whole thing does
909 -- Otherwise take CPR info from the first
910 bothRes r1 BotRes = BotRes
911 bothRes r1 r2     = r1
912 \end{code}
913
914 \begin{code}
915 modifyEnv :: Bool                       -- No-op if False
916           -> (Demand -> Demand)         -- The zapper
917           -> DmdEnv -> DmdEnv           -- Env1 and Env2
918           -> DmdEnv -> DmdEnv           -- Transform this env
919         -- Zap anything in Env1 but not in Env2
920         -- Assume: dom(env) includes dom(Env1) and dom(Env2)
921
922 modifyEnv need_to_modify zapper env1 env2 env
923   | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
924   | otherwise      = env
925   where
926     zap uniq env = addToUFM_Directly env uniq (zapper current_val)
927                  where
928                    current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
929 \end{code}
930
931
932 %************************************************************************
933 %*                                                                      *
934 \subsection{LUB and BOTH}
935 %*                                                                      *
936 %************************************************************************
937
938 \begin{code}
939 lub :: Demand -> Demand -> Demand
940
941 lub Bot         d2 = d2
942 lub Abs         d2 = absLub d2
943 lub Top         d2 = Top
944 lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
945
946 lub (Call d1)   (Call d2)    = Call (d1 `lub` d2)
947 lub d1@(Call _) (Box d2)     = d1 `lub` d2      -- Just strip the box
948 lub d1@(Call _) d2@(Eval _)  = d2               -- Presumably seq or vanilla eval
949 lub d1@(Call _) d2           = d2 `lub` d1      -- Bot, Abs, Top
950
951 -- For the Eval case, we use these approximation rules
952 -- Box Bot       <= Eval (Box Bot ...)
953 -- Box Top       <= Defer (Box Bot ...)
954 -- Box (Eval ds) <= Eval (map Box ds)
955 lub (Eval ds1)  (Eval ds2)        = Eval (ds1 `lubs` ds2)
956 lub (Eval ds1)  (Box Bot)         = Eval (mapDmds (`lub` Box Bot) ds1)
957 lub (Eval ds1)  (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
958 lub (Eval ds1)  (Box Abs)        = deferEval (mapDmds (`lub` Box Bot) ds1)
959 lub d1@(Eval _) d2                = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
960
961 lub (Box d1)   (Box d2) = box (d1 `lub` d2)
962 lub d1@(Box _)  d2      = d2 `lub` d1
963
964 lubs = zipWithDmds lub
965
966 ---------------------
967 -- box is the smart constructor for Box
968 -- It computes <B,bot> & d
969 -- INVARIANT: (Box d) => d = Bot, Abs, Eval
970 -- Seems to be no point in allowing (Box (Call d))
971 box (Call d)  = Call d  -- The odd man out.  Why?
972 box (Box d)   = Box d
973 box (Defer _) = lazyDmd
974 box Top       = lazyDmd -- Box Abs and Box Top
975 box Abs       = lazyDmd -- are the same <B,L>
976 box d         = Box d   -- Bot, Eval
977
978 ---------------
979 defer :: Demand -> Demand
980
981 -- defer is the smart constructor for Defer
982 -- The idea is that (Defer ds) = <U(ds), L>
983 --
984 -- It specifies what happens at a lazy function argument
985 -- or a lambda; the L* operator
986 -- Set the strictness part to L, but leave
987 -- the boxity side unaffected
988 -- It also ensures that Defer (Eval [LLLL]) = L
989
990 defer Bot        = Abs
991 defer Abs        = Abs
992 defer Top        = Top
993 defer (Call _)   = lazyDmd      -- Approximation here?
994 defer (Box _)    = lazyDmd
995 defer (Defer ds) = Defer ds
996 defer (Eval ds)  = deferEval ds
997
998 -- deferEval ds = defer (Eval ds)
999 deferEval ds | allTop ds = Top
1000              | otherwise  = Defer ds
1001
1002 ---------------------
1003 absLub :: Demand -> Demand
1004 -- Computes (Abs `lub` d)
1005 -- For the Bot case consider
1006 --      f x y = if ... then x else error x
1007 --   Then for y we get Abs `lub` Bot, and we really
1008 --   want Abs overall
1009 absLub Bot        = Abs
1010 absLub Abs        = Abs
1011 absLub Top        = Top
1012 absLub (Call _)   = Top
1013 absLub (Box _)    = Top
1014 absLub (Eval ds)  = Defer (absLubs ds)  -- Or (Defer ds)?
1015 absLub (Defer ds) = Defer (absLubs ds)  -- Or (Defer ds)?
1016
1017 absLubs = mapDmds absLub
1018
1019 ---------------
1020 both :: Demand -> Demand -> Demand
1021
1022 both Abs d2 = d2
1023
1024 both Bot Bot       = Bot
1025 both Bot Abs       = Bot 
1026 both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
1027         -- Consider
1028         --      f x = error x
1029         -- From 'error' itself we get demand Bot on x
1030         -- From the arg demand on x we get 
1031         --      x :-> evalDmd = Box (Eval (Poly Abs))
1032         -- So we get  Bot `both` Box (Eval (Poly Abs))
1033         --          = Seq Keep (Poly Bot)
1034         --
1035         -- Consider also
1036         --      f x = if ... then error (fst x) else fst x
1037         -- Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
1038         --      = Eval (SA)
1039         -- which is what we want.
1040 both Bot d = errDmd
1041
1042 both Top Bot         = errDmd
1043 both Top Abs         = Top
1044 both Top Top         = Top
1045 both Top (Box d)    = Box d
1046 both Top (Call d)   = Call d
1047 both Top (Eval ds)  = Eval (mapDmds (`both` Top) ds)
1048 both Top (Defer ds)     -- = defer (Top `both` Eval ds)
1049                         -- = defer (Eval (mapDmds (`both` Top) ds))
1050                      = deferEval (mapDmds (`both` Top) ds)
1051
1052
1053 both (Box d1)   (Box d2)    = box (d1 `both` d2)
1054 both (Box d1)   d2@(Call _) = box (d1 `both` d2)
1055 both (Box d1)   d2@(Eval _) = box (d1 `both` d2)
1056 both (Box d1)   (Defer d2)  = Box d1
1057 both d1@(Box _) d2          = d2 `both` d1
1058
1059 both (Call d1)   (Call d2)   = Call (d1 `both` d2)
1060 both (Call d1)   (Eval ds2)  = Call d1  -- Could do better for (Poly Bot)?
1061 both (Call d1)   (Defer ds2) = Call d1  -- Ditto
1062 both d1@(Call _) d2          = d1 `both` d1
1063
1064 both (Eval ds1)    (Eval  ds2) = Eval (ds1 `boths` ds2)
1065 both (Eval ds1)    (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
1066 both d1@(Eval ds1) d2          = d2 `both` d1
1067
1068 both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
1069 both d1@(Defer ds1) d2       = d2 `both` d1
1070  
1071 boths = zipWithDmds both
1072 \end{code}
1073
1074
1075
1076 %************************************************************************
1077 %*                                                                      *
1078 \subsection{Miscellaneous
1079 %*                                                                      *
1080 %************************************************************************
1081
1082
1083 \begin{code}
1084 #ifdef OLD_STRICTNESS
1085 get_changes binds = vcat (map get_changes_bind binds)
1086
1087 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
1088 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
1089
1090 get_changes_pr (id,rhs) 
1091   = get_changes_var id $$ get_changes_expr rhs
1092
1093 get_changes_var var
1094   | isId var  = get_changes_str var $$ get_changes_dmd var
1095   | otherwise = empty
1096
1097 get_changes_expr (Type t)     = empty
1098 get_changes_expr (Var v)      = empty
1099 get_changes_expr (Lit l)      = empty
1100 get_changes_expr (Note n e)   = get_changes_expr e
1101 get_changes_expr (App e1 e2)  = get_changes_expr e1 $$ get_changes_expr e2
1102 get_changes_expr (Lam b e)    = {- get_changes_var b $$ -} get_changes_expr e
1103 get_changes_expr (Let b e)    = get_changes_bind b $$ get_changes_expr e
1104 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
1105
1106 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
1107
1108 get_changes_str id
1109   | new_better && old_better = empty
1110   | new_better               = message "BETTER"
1111   | old_better               = message "WORSE"
1112   | otherwise                = message "INCOMPARABLE" 
1113   where
1114     message word = text word <+> text "strictness for" <+> ppr id <+> info
1115     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1116     new = squashSig (idNewStrictness id)        -- Don't report spurious diffs that the old
1117                                                 -- strictness analyser can't track
1118     old = newStrictnessFromOld (idName id) (idArity id) (idStrictness id) (idCprInfo id)
1119     old_better = old `betterStrictness` new
1120     new_better = new `betterStrictness` old
1121
1122 get_changes_dmd id
1123   | isUnLiftedType (idType id) = empty  -- Not useful
1124   | new_better && old_better = empty
1125   | new_better               = message "BETTER"
1126   | old_better               = message "WORSE"
1127   | otherwise                = message "INCOMPARABLE" 
1128   where
1129     message word = text word <+> text "demand for" <+> ppr id <+> info
1130     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1131     new = squashDmd (argDemand (idNewDemandInfo id))    -- To avoid spurious improvements
1132                                                         -- A bit of a hack
1133     old = newDemand (idDemandInfo id)
1134     new_better = new `betterDemand` old 
1135     old_better = old `betterDemand` new
1136
1137 betterStrictness :: StrictSig -> StrictSig -> Bool
1138 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
1139
1140 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
1141
1142 betterDemand :: Demand -> Demand -> Bool
1143 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
1144 betterDemand d1 d2 = (d1 `lub` d2) == d2
1145
1146 squashSig (StrictSig (DmdType fv ds res))
1147   = StrictSig (DmdType emptyDmdEnv (map squashDmd ds) res)
1148   where
1149         -- squash just gets rid of call demands
1150         -- which the old analyser doesn't track
1151 squashDmd (Call d)   = evalDmd
1152 squashDmd (Box d)    = Box (squashDmd d)
1153 squashDmd (Eval ds)  = Eval (mapDmds squashDmd ds)
1154 squashDmd (Defer ds) = Defer (mapDmds squashDmd ds)
1155 squashDmd d          = d
1156 #endif
1157 \end{code}