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