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