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