2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
10 module DmdAnal ( dmdAnalPgm ) where
12 #include "HsVersions.h"
14 import CmdLineOpts ( DynFlags, DynFlag(..), opt_MaxWorkerArgs )
15 import NewDemand -- All of it
17 import CoreUtils ( exprIsValue, exprArity )
18 import DataCon ( dataConTyCon )
19 import TyCon ( isProductTyCon, isRecursiveTyCon )
20 import Id ( Id, idType, idDemandInfo,
21 isDataConId, isImplicitId, isGlobalId,
22 idNewStrictness, idNewStrictness_maybe, getNewStrictness, setIdNewStrictness,
23 idNewDemandInfo, setIdNewDemandInfo, newStrictnessFromOld )
24 import IdInfo ( newDemand )
27 import UniqFM ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
28 keysUFM, minusUFM, ufmToList, filterUFM )
29 import Type ( isUnLiftedType )
30 import CoreLint ( showPass, endPass )
31 import Util ( mapAndUnzip, mapAccumL, mapAccumR )
32 import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel )
33 import Maybes ( orElse, expectJust )
39 * set a noinline pragma on bottoming Ids
41 * Consider f x = x+1 `fatbar` error (show x)
42 We'd like to unbox x, even if that means reboxing it in the error case.
45 instance Outputable TopLevelFlag where
49 %************************************************************************
51 \subsection{Top level stuff}
53 %************************************************************************
56 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
57 dmdAnalPgm dflags binds
59 showPass dflags "Demand analysis" ;
60 let { binds_plus_dmds = do_prog binds ;
61 dmd_changes = get_changes binds_plus_dmds } ;
62 endPass dflags "Demand analysis"
63 Opt_D_dump_stranal binds_plus_dmds ;
65 -- Only if DEBUG is on, because only then is the old strictness analyser run
66 printDump (text "Changes in demands" $$ dmd_changes) ;
68 return binds_plus_dmds
71 do_prog :: [CoreBind] -> [CoreBind]
72 do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
74 dmdAnalTopBind :: SigEnv
77 dmdAnalTopBind sigs (NonRec id rhs)
78 | isImplicitId id -- Don't touch the info on constructors, selectors etc
79 = (sigs, NonRec id rhs) -- It's pre-computed in MkId.lhs
82 (sigs', _, (id', rhs')) = downRhs TopLevel sigs (id, rhs)
84 (sigs', NonRec id' rhs')
86 dmdAnalTopBind sigs (Rec pairs)
88 (sigs', _, pairs') = dmdFix TopLevel sigs pairs
94 %************************************************************************
96 \subsection{The analyser itself}
98 %************************************************************************
101 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
103 dmdAnal sigs Abs e = (topDmdType, e)
105 dmdAnal sigs Lazy e = let
106 (res_ty, e') = dmdAnal sigs Eval e
108 (deferType res_ty, e')
109 -- It's important not to analyse e with a lazy demand because
110 -- a) When we encounter case s of (a,b) ->
111 -- we demand s with U(d1d2)... but if the overall demand is lazy
112 -- that is wrong, and we'd need to reduce the demand on s,
113 -- which is inconvenient
114 -- b) More important, consider
115 -- f (let x = R in x+x), where f is lazy
116 -- We still want to mark x as demanded, because it will be when we
117 -- enter the let. If we analyse f's arg with a Lazy demand, we'll
118 -- just mark x as Lazy
121 dmdAnal sigs dmd (Lit lit)
122 = (topDmdType, Lit lit)
124 dmdAnal sigs dmd (Var var)
125 = (dmdTransform sigs var dmd, Var var)
127 dmdAnal sigs dmd (Note n e)
128 = (dmd_ty, Note n e')
130 (dmd_ty, e') = dmdAnal sigs dmd' e
132 Coerce _ _ -> Eval -- This coerce usually arises from a recursive
133 other -> dmd -- newtype, and we don't want to look inside them
134 -- for exactly the same reason that we don't look
135 -- inside recursive products -- we might not reach
136 -- a fixpoint. So revert to a vanilla Eval demand
138 dmdAnal sigs dmd (App fun (Type ty))
139 = (fun_ty, App fun' (Type ty))
141 (fun_ty, fun') = dmdAnal sigs dmd fun
143 dmdAnal sigs dmd (App fun arg) -- Non-type arguments
144 = let -- [Type arg handled above]
145 (fun_ty, fun') = dmdAnal sigs (Call dmd) fun
146 (arg_ty, arg') = dmdAnal sigs arg_dmd arg
147 (arg_dmd, res_ty) = splitDmdTy fun_ty
149 (res_ty `bothType` arg_ty, App fun' arg')
151 dmdAnal sigs dmd (Lam var body)
154 (body_ty, body') = dmdAnal sigs dmd body
156 (body_ty, Lam var body')
158 | Call body_dmd <- dmd -- A call demand: good!
160 (body_ty, body') = dmdAnal sigs body_dmd body
161 (lam_ty, var') = annotateLamIdBndr body_ty var
163 (lam_ty, Lam var' body')
165 | otherwise -- Not enough demand on the lambda; but do the body
166 = let -- anyway to annotate it and gather free var info
167 (body_ty, body') = dmdAnal sigs Eval body
168 (lam_ty, var') = annotateLamIdBndr body_ty var
170 (deferType lam_ty, Lam var' body')
172 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
173 | let tycon = dataConTyCon dc,
174 isProductTyCon tycon,
175 not (isRecursiveTyCon tycon)
177 bndr_ids = filter isId bndrs
178 (alt_ty, alt') = dmdAnalAlt sigs dmd alt
179 (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
180 (_, bndrs', _) = alt'
182 -- Figure out whether the demand on the case binder is used, and use
183 -- that to set the scrut_dmd. This is utterly essential.
184 -- Consider f x = case x of y { (a,b) -> k y a }
185 -- If we just take scrut_demand = U(L,A), then we won't pass x to the
186 -- worker, so the worker will rebuild
187 -- x = (a, absent-error)
188 -- and that'll crash.
189 -- So at one stage I had:
190 -- dead_case_bndr = isAbsentDmd (idNewDemandInfo case_bndr')
191 -- keepity | dead_case_bndr = Drop
192 -- | otherwise = Keep
195 -- case x of y { (a,b) -> h y + a }
196 -- where h : U(LL) -> T
197 -- The above code would compute a Keep for x, since y is not Abs, which is silly
198 -- The insight is, of course, that a demand on y is a demand on the
199 -- scrutinee, so we need to `both` it with the scrut demand
201 scrut_dmd = Seq Drop Now [idNewDemandInfo b | b <- bndrs', isId b]
203 idNewDemandInfo case_bndr'
205 (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut
207 (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
209 dmdAnal sigs dmd (Case scrut case_bndr alts)
211 (alt_tys, alts') = mapAndUnzip (dmdAnalAlt sigs dmd) alts
212 (scrut_ty, scrut') = dmdAnal sigs Eval scrut
213 (alt_ty, case_bndr') = annotateBndr (foldr1 lubType alt_tys) case_bndr
215 -- pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
216 (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
218 dmdAnal sigs dmd (Let (NonRec id rhs) body)
220 (sigs', lazy_fv, (id1, rhs')) = downRhs NotTopLevel sigs (id, rhs)
221 (body_ty, body') = dmdAnal sigs' dmd body
222 (body_ty1, id2) = annotateBndr body_ty id1
223 body_ty2 = addLazyFVs body_ty1 lazy_fv
225 -- pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env))
226 (body_ty2, Let (NonRec id2 rhs') body')
228 dmdAnal sigs dmd (Let (Rec pairs) body)
230 bndrs = map fst pairs
231 (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
232 (body_ty, body') = dmdAnal sigs' dmd body
233 body_ty1 = addLazyFVs body_ty lazy_fv
235 sigs' `seq` body_ty `seq`
237 (body_ty2, _) = annotateBndrs body_ty1 bndrs
238 -- Don't bother to add demand info to recursive
239 -- binders as annotateBndr does;
240 -- being recursive, we can't treat them strictly.
241 -- But we do need to remove the binders from the result demand env
243 (body_ty2, Let (Rec pairs') body')
246 dmdAnalAlt sigs dmd (con,bndrs,rhs)
248 (rhs_ty, rhs') = dmdAnal sigs dmd rhs
249 (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
251 (alt_ty, (con, bndrs', rhs'))
254 %************************************************************************
256 \subsection{Bindings}
258 %************************************************************************
261 dmdFix :: TopLevelFlag
262 -> SigEnv -- Does not include bindings for this binding
265 [(Id,CoreExpr)]) -- Binders annotated with stricness info
267 dmdFix top_lvl sigs pairs
268 = loop 1 initial_sigs pairs
270 bndrs = map fst pairs
271 initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs]
274 -> SigEnv -- Already contains the current sigs
276 -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
278 | all (same_sig sigs sigs') bndrs = (sigs', lazy_fv, pairs')
279 -- Note: use pairs', not pairs. pairs' is the result of
280 -- processing the RHSs with sigs (= sigs'), whereas pairs
281 -- is the result of processing the RHSs with the *previous*
282 -- iteration of sigs.
283 | n >= 5 = pprTrace "dmdFix" (ppr n <+> (vcat
284 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
285 text "env:" <+> ppr (ufmToList sigs),
286 text "binds:" <+> ppr pairs]))
287 (loop (n+1) sigs' pairs')
288 | otherwise = {- pprTrace "dmdFixLoop" (ppr id_sigs) -} (loop (n+1) sigs' pairs')
290 -- Use the new signature to do the next pair
291 -- The occurrence analyser has arranged them in a good order
292 -- so this can significantly reduce the number of iterations needed
293 ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
295 my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
296 = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
298 -- pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' )
299 ((sigs', lazy_fv'), pair')
302 (sigs', lazy_fv1, pair') = downRhs top_lvl sigs (id,rhs)
303 lazy_fv' = plusUFM_C both lazy_fv lazy_fv1
304 old_sig = lookup sigs id
305 new_sig = lookup sigs' id
307 -- Get an initial strictness signature from the Id
308 -- itself. That way we make use of earlier iterations
309 -- of the fixpoint algorithm. (Cunning plan.)
310 -- Note that the cunning plan extends to the DmdEnv too,
311 -- since it is part of the strictness signature
312 initial_sig id = idNewStrictness_maybe id `orElse` botSig
314 same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
315 lookup sigs var = case lookupVarEnv sigs var of
318 downRhs :: TopLevelFlag
319 -> SigEnv -> (Id, CoreExpr)
320 -> (SigEnv, DmdEnv, (Id, CoreExpr))
321 -- Process the RHS of the binding, add the strictness signature
322 -- to the Id, and augment the environment with the signature as well.
324 downRhs top_lvl sigs (id, rhs)
325 = (sigs', lazy_fv, (id', rhs'))
327 arity = exprArity rhs -- The idArity may not be up to date
328 (rhs_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
329 (lazy_fv, sig_ty) = mkSigTy id arity rhs rhs_ty
330 id' = id `setIdNewStrictness` sig_ty
331 sigs' = extendSigEnv top_lvl sigs id sig_ty
334 %************************************************************************
336 \subsection{Strictness signatures and types}
338 %************************************************************************
341 mkSigTy :: Id -> Arity -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
342 -- Take a DmdType and turn it into a StrictSig
343 mkSigTy id arity rhs (DmdType fv dmds res)
344 = (lazy_fv, mkStrictSig id arity dmd_ty)
346 dmd_ty = DmdType strict_fv lazified_dmds res'
348 lazy_fv = filterUFM (not . isStrictDmd) fv
349 strict_fv = filterUFM isStrictDmd fv
350 -- We put the strict FVs in the DmdType of the Id, so
351 -- that at its call sites we unleash demands on its strict fvs.
352 -- An example is 'roll' in imaginary/wheel-sieve2
353 -- Something like this:
355 -- go y = if ... then roll (x-1) else x+1
358 -- We want to see that roll is strict in x, which is because
359 -- go is called. So we put the DmdEnv for x in go's DmdType.
362 -- f :: Int -> Int -> Int
363 -- f x y = let t = x+1
364 -- h z = if z==0 then t else
365 -- if z==1 then x+1 else
369 -- Calling h does indeed evaluate x, but we can only see
370 -- that if we unleash a demand on x at the call site for t.
372 -- Incidentally, here's a place where lambda-lifting h would
373 -- lose the cigar --- we couldn't see the joint strictness in t/x
376 -- We don't want to put *all* the fv's from the RHS into the
377 -- DmdType, because that makes fixpointing very slow --- the
378 -- DmdType gets full of lazy demands that are slow to converge.
380 lazified_dmds = map lazify dmds
381 -- Get rid of defers in the arguments
382 final_dmds = setUnpackStrategy lazified_dmds
383 -- Set the unpacking strategy
385 res' = case (dmds, res) of
386 ([], RetCPR) | not (exprIsValue rhs) -> TopRes
388 -- If the rhs is a thunk, we forget the CPR info, because
389 -- it is presumably shared (else it would have been inlined, and
390 -- so we'd lose sharing if w/w'd it into a function.
392 -- DONE IN OLD CPR ANALYSER, BUT NOT YET HERE
393 -- Also, if the strictness analyser has figured out that it's strict,
394 -- the let-to-case transformation will happen, so again it's good.
395 -- (CPR analysis runs before the simplifier has had a chance to do
396 -- the let-to-case transform.)
397 -- This made a big difference to PrelBase.modInt, which had something like
398 -- modInt = \ x -> let r = ... -> I# v in
399 -- ...body strict in r...
400 -- r's RHS isn't a value yet; but modInt returns r in various branches, so
401 -- if r doesn't have the CPR property then neither does modInt
404 The unpack strategy determines whether we'll *really* unpack the argument,
405 or whether we'll just remember its strictness. If unpacking would give
406 rise to a *lot* of worker args, we may decide not to unpack after all.
409 setUnpackStrategy :: [Demand] -> [Demand]
411 = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
413 go :: Int -- Max number of args available for sub-components of [Demand]
415 -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
417 go n (Seq keep _ cs : ds)
418 | n' >= 0 = Seq keep Now cs' `cons` go n'' ds
419 | otherwise = Eval `cons` go n ds
422 n' = n + box - non_abs_args
425 Drop -> 1 -- Add one to the budget if we drop the top-level arg
426 non_abs_args = nonAbsentArgs cs
427 -- Delete # of non-absent args to which we'll now be committed
429 go n (d:ds) = d `cons` go n ds
432 cons d (n,ds) = (n, d:ds)
434 nonAbsentArgs :: [Demand] -> Int
436 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
437 nonAbsentArgs (d : ds) = 1 + nonAbsentArgs ds
441 %************************************************************************
443 \subsection{Strictness signatures and types}
445 %************************************************************************
448 splitDmdTy :: DmdType -> (Demand, DmdType)
449 -- Split off one function argument
450 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
451 splitDmdTy ty@(DmdType fv [] TopRes) = (topDmd, ty)
452 splitDmdTy ty@(DmdType fv [] BotRes) = (Abs, ty)
453 -- We already have a suitable demand on all
454 -- free vars, so no need to add more!
455 splitDmdTy (DmdType fv [] RetCPR) = panic "splitDmdTy"
459 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
461 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
462 | isTopLevel top_lvl = dmd_ty -- Don't record top level things
463 | otherwise = DmdType (extendVarEnv fv var dmd) ds res
465 addLazyFVs (DmdType fv ds res) lazy_fvs
466 = DmdType (plusUFM_C both fv lazy_fvs) ds res
468 annotateBndr :: DmdType -> Var -> (DmdType, Var)
469 -- The returned env has the var deleted
470 -- The returned var is annotated with demand info
471 -- No effect on the argument demands
472 annotateBndr dmd_ty@(DmdType fv ds res) var
473 | isTyVar var = (dmd_ty, var)
474 | otherwise = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
476 (fv', dmd) = removeFV fv var res
478 annotateBndrs = mapAccumR annotateBndr
480 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
481 -- For lambdas we add the demand to the argument demands
482 -- Only called for Ids
484 (DmdType fv' (dmd:ds) res, setIdNewDemandInfo id dmd)
486 (fv', dmd) = removeFV fv id res
488 removeFV fv var res = (fv', dmd)
490 fv' = fv `delVarEnv` var
491 dmd = lookupVarEnv fv var `orElse` deflt
492 deflt | isBotRes res = Bot
496 %************************************************************************
498 \subsection{Strictness signatures}
500 %************************************************************************
503 type SigEnv = VarEnv (StrictSig, TopLevelFlag)
504 -- We use the SigEnv to tell us whether to
505 -- record info about a variable in the DmdEnv
506 -- We do so if it's a LocalId, but not top-level
508 -- The DmdEnv gives the demand on the free vars of the function
509 -- when it is given enough args to satisfy the strictness signature
511 emptySigEnv = emptyVarEnv
513 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
514 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
516 extendSigEnvList = extendVarEnvList
518 dmdTransform :: SigEnv -- The strictness environment
519 -> Id -- The function
520 -> Demand -- The demand on the function
521 -> DmdType -- The demand type of the function in this context
522 -- Returned DmdEnv includes the demand on
523 -- this function plus demand on its free variables
525 dmdTransform sigs var dmd
527 ------ DATA CONSTRUCTOR
528 | isDataConId var, -- Data constructor
529 Seq k Now ds <- res_dmd, -- and the demand looks inside its fields
530 let StrictSig dmd_ty = idNewStrictness var, -- It must have a strictness sig
531 let DmdType _ con_ds con_res = dmd_ty
532 = if length con_ds == length ds then -- Saturated, so unleash the demand
533 -- ds can be empty, when we are just seq'ing the thing
536 Keep -> zipWith lub ds con_ds
538 -- Important! If we Keep the constructor application, then
539 -- we need the demands the constructor places (usually lazy)
540 -- If not, we don't need to. For example:
541 -- f p@(x,y) = (p,y) -- S(AL)
543 -- It's vital that we don't calculate Absent for a!
545 mkDmdType emptyDmdEnv arg_ds con_res
546 -- Must remember whether it's a product, hence con_res, not TopRes
550 ------ IMPORTED FUNCTION
551 | isGlobalId var, -- Imported function
552 let StrictSig dmd_ty = getNewStrictness var
553 = if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
558 ------ LOCAL LET/REC BOUND THING
559 | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
561 fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
562 | otherwise = deferType dmd_ty
563 -- NB: it's important to use deferType, and not just return topDmdType
564 -- Consider let { f x y = p + x } in f 1
565 -- The application isn't saturated, but we must nevertheless propagate
566 -- a lazy demand for p!
568 addVarDmd top_lvl fn_ty var dmd
570 ------ LOCAL NON-LET/REC BOUND THING
571 | otherwise -- Default case
575 (call_depth, res_dmd) = splitCallDmd dmd
579 %************************************************************************
583 %************************************************************************
586 splitCallDmd :: Demand -> (Int, Demand)
587 splitCallDmd (Call d) = case splitCallDmd d of
589 splitCallDmd d = (0, d)
591 vanillaCall :: Arity -> Demand
593 vanillaCall n = Call (vanillaCall (n-1))
595 deferType :: DmdType -> DmdType
596 deferType (DmdType fv _ _) = DmdType (mapVarEnv defer fv) [] TopRes
597 -- Notice that we throw away info about both arguments and results
598 -- For example, f = let ... in \x -> x
599 -- We don't want to get a stricness type V->T for f.
601 defer :: Demand -> Demand
604 lazify :: Demand -> Demand
605 -- The 'Defer' demands are just Lazy at function boundaries
606 lazify (Seq k Defer ds) = Lazy
607 lazify (Seq k Now ds) = Seq k Now (map lazify ds)
608 lazify Bot = Abs -- Don't pass args that are consumed by bottom/err
614 betterStrictness :: StrictSig -> StrictSig -> Bool
615 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
617 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
619 betterDemand :: Demand -> Demand -> Bool
620 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
621 betterDemand d1 d2 = (d1 `lub` d2) == d2
623 squashDmdEnv (StrictSig (DmdType fv ds res)) = StrictSig (DmdType emptyDmdEnv ds res)
627 %************************************************************************
629 \subsection{LUB and BOTH}
631 %************************************************************************
634 lub :: Demand -> Demand -> Demand
643 lub Abs Bot = Abs -- E.g f x y = if ... then x else error x
644 -- Then for y we get Abs `lub` Bot, and we really
648 lub Abs (Seq k _ ds) = Seq k Defer ds -- Very important ('radicals' example)
654 lub Eval (Seq k Now ds) = Eval -- Urk! Is this monotonic?
655 -- Was (incorrectly):
656 -- lub Eval (Seq k Now ds) = Seq Keep Now ds
658 -- Eval `lub` U(VV) is not S(VV)
659 -- (because the components aren't necessarily evaluated)
661 -- Was (correctly, but pessimistically):
662 -- lub Eval (Seq k Now ds) = Eval
663 -- Pessimistic because
665 -- f n (x:xs) = f (n+x) xs
666 -- Here we want to do better than just V for n. It's
667 -- unboxed in the (x:xs) case, and we might be prepared to
668 -- rebox it in the [] case.
669 -- To achieve this we could perhaps consider Eval to be equivalent to
672 lub Eval (Seq k Defer ds) = Lazy
675 lub (Call d1) (Call d2) = Call (lub d1 d2)
677 lub (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) (l1 `or_defer` l2) (lubs ds1 ds2)
679 -- The last clauses deal with the remaining cases for Call and Seq
680 lub d1@(Call _) d2@(Seq _ _ _) = pprPanic "lub" (ppr d1 $$ ppr d2)
681 lub d1 d2 = lub d2 d1
683 -- A Seq can have an empty list of demands, in the polymorphic case.
686 lubs ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith lub ds1 ds2
688 or_defer Now Now = Now
691 -------------------------
692 -- Consider (if x then y else []) with demand V
693 -- Then the first branch gives {y->V} and the second
694 -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
695 -- in the result env.
696 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
697 = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2)
699 lub_fv = plusUFM_C lub fv1 fv2
700 lub_fv1 = modifyEnv (not (isBotRes r1)) (Abs `lub`) fv2 fv1 lub_fv
701 lub_fv2 = modifyEnv (not (isBotRes r2)) (Abs `lub`) fv1 fv2 lub_fv1
702 -- lub is the identity for Bot
704 -------------------------
707 lubRes RetCPR RetCPR = RetCPR
708 lubRes r1 r2 = TopRes
710 -----------------------------------
711 vee :: Keepity -> Keepity -> Keepity
715 -----------------------------------
716 both :: Demand -> Demand -> Demand
721 -- The experimental one
722 -- The idea is that (error x) places on x
723 -- both demand Bot (like on all free vars)
724 -- and demand Eval (for the arg to error)
725 -- and we want the result to be Eval.
739 both Lazy (Seq k l ds) = Seq Keep l ds
741 -- Notice that the Seq case ensures that we have the
742 -- boxed value. The equation originally said
743 -- both (Seq k Now ds) = Seq Keep Now ds
744 -- but it's important that the Keep is switched on even
745 -- for a deferred demand. Otherwise a (Seq Drop Now [])
746 -- might both'd with the result, and then we won't pass
747 -- the boxed value. Here's an example:
748 -- (x-1) `seq` (x+1, x)
749 -- From the (x+1, x) we get (U*(V) `both` L), which must give S*(V)
750 -- From (x-1) we get U(V). Combining, we must get S(V).
751 -- If we got U*(V) from the pair, we'd end up with U(V), and that
752 -- can be a disaster if a component of the data structure is absent.
753 -- [Disaster = enter an absent argument.]
755 both Eval (Seq k l ds) = Seq Keep Now ds
756 both Eval (Call d) = Call d
759 both (Seq k1 Defer ds1) (Seq k2 Defer ds2) = Seq (k1 `vee` k2) Defer (boths ds1 ds2)
760 both (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) Now (boths ds1' ds2')
762 ds1' = case l1 of { Now -> ds1; Defer -> map defer ds1 }
763 ds2' = case l2 of { Now -> ds2; Defer -> map defer ds2 }
765 both (Call d1) (Call d2) = Call (d1 `both` d2)
767 -- The last clauses deal with the remaining cases for Call and Seq
768 both d1@(Call _) d2@(Seq _ _ _) = pprPanic "both" (ppr d1 $$ ppr d2)
769 both d1 d2 = both d2 d1
771 -----------------------------------
772 -- A Seq can have an empty list of demands, in the polymorphic case.
775 boths ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith both ds1 ds2
777 -----------------------------------
778 bothRes :: DmdResult -> DmdResult -> DmdResult
779 -- Left-biased for CPR info
780 bothRes BotRes _ = BotRes
781 bothRes _ BotRes = BotRes
784 -----------------------------------
785 -- (t1 `bothType` t2) takes the argument/result info from t1,
786 -- using t2 just for its free-var info
787 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
788 = DmdType both_fv2 ds1 r1
790 both_fv = plusUFM_C both fv1 fv2
791 both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
792 both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
793 -- both is the identity for Abs
797 modifyEnv :: Bool -- No-op if False
798 -> (Demand -> Demand) -- The zapper
799 -> DmdEnv -> DmdEnv -- Env1 and Env2
800 -> DmdEnv -> DmdEnv -- Transform this env
801 -- Zap anything in Env1 but not in Env2
802 -- Assume: dom(env) includes dom(Env1) and dom(Env2)
804 modifyEnv need_to_modify zapper env1 env2 env
805 | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
808 zap uniq env = addToUFM_Directly env uniq (zapper current_val)
810 current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
814 %************************************************************************
816 \subsection{Miscellaneous
818 %************************************************************************
822 get_changes binds = vcat (map get_changes_bind binds)
824 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
825 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
827 get_changes_pr (id,rhs)
828 | isImplicitId id = empty -- We don't look inside these
829 | otherwise = get_changes_var id $$ get_changes_expr rhs
832 | isId var = get_changes_str var $$ get_changes_dmd var
835 get_changes_expr (Type t) = empty
836 get_changes_expr (Var v) = empty
837 get_changes_expr (Lit l) = empty
838 get_changes_expr (Note n e) = get_changes_expr e
839 get_changes_expr (App e1 e2) = get_changes_expr e1 $$ get_changes_expr e2
840 get_changes_expr (Lam b e) = {- get_changes_var b $$ -} get_changes_expr e
841 get_changes_expr (Let b e) = get_changes_bind b $$ get_changes_expr e
842 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
844 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
847 | new_better && old_better = empty
848 | new_better = message "BETTER"
849 | old_better = message "WORSE"
850 | otherwise = message "INCOMPARABLE"
852 message word = text word <+> text "strictness for" <+> ppr id <+> info
853 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
854 new = squashDmdEnv (idNewStrictness id) -- Don't report diffs in the env
855 old = newStrictnessFromOld id
856 old_better = old `betterStrictness` new
857 new_better = new `betterStrictness` old
860 | isUnLiftedType (idType id) = empty -- Not useful
861 | new_better && old_better = empty
862 | new_better = message "BETTER"
863 | old_better = message "WORSE"
864 | otherwise = message "INCOMPARABLE"
866 message word = text word <+> text "demand for" <+> ppr id <+> info
867 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
868 new = lazify (idNewDemandInfo id) -- Lazify to avoid spurious improvements
869 old = newDemand (idDemandInfo id)
870 new_better = new `betterDemand` old
871 old_better = old `betterDemand` new