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