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