2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
10 {-# OPTIONS -fno-warn-tabs #-}
11 -- The above warning supression flag is a temporary kludge.
12 -- While working on this module you are encouraged to remove it and
13 -- detab the module (please do the detabbing in a separate patch). See
14 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
17 module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs,
18 both {- needed by WwLib -}
21 #include "HsVersions.h"
24 import Demand -- All of it
27 import Coercion ( isCoVarType )
28 import CoreUtils ( exprIsHNF, exprIsTrivial )
29 import CoreArity ( exprArity )
30 import DataCon ( dataConTyCon, dataConRepStrictness, isMarkedStrict )
31 import TyCon ( isProductTyCon, isRecursiveTyCon )
32 import Id ( Id, idType, idInlineActivation,
33 isDataConWorkId, isGlobalId, idArity,
35 setIdStrictness, idDemandInfo, idUnfolding,
36 idDemandInfo_maybe, setIdDemandInfo
38 import Var ( Var, isTyVar )
40 import TysWiredIn ( unboxedPairDataCon )
41 import TysPrim ( realWorldStatePrimTy )
42 import UniqFM ( addToUFM_Directly, lookupUFM_Directly,
44 import Type ( isUnLiftedType, eqType, tyConAppTyCon_maybe )
45 import Coercion ( coercionKind )
47 import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
49 import Maybes ( orElse, expectJust )
58 * set a noinline pragma on bottoming Ids
60 * Consider f x = x+1 `fatbar` error (show x)
61 We'd like to unbox x, even if that means reboxing it in the error case.
64 %************************************************************************
66 \subsection{Top level stuff}
68 %************************************************************************
71 dmdAnalPgm :: DynFlags -> CoreProgram -> IO CoreProgram
72 dmdAnalPgm dflags binds
74 let { binds_plus_dmds = do_prog binds } ;
75 return binds_plus_dmds
78 do_prog :: CoreProgram -> CoreProgram
79 do_prog binds = snd $ mapAccumL (dmdAnalTopBind dflags) emptySigEnv binds
81 dmdAnalTopBind :: DynFlags
85 dmdAnalTopBind dflags sigs (NonRec id rhs)
86 = (sigs2, NonRec id2 rhs2)
88 ( _, _, (_, rhs1)) = dmdAnalRhs dflags TopLevel NonRecursive (virgin sigs) (id, rhs)
89 (sigs2, _, (id2, rhs2)) = dmdAnalRhs dflags TopLevel NonRecursive (nonVirgin sigs) (id, rhs1)
90 -- Do two passes to improve CPR information
91 -- See comments with ignore_cpr_info in mk_sig_ty
92 -- and with extendSigsWithLam
94 dmdAnalTopBind dflags sigs (Rec pairs)
97 (sigs', _, pairs') = dmdFix dflags TopLevel (virgin sigs) pairs
98 -- We get two iterations automatically
99 -- c.f. the NonRec case above
103 dmdAnalTopRhs :: DynFlags -> CoreExpr -> (StrictSig, CoreExpr)
104 -- Analyse the RHS and return
105 -- a) appropriate strictness info
106 -- b) the unfolding (decorated with strictness info)
107 dmdAnalTopRhs dflags rhs
110 call_dmd = vanillaCall (exprArity rhs)
111 (_, rhs1) = dmdAnal dflags (virgin emptySigEnv) call_dmd rhs
112 (rhs_ty, rhs2) = dmdAnal dflags (nonVirgin emptySigEnv) call_dmd rhs1
113 sig = mkTopSigTy dflags rhs rhs_ty
114 -- Do two passes; see notes with extendSigsWithLam
115 -- Otherwise we get bogus CPR info for constructors like
116 -- newtype T a = MkT a
117 -- The constructor looks like (\x::T a -> x), modulo the coerce
118 -- extendSigsWithLam will optimistically give x a CPR tag the
119 -- first time, which is wrong in the end.
122 %************************************************************************
124 \subsection{The analyser itself}
126 %************************************************************************
129 dmdAnal :: DynFlags -> AnalEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
131 dmdAnal _ _ Abs e = (topDmdType, e)
133 dmdAnal dflags env dmd e
134 | not (isStrictDmd dmd)
136 (res_ty, e') = dmdAnal dflags env evalDmd e
138 (deferType res_ty, e')
139 -- It's important not to analyse e with a lazy demand because
140 -- a) When we encounter case s of (a,b) ->
141 -- we demand s with U(d1d2)... but if the overall demand is lazy
142 -- that is wrong, and we'd need to reduce the demand on s,
143 -- which is inconvenient
144 -- b) More important, consider
145 -- f (let x = R in x+x), where f is lazy
146 -- We still want to mark x as demanded, because it will be when we
147 -- enter the let. If we analyse f's arg with a Lazy demand, we'll
148 -- just mark x as Lazy
149 -- c) The application rule wouldn't be right either
150 -- Evaluating (f x) in a L demand does *not* cause
151 -- evaluation of f in a C(L) demand!
154 dmdAnal _ _ _ (Lit lit) = (topDmdType, Lit lit)
155 dmdAnal _ _ _ (Type ty) = (topDmdType, Type ty) -- Doesn't happen, in fact
156 dmdAnal _ _ _ (Coercion co) = (topDmdType, Coercion co)
158 dmdAnal _ env dmd (Var var)
159 = (dmdTransform env var dmd, Var var)
161 dmdAnal dflags env dmd (Cast e co)
162 = (dmd_ty, Cast e' co)
164 (dmd_ty, e') = dmdAnal dflags env dmd' e
165 to_co = pSnd (coercionKind co)
167 | Just tc <- tyConAppTyCon_maybe to_co
168 , isRecursiveTyCon tc = evalDmd
170 -- This coerce usually arises from a recursive
171 -- newtype, and we don't want to look inside them
172 -- for exactly the same reason that we don't look
173 -- inside recursive products -- we might not reach
174 -- a fixpoint. So revert to a vanilla Eval demand
176 dmdAnal dflags env dmd (Tick t e)
177 = (dmd_ty, Tick t e')
179 (dmd_ty, e') = dmdAnal dflags env dmd e
181 dmdAnal dflags env dmd (App fun (Type ty))
182 = (fun_ty, App fun' (Type ty))
184 (fun_ty, fun') = dmdAnal dflags env dmd fun
186 dmdAnal dflags sigs dmd (App fun (Coercion co))
187 = (fun_ty, App fun' (Coercion co))
189 (fun_ty, fun') = dmdAnal dflags sigs dmd fun
191 -- Lots of the other code is there to make this
192 -- beautiful, compositional, application rule :-)
193 dmdAnal dflags env dmd (App fun arg) -- Non-type arguments
194 = let -- [Type arg handled above]
195 (fun_ty, fun') = dmdAnal dflags env (Call dmd) fun
196 (arg_ty, arg') = dmdAnal dflags env arg_dmd arg
197 (arg_dmd, res_ty) = splitDmdTy fun_ty
199 (res_ty `bothType` arg_ty, App fun' arg')
201 dmdAnal dflags env dmd (Lam var body)
204 (body_ty, body') = dmdAnal dflags env dmd body
206 (body_ty, Lam var body')
208 | Call body_dmd <- dmd -- A call demand: good!
210 env' = extendSigsWithLam env var
211 (body_ty, body') = dmdAnal dflags env' body_dmd body
212 (lam_ty, var') = annotateLamIdBndr dflags env body_ty var
214 (lam_ty, Lam var' body')
216 | otherwise -- Not enough demand on the lambda; but do the body
217 = let -- anyway to annotate it and gather free var info
218 (body_ty, body') = dmdAnal dflags env evalDmd body
219 (lam_ty, var') = annotateLamIdBndr dflags env body_ty var
221 (deferType lam_ty, Lam var' body')
223 dmdAnal dflags env dmd (Case scrut case_bndr ty [alt@(DataAlt dc, _, _)])
224 | let tycon = dataConTyCon dc
225 , isProductTyCon tycon
226 , not (isRecursiveTyCon tycon)
228 env_alt = extendAnalEnv NotTopLevel env case_bndr case_bndr_sig
229 (alt_ty, alt') = dmdAnalAlt dflags env_alt dmd alt
230 (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
231 (_, bndrs', _) = alt'
232 case_bndr_sig = cprSig
233 -- Inside the alternative, the case binder has the CPR property.
234 -- Meaning that a case on it will successfully cancel.
236 -- f True x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
239 -- We want f to have the CPR property:
240 -- f b x = case fw b x of { r -> I# r }
241 -- fw True x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
244 -- Figure out whether the demand on the case binder is used, and use
245 -- that to set the scrut_dmd. This is utterly essential.
246 -- Consider f x = case x of y { (a,b) -> k y a }
247 -- If we just take scrut_demand = U(L,A), then we won't pass x to the
248 -- worker, so the worker will rebuild
249 -- x = (a, absent-error)
250 -- and that'll crash.
251 -- So at one stage I had:
252 -- dead_case_bndr = isAbsentDmd (idDemandInfo case_bndr')
253 -- keepity | dead_case_bndr = Drop
254 -- | otherwise = Keep
257 -- case x of y { (a,b) -> h y + a }
258 -- where h : U(LL) -> T
259 -- The above code would compute a Keep for x, since y is not Abs, which is silly
260 -- The insight is, of course, that a demand on y is a demand on the
261 -- scrutinee, so we need to `both` it with the scrut demand
263 alt_dmd = Eval (Prod [idDemandInfo b | b <- bndrs', isId b])
264 scrut_dmd = alt_dmd `both`
265 idDemandInfo case_bndr'
267 (scrut_ty, scrut') = dmdAnal dflags env scrut_dmd scrut
268 res_ty = alt_ty1 `bothType` scrut_ty
270 -- pprTrace "dmdAnal:Case1" (vcat [ text "scrut" <+> ppr scrut
271 -- , text "scrut_ty" <+> ppr scrut_ty
272 -- , text "alt_ty" <+> ppr alt_ty1
273 -- , text "res_ty" <+> ppr res_ty ]) $
274 (res_ty, Case scrut' case_bndr' ty [alt'])
276 dmdAnal dflags env dmd (Case scrut case_bndr ty alts)
278 (alt_tys, alts') = mapAndUnzip (dmdAnalAlt dflags env dmd) alts
279 (scrut_ty, scrut') = dmdAnal dflags env evalDmd scrut
280 (alt_ty, case_bndr') = annotateBndr (foldr lubType botDmdType alt_tys) case_bndr
281 res_ty = alt_ty `bothType` scrut_ty
283 -- pprTrace "dmdAnal:Case2" (vcat [ text "scrut" <+> ppr scrut
284 -- , text "scrut_ty" <+> ppr scrut_ty
285 -- , text "alt_ty" <+> ppr alt_ty
286 -- , text "res_ty" <+> ppr res_ty ]) $
287 (res_ty, Case scrut' case_bndr' ty alts')
289 dmdAnal dflags env dmd (Let (NonRec id rhs) body)
291 (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs dflags NotTopLevel NonRecursive env (id, rhs)
292 (body_ty, body') = dmdAnal dflags (updSigEnv env sigs') dmd body
293 (body_ty1, id2) = annotateBndr body_ty id1
294 body_ty2 = addLazyFVs body_ty1 lazy_fv
296 -- If the actual demand is better than the vanilla call
297 -- demand, you might think that we might do better to re-analyse
298 -- the RHS with the stronger demand.
299 -- But (a) That seldom happens, because it means that *every* path in
300 -- the body of the let has to use that stronger demand
301 -- (b) It often happens temporarily in when fixpointing, because
302 -- the recursive function at first seems to place a massive demand.
303 -- But we don't want to go to extra work when the function will
304 -- probably iterate to something less demanding.
305 -- In practice, all the times the actual demand on id2 is more than
306 -- the vanilla call demand seem to be due to (b). So we don't
307 -- bother to re-analyse the RHS.
308 (body_ty2, Let (NonRec id2 rhs') body')
310 dmdAnal dflags env dmd (Let (Rec pairs) body)
312 bndrs = map fst pairs
313 (sigs', lazy_fv, pairs') = dmdFix dflags NotTopLevel env pairs
314 (body_ty, body') = dmdAnal dflags (updSigEnv env sigs') dmd body
315 body_ty1 = addLazyFVs body_ty lazy_fv
317 sigs' `seq` body_ty `seq`
319 (body_ty2, _) = annotateBndrs body_ty1 bndrs
320 -- Don't bother to add demand info to recursive
321 -- binders as annotateBndr does;
322 -- being recursive, we can't treat them strictly.
323 -- But we do need to remove the binders from the result demand env
325 (body_ty2, Let (Rec pairs') body')
328 dmdAnalAlt :: DynFlags -> AnalEnv -> Demand -> Alt Var -> (DmdType, Alt Var)
329 dmdAnalAlt dflags env dmd (con,bndrs,rhs)
331 (rhs_ty, rhs') = dmdAnal dflags env dmd rhs
332 rhs_ty' = addDataConPatDmds con bndrs rhs_ty
333 (alt_ty, bndrs') = annotateBndrs rhs_ty' bndrs
334 final_alt_ty | io_hack_reqd = alt_ty `lubType` topDmdType
337 -- There's a hack here for I/O operations. Consider
338 -- case foo x s of { (# s, r #) -> y }
339 -- Is this strict in 'y'. Normally yes, but what if 'foo' is an I/O
340 -- operation that simply terminates the program (not in an erroneous way)?
341 -- In that case we should not evaluate y before the call to 'foo'.
342 -- Hackish solution: spot the IO-like situation and add a virtual branch,
346 -- other -> return ()
347 -- So the 'y' isn't necessarily going to be evaluated
349 -- A more complete example (Trac #148, #1592) where this shows up is:
350 -- do { let len = <expensive> ;
351 -- ; when (...) (exitWith ExitSuccess)
354 io_hack_reqd = con == DataAlt unboxedPairDataCon &&
355 idType (head bndrs) `eqType` realWorldStatePrimTy
357 (final_alt_ty, (con, bndrs', rhs'))
359 addDataConPatDmds :: AltCon -> [Var] -> DmdType -> DmdType
360 -- See Note [Add demands for strict constructors]
361 addDataConPatDmds DEFAULT _ dmd_ty = dmd_ty
362 addDataConPatDmds (LitAlt _) _ dmd_ty = dmd_ty
363 addDataConPatDmds (DataAlt con) bndrs dmd_ty
364 = foldr add dmd_ty str_bndrs
366 add bndr dmd_ty = addVarDmd dmd_ty bndr seqDmd
367 str_bndrs = [ b | (b,s) <- zipEqual "addDataConPatBndrs"
369 (dataConRepStrictness con)
373 Note [Add demands for strict constructors]
374 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
375 Consider this program (due to Roman):
379 foo :: X Int -> Int -> Int
382 go i | i < n = a + go (i+1)
385 We want the worker for 'foo' too look like this:
387 $wfoo :: Int# -> Int# -> Int#
389 with the first argument unboxed, so that it is not eval'd each time
390 around the loop (which would otherwise happen, since 'foo' is not
391 strict in 'a'. It is sound for the wrapper to pass an unboxed arg
392 because X is strict, so its argument must be evaluated. And if we
393 *don't* pass an unboxed argument, we can't even repair it by adding a
396 foo (X a) n = a `seq` go 0
398 because the seq is discarded (very early) since X is strict!
400 There is the usual danger of reboxing, which as usual we ignore. But
401 if X is monomorphic, and has an UNPACK pragma, then this optimisation
402 is even more important. We don't want the wrapper to rebox an unboxed
403 argument, and pass an Int to $wfoo!
406 %************************************************************************
410 %************************************************************************
413 dmdTransform :: AnalEnv -- The strictness environment
414 -> Id -- The function
415 -> Demand -- The demand on the function
416 -> DmdType -- The demand type of the function in this context
417 -- Returned DmdEnv includes the demand on
418 -- this function plus demand on its free variables
420 dmdTransform env var dmd
422 ------ DATA CONSTRUCTOR
423 | isDataConWorkId var -- Data constructor
425 StrictSig dmd_ty = idStrictness var -- It must have a strictness sig
426 DmdType _ _ con_res = dmd_ty
429 if arity == call_depth then -- Saturated, so unleash the demand
431 -- Important! If we Keep the constructor application, then
432 -- we need the demands the constructor places (always lazy)
433 -- If not, we don't need to. For example:
434 -- f p@(x,y) = (p,y) -- S(AL)
436 -- It's vital that we don't calculate Absent for a!
437 dmd_ds = case res_dmd of
438 Box (Eval ds) -> mapDmds box ds
442 -- ds can be empty, when we are just seq'ing the thing
443 -- If so we must make up a suitable bunch of demands
444 arg_ds = case dmd_ds of
445 Poly d -> replicate arity d
446 Prod ds -> ASSERT( ds `lengthIs` arity ) ds
449 mkDmdType emptyDmdEnv arg_ds con_res
450 -- Must remember whether it's a product, hence con_res, not TopRes
454 ------ IMPORTED FUNCTION
455 | isGlobalId var, -- Imported function
456 let StrictSig dmd_ty = idStrictness var
457 = -- pprTrace "strict-sig" (ppr var $$ ppr dmd_ty) $
458 if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
463 ------ LOCAL LET/REC BOUND THING
464 | Just (StrictSig dmd_ty, top_lvl) <- lookupSigEnv env var
466 fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
467 | otherwise = deferType dmd_ty
468 -- NB: it's important to use deferType, and not just return topDmdType
469 -- Consider let { f x y = p + x } in f 1
470 -- The application isn't saturated, but we must nevertheless propagate
471 -- a lazy demand for p!
473 if isTopLevel top_lvl then fn_ty -- Don't record top level things
474 else addVarDmd fn_ty var dmd
476 ------ LOCAL NON-LET/REC BOUND THING
477 | otherwise -- Default case
481 (call_depth, res_dmd) = splitCallDmd dmd
484 %************************************************************************
486 \subsection{Bindings}
488 %************************************************************************
493 -> AnalEnv -- Does not include bindings for this binding
496 [(Id,CoreExpr)]) -- Binders annotated with stricness info
498 dmdFix dflags top_lvl env orig_pairs
499 = loop 1 initial_env orig_pairs
501 bndrs = map fst orig_pairs
502 initial_env = addInitialSigs top_lvl env bndrs
505 -> AnalEnv -- Already contains the current sigs
507 -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
509 = -- pprTrace "dmd loop" (ppr n <+> ppr bndrs $$ ppr env) $
514 = (sigs', lazy_fv, pairs')
515 -- Note: return pairs', not pairs. pairs' is the result of
516 -- processing the RHSs with sigs (= sigs'), whereas pairs
517 -- is the result of processing the RHSs with the *previous*
518 -- iteration of sigs.
521 = pprTrace "dmdFix loop" (ppr n <+> (vcat
522 [ text "Sigs:" <+> ppr [ (id,lookupVarEnv sigs id, lookupVarEnv sigs' id)
524 text "env:" <+> ppr env,
525 text "binds:" <+> pprCoreBinding (Rec pairs)]))
526 (sigEnv env, lazy_fv, orig_pairs) -- Safe output
527 -- The lazy_fv part is really important! orig_pairs has no strictness
528 -- info, including nothing about free vars. But if we have
529 -- letrec f = ....y..... in ...f...
530 -- where 'y' is free in f, we must record that y is mentioned,
531 -- otherwise y will get recorded as absent altogether
534 = loop (n+1) (nonVirgin sigs') pairs'
537 found_fixpoint = all (same_sig sigs sigs') bndrs
539 ((sigs',lazy_fv), pairs') = mapAccumL my_downRhs (sigs, emptyDmdEnv) pairs
540 -- mapAccumL: Use the new signature to do the next pair
541 -- The occurrence analyser has arranged them in a good order
542 -- so this can significantly reduce the number of iterations needed
544 my_downRhs (sigs,lazy_fv) (id,rhs)
545 = ((sigs', lazy_fv'), pair')
547 (sigs', lazy_fv1, pair') = dmdAnalRhs dflags top_lvl Recursive (updSigEnv env sigs) (id,rhs)
548 lazy_fv' = plusVarEnv_C both lazy_fv lazy_fv1
550 same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
551 lookup sigs var = case lookupVarEnv sigs var of
553 Nothing -> pprPanic "dmdFix" (ppr var)
555 dmdAnalRhs :: DynFlags -> TopLevelFlag -> RecFlag
556 -> AnalEnv -> (Id, CoreExpr)
557 -> (SigEnv, DmdEnv, (Id, CoreExpr))
558 -- Process the RHS of the binding, add the strictness signature
559 -- to the Id, and augment the environment with the signature as well.
561 dmdAnalRhs dflags top_lvl rec_flag env (id, rhs)
562 = (sigs', lazy_fv, (id', rhs'))
564 arity = idArity id -- The idArity should be up to date
565 -- The simplifier was run just beforehand
566 (rhs_dmd_ty, rhs') = dmdAnal dflags env (vanillaCall arity) rhs
567 (lazy_fv, sig_ty) = WARN( arity /= dmdTypeDepth rhs_dmd_ty && not (exprIsTrivial rhs), ppr id )
568 -- The RHS can be eta-reduced to just a variable,
569 -- in which case we should not complain.
570 mkSigTy dflags top_lvl rec_flag id rhs rhs_dmd_ty
571 id' = id `setIdStrictness` sig_ty
572 sigs' = extendSigEnv top_lvl (sigEnv env) id sig_ty
576 %************************************************************************
578 \subsection{Strictness signatures and types}
580 %************************************************************************
583 mkTopSigTy :: DynFlags -> CoreExpr -> DmdType -> StrictSig
584 -- Take a DmdType and turn it into a StrictSig
585 -- NB: not used for never-inline things; hence False
586 mkTopSigTy dflags rhs dmd_ty = snd (mk_sig_ty dflags False False rhs dmd_ty)
588 mkSigTy :: DynFlags -> TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
589 mkSigTy dflags top_lvl rec_flag id rhs dmd_ty
590 = mk_sig_ty dflags never_inline thunk_cpr_ok rhs dmd_ty
592 never_inline = isNeverActive (idInlineActivation id)
593 maybe_id_dmd = idDemandInfo_maybe id
594 -- Is Nothing the first time round
596 thunk_cpr_ok -- See Note [CPR for thunks]
597 | isTopLevel top_lvl = False -- Top level things don't get
598 -- their demandInfo set at all
599 | isRec rec_flag = False -- Ditto recursive things
600 | Just dmd <- maybe_id_dmd = isStrictDmd dmd
601 | otherwise = True -- Optimistic, first time round
605 Note [CPR for thunks]
606 ~~~~~~~~~~~~~~~~~~~~~
607 If the rhs is a thunk, we usually forget the CPR info, because
608 it is presumably shared (else it would have been inlined, and
609 so we'd lose sharing if w/w'd it into a function). E.g.
611 let r = case expensive of
615 If we marked r as having the CPR property, then we'd w/w into
617 let $wr = \() -> case expensive of
623 But now r is a thunk, which won't be inlined, so we are no further ahead.
626 f x = let r = case expensive of (a,b) -> (b,a)
627 in if foo r then r else (x,x)
629 Does f have the CPR property? Well, no.
631 However, if the strictness analyser has figured out (in a previous
632 iteration) that it's strict, then we DON'T need to forget the CPR info.
633 Instead we can retain the CPR info and do the thunk-splitting transform
634 (see WorkWrap.splitThunk).
636 This made a big difference to PrelBase.modInt, which had something like
637 modInt = \ x -> let r = ... -> I# v in
638 ...body strict in r...
639 r's RHS isn't a value yet; but modInt returns r in various branches, so
640 if r doesn't have the CPR property then neither does modInt
641 Another case I found in practice (in Complex.magnitude), looks like this:
642 let k = if ... then I# a else I# b
643 in ... body strict in k ....
644 (For this example, it doesn't matter whether k is returned as part of
645 the overall result; but it does matter that k's RHS has the CPR property.)
646 Left to itself, the simplifier will make a join point thus:
647 let $j k = ...body strict in k...
648 if ... then $j (I# a) else $j (I# b)
649 With thunk-splitting, we get instead
650 let $j x = let k = I#x in ...body strict in k...
651 in if ... then $j a else $j b
652 This is much better; there's a good chance the I# won't get allocated.
654 The difficulty with this is that we need the strictness type to
655 look at the body... but we now need the body to calculate the demand
656 on the variable, so we can decide whether its strictness type should
657 have a CPR in it or not. Simple solution:
658 a) use strictness info from the previous iteration
659 b) make sure we do at least 2 iterations, by doing a second
660 round for top-level non-recs. Top level recs will get at
661 least 2 iterations except for totally-bottom functions
662 which aren't very interesting anyway.
664 NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
666 Note [Optimistic in the Nothing case]
667 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
668 Demand info now has a 'Nothing' state, just like strictness info.
669 The analysis works from 'dangerous' towards a 'safe' state; so we
670 start with botSig for 'Nothing' strictness infos, and we start with
671 "yes, it's demanded" for 'Nothing' in the demand info. The
672 fixpoint iteration will sort it all out.
674 We can't start with 'not-demanded' because then consider
678 if ... then t else I# y else f x'
680 In the first iteration we'd have no demand info for x, so assume
681 not-demanded; then we'd get TopRes for f's CPR info. Next iteration
682 we'd see that t was demanded, and so give it the CPR property, but by
683 now f has TopRes, so it will stay TopRes. Instead, with the Nothing
684 setting the first time round, we say 'yes t is demanded' the first
687 However, this does mean that for non-recursive bindings we must
688 iterate twice to be sure of not getting over-optimistic CPR info,
689 in the case where t turns out to be not-demanded. This is handled
693 Note [NOINLINE and strictness]
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 The strictness analyser used to have a HACK which ensured that NOINLNE
696 things were not strictness-analysed. The reason was unsafePerformIO.
697 Left to itself, the strictness analyser would discover this strictness
699 unsafePerformIO: C(U(AV))
700 But then consider this sub-expression
701 unsafePerformIO (\s -> let r = f x in
702 case writeIORef v r s of (# s1, _ #) ->
704 The strictness analyser will now find that r is sure to be eval'd,
705 and may then hoist it out. This makes tests/lib/should_run/memo002
708 Solving this by making all NOINLINE things have no strictness info is overkill.
709 In particular, it's overkill for runST, which is perfectly respectable.
711 f x = runST (return x)
712 This should be strict in x.
714 So the new plan is to define unsafePerformIO using the 'lazy' combinator:
716 unsafePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
718 Remember, 'lazy' is a wired-in identity-function Id, of type a->a, which is
719 magically NON-STRICT, and is inlined after strictness analysis. So
720 unsafePerformIO will look non-strict, and that's what we want.
722 Now we don't need the hack in the strictness analyser. HOWEVER, this
723 decision does mean that even a NOINLINE function is not entirely
724 opaque: some aspect of its implementation leaks out, notably its
725 strictness. For example, if you have a function implemented by an
726 error stub, but which has RULES, you may want it not to be eliminated
731 mk_sig_ty :: DynFlags -> Bool -> Bool -> CoreExpr
732 -> DmdType -> (DmdEnv, StrictSig)
733 mk_sig_ty dflags _never_inline thunk_cpr_ok rhs (DmdType fv dmds res)
734 = (lazy_fv, mkStrictSig dmd_ty)
735 -- Re unused never_inline, see Note [NOINLINE and strictness]
737 dmd_ty = DmdType strict_fv final_dmds res'
739 lazy_fv = filterUFM (not . isStrictDmd) fv
740 strict_fv = filterUFM isStrictDmd fv
741 -- We put the strict FVs in the DmdType of the Id, so
742 -- that at its call sites we unleash demands on its strict fvs.
743 -- An example is 'roll' in imaginary/wheel-sieve2
744 -- Something like this:
746 -- go y = if ... then roll (x-1) else x+1
749 -- We want to see that roll is strict in x, which is because
750 -- go is called. So we put the DmdEnv for x in go's DmdType.
753 -- f :: Int -> Int -> Int
754 -- f x y = let t = x+1
755 -- h z = if z==0 then t else
756 -- if z==1 then x+1 else
760 -- Calling h does indeed evaluate x, but we can only see
761 -- that if we unleash a demand on x at the call site for t.
763 -- Incidentally, here's a place where lambda-lifting h would
764 -- lose the cigar --- we couldn't see the joint strictness in t/x
767 -- We don't want to put *all* the fv's from the RHS into the
768 -- DmdType, because that makes fixpointing very slow --- the
769 -- DmdType gets full of lazy demands that are slow to converge.
771 final_dmds = setUnpackStrategy dflags dmds
772 -- Set the unpacking strategy
775 RetCPR | ignore_cpr_info -> TopRes
777 ignore_cpr_info = not (exprIsHNF rhs || thunk_cpr_ok)
780 The unpack strategy determines whether we'll *really* unpack the argument,
781 or whether we'll just remember its strictness. If unpacking would give
782 rise to a *lot* of worker args, we may decide not to unpack after all.
785 setUnpackStrategy :: DynFlags -> [Demand] -> [Demand]
786 setUnpackStrategy dflags ds
787 = snd (go (maxWorkerArgs dflags - nonAbsentArgs ds) ds)
789 go :: Int -- Max number of args available for sub-components of [Demand]
791 -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
793 go n (Eval (Prod cs) : ds)
794 | n' >= 0 = Eval (Prod cs') `cons` go n'' ds
795 | otherwise = Box (Eval (Prod cs)) `cons` go n ds
798 n' = n + 1 - non_abs_args
799 -- Add one to the budget 'cos we drop the top-level arg
800 non_abs_args = nonAbsentArgs cs
801 -- Delete # of non-absent args to which we'll now be committed
803 go n (d:ds) = d `cons` go n ds
806 cons d (n,ds) = (n, d:ds)
808 nonAbsentArgs :: [Demand] -> Int
810 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
811 nonAbsentArgs (_ : ds) = 1 + nonAbsentArgs ds
815 %************************************************************************
817 \subsection{Strictness signatures and types}
819 %************************************************************************
822 unitVarDmd :: Var -> Demand -> DmdType
823 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
825 addVarDmd :: DmdType -> Var -> Demand -> DmdType
826 addVarDmd (DmdType fv ds res) var dmd
827 = DmdType (extendVarEnv_C both fv var dmd) ds res
829 addLazyFVs :: DmdType -> DmdEnv -> DmdType
830 addLazyFVs (DmdType fv ds res) lazy_fvs
831 = DmdType both_fv1 ds res
833 both_fv = plusVarEnv_C both fv lazy_fvs
834 both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
835 -- This modifyEnv is vital. Consider
836 -- let f = \x -> (x,y)
838 -- Here, y is treated as a lazy-fv of f, but we must `both` that L
839 -- demand with the bottom coming up from 'error'
841 -- I got a loop in the fixpointer without this, due to an interaction
842 -- with the lazy_fv filtering in mkSigTy. Roughly, it was
844 -- = letrec g y = x `fatbar`
845 -- letrec h z = z + ...g...
848 -- In the initial iteration for f, f=Bot
849 -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
850 -- is lazy. Now consider the fixpoint iteration for g, esp the demands it
851 -- places on its free variables. Suppose it places none. Then the
852 -- x `fatbar` ...call to h...
853 -- will give a x->V demand for x. That turns into a L demand for x,
854 -- which floats out of the defn for h. Without the modifyEnv, that
855 -- L demand doesn't get both'd with the Bot coming up from the inner
856 -- call to f. So we just get an L demand for x for g.
858 -- A better way to say this is that the lazy-fv filtering should give the
859 -- same answer as putting the lazy fv demands in the function's type.
861 annotateBndr :: DmdType -> Var -> (DmdType, Var)
862 -- The returned env has the var deleted
863 -- The returned var is annotated with demand info
864 -- No effect on the argument demands
865 annotateBndr dmd_ty@(DmdType fv ds res) var
866 | isTyVar var = (dmd_ty, var)
867 | otherwise = (DmdType fv' ds res, setIdDemandInfo var dmd)
869 (fv', dmd) = removeFV fv var res
871 annotateBndrs :: DmdType -> [Var] -> (DmdType, [Var])
872 annotateBndrs = mapAccumR annotateBndr
874 annotateLamIdBndr :: DynFlags
876 -> DmdType -- Demand type of body
877 -> Id -- Lambda binder
878 -> (DmdType, -- Demand type of lambda
879 Id) -- and binder annotated with demand
881 annotateLamIdBndr dflags env (DmdType fv ds res) id
882 -- For lambdas we add the demand to the argument demands
883 -- Only called for Ids
885 (final_ty, setIdDemandInfo id hacked_dmd)
887 -- Watch out! See note [Lambda-bound unfoldings]
888 final_ty = case maybeUnfoldingTemplate (idUnfolding id) of
890 Just unf -> main_ty `bothType` unf_ty
892 (unf_ty, _) = dmdAnal dflags env dmd unf
894 main_ty = DmdType fv' (hacked_dmd:ds) res
896 (fv', dmd) = removeFV fv id res
897 hacked_dmd = argDemand dmd
898 -- This call to argDemand is vital, because otherwise we label
899 -- a lambda binder with demand 'B'. But in terms of calling
900 -- conventions that's Abs, because we don't pass it. But
901 -- when we do a w/w split we get
902 -- fw x = (\x y:B -> ...) x (error "oops")
903 -- And then the simplifier things the 'B' is a strict demand
904 -- and evaluates the (error "oops"). Sigh
906 removeFV :: DmdEnv -> Var -> DmdResult -> (DmdEnv, Demand)
907 removeFV fv id res = (fv', zapUnlifted id dmd)
909 fv' = fv `delVarEnv` id
910 dmd = lookupVarEnv fv id `orElse` deflt
911 deflt | isBotRes res = Bot
914 zapUnlifted :: Id -> Demand -> Demand
915 -- For unlifted-type variables, we are only
916 -- interested in Bot/Abs/Box Abs
919 _ | isCoVarType ty -> lazyDmd -- For coercions, ignore str/abs totally
922 _ | isUnLiftedType ty -> lazyDmd -- For unlifted types, ignore strictness
928 Note [Lamba-bound unfoldings]
929 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
930 We allow a lambda-bound variable to carry an unfolding, a facility that is used
931 exclusively for join points; see Note [Case binders and join points]. If so,
932 we must be careful to demand-analyse the RHS of the unfolding! Example
933 \x. \y{=Just x}. <body>
934 Then if <body> uses 'y', then transitively it uses 'x', and we must not
935 forget that fact, otherwise we might make 'x' absent when it isn't.
938 %************************************************************************
940 \subsection{Strictness signatures}
942 %************************************************************************
946 = AE { ae_sigs :: SigEnv
947 , ae_virgin :: Bool } -- True on first iteration only
948 -- See Note [Initialising strictness]
949 -- We use the se_env to tell us whether to
950 -- record info about a variable in the DmdEnv
951 -- We do so if it's a LocalId, but not top-level
953 -- The DmdEnv gives the demand on the free vars of the function
954 -- when it is given enough args to satisfy the strictness signature
956 type SigEnv = VarEnv (StrictSig, TopLevelFlag)
958 instance Outputable AnalEnv where
959 ppr (AE { ae_sigs = env, ae_virgin = virgin })
960 = ptext (sLit "AE") <+> braces (vcat
961 [ ptext (sLit "ae_virgin =") <+> ppr virgin
962 , ptext (sLit "ae_sigs =") <+> ppr env ])
964 emptySigEnv :: SigEnv
965 emptySigEnv = emptyVarEnv
967 sigEnv :: AnalEnv -> SigEnv
970 updSigEnv :: AnalEnv -> SigEnv -> AnalEnv
971 updSigEnv env sigs = env { ae_sigs = sigs }
973 extendAnalEnv :: TopLevelFlag -> AnalEnv -> Id -> StrictSig -> AnalEnv
974 extendAnalEnv top_lvl env var sig
975 = env { ae_sigs = extendSigEnv top_lvl (ae_sigs env) var sig }
977 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
978 extendSigEnv top_lvl sigs var sig = extendVarEnv sigs var (sig, top_lvl)
980 lookupSigEnv :: AnalEnv -> Id -> Maybe (StrictSig, TopLevelFlag)
981 lookupSigEnv env id = lookupVarEnv (ae_sigs env) id
983 addInitialSigs :: TopLevelFlag -> AnalEnv -> [Id] -> AnalEnv
984 -- See Note [Initialising strictness]
985 addInitialSigs top_lvl env@(AE { ae_sigs = sigs, ae_virgin = virgin }) ids
986 = env { ae_sigs = extendVarEnvList sigs [ (id, (init_sig id, top_lvl))
989 init_sig | virgin = \_ -> botSig
990 | otherwise = idStrictness
992 virgin, nonVirgin :: SigEnv -> AnalEnv
993 virgin sigs = AE { ae_sigs = sigs, ae_virgin = True }
994 nonVirgin sigs = AE { ae_sigs = sigs, ae_virgin = False }
996 extendSigsWithLam :: AnalEnv -> Id -> AnalEnv
997 -- Extend the AnalEnv when we meet a lambda binder
998 -- If the binder is marked demanded with a product demand, then give it a CPR
999 -- signature, because in the likely event that this is a lambda on a fn defn
1000 -- [we only use this when the lambda is being consumed with a call demand],
1001 -- it'll be w/w'd and so it will be CPR-ish. E.g.
1002 -- f = \x::(Int,Int). if ...strict in x... then
1006 -- We want f to have the CPR property because x does, by the time f has been w/w'd
1008 -- Also note that we only want to do this for something that
1009 -- definitely has product type, else we may get over-optimistic
1010 -- CPR results (e.g. from \x -> x!).
1012 extendSigsWithLam env id
1013 = case idDemandInfo_maybe id of
1014 Nothing -> extendAnalEnv NotTopLevel env id cprSig
1015 -- See Note [Optimistic in the Nothing case]
1016 Just (Eval (Prod _)) -> extendAnalEnv NotTopLevel env id cprSig
1020 Note [Initialising strictness]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 Our basic plan is to initialise the strictness of each Id in
1023 a recursive group to "bottom", and find a fixpoint from there.
1024 However, this group A might be inside an *enclosing* recursive
1025 group B, in which case we'll do the entire fixpoint shebang on A
1026 for each iteration of B.
1028 To speed things up, we initialise each iteration of B from the result
1029 of the last one, which is neatly recorded in each binder. That way we
1030 make use of earlier iterations of the fixpoint algorithm. (Cunning
1033 But on the *first* iteration we want to *ignore* the current strictness
1034 of the Id, and start from "bottom". Nowadays the Id can have a current
1035 strictness, because interface files record strictness for nested bindings.
1036 To know when we are in the first iteration, we look at the ae_virgin
1037 field of the AnalEnv.
1040 %************************************************************************
1044 %************************************************************************
1047 splitDmdTy :: DmdType -> (Demand, DmdType)
1048 -- Split off one function argument
1049 -- We already have a suitable demand on all
1050 -- free vars, so no need to add more!
1051 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
1052 splitDmdTy ty@(DmdType _ [] res_ty) = (resTypeArgDmd res_ty, ty)
1054 splitCallDmd :: Demand -> (Int, Demand)
1055 splitCallDmd (Call d) = case splitCallDmd d of
1057 splitCallDmd d = (0, d)
1059 vanillaCall :: Arity -> Demand
1060 vanillaCall 0 = evalDmd
1061 vanillaCall n = Call (vanillaCall (n-1))
1063 deferType :: DmdType -> DmdType
1064 deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
1065 -- Notice that we throw away info about both arguments and results
1066 -- For example, f = let ... in \x -> x
1067 -- We don't want to get a stricness type V->T for f.
1069 deferEnv :: DmdEnv -> DmdEnv
1070 deferEnv fv = mapVarEnv defer fv
1074 argDemand :: Demand -> Demand
1075 -- The 'Defer' demands are just Lazy at function boundaries
1076 -- Ugly! Ask John how to improve it.
1077 argDemand Top = lazyDmd
1078 argDemand (Defer _) = lazyDmd
1079 argDemand (Eval ds) = Eval (mapDmds argDemand ds)
1080 argDemand (Box Bot) = evalDmd
1081 argDemand (Box d) = box (argDemand d)
1082 argDemand Bot = Abs -- Don't pass args that are consumed (only) by bottom
1087 -------------------------
1088 lubType :: DmdType -> DmdType -> DmdType
1089 -- Consider (if x then y else []) with demand V
1090 -- Then the first branch gives {y->V} and the second
1091 -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
1092 -- in the result env.
1093 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
1094 = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
1096 lub_fv = plusVarEnv_C lub fv1 fv2
1097 lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
1098 lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
1099 -- lub is the identity for Bot
1101 -- Extend the shorter argument list to match the longer
1102 lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
1104 lub_ds ds1 [] = map (`lub` resTypeArgDmd r2) ds1
1105 lub_ds [] ds2 = map (resTypeArgDmd r1 `lub`) ds2
1107 -----------------------------------
1108 bothType :: DmdType -> DmdType -> DmdType
1109 -- (t1 `bothType` t2) takes the argument/result info from t1,
1110 -- using t2 just for its free-var info
1111 -- NB: Don't forget about r2! It might be BotRes, which is
1112 -- a bottom demand on all the in-scope variables.
1113 -- Peter: can this be done more neatly?
1114 bothType (DmdType fv1 ds1 r1) (DmdType fv2 _ r2)
1115 = DmdType both_fv2 ds1 (r1 `bothRes` r2)
1117 both_fv = plusVarEnv_C both fv1 fv2
1118 both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
1119 both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
1120 -- both is the identity for Abs
1125 lubRes :: DmdResult -> DmdResult -> DmdResult
1128 lubRes RetCPR RetCPR = RetCPR
1131 bothRes :: DmdResult -> DmdResult -> DmdResult
1132 -- If either diverges, the whole thing does
1133 -- Otherwise take CPR info from the first
1134 bothRes _ BotRes = BotRes
1139 modifyEnv :: Bool -- No-op if False
1140 -> (Demand -> Demand) -- The zapper
1141 -> DmdEnv -> DmdEnv -- Env1 and Env2
1142 -> DmdEnv -> DmdEnv -- Transform this env
1143 -- Zap anything in Env1 but not in Env2
1144 -- Assume: dom(env) includes dom(Env1) and dom(Env2)
1146 modifyEnv need_to_modify zapper env1 env2 env
1147 | need_to_modify = foldr zap env (varEnvKeys (env1 `minusUFM` env2))
1150 zap uniq env = addToUFM_Directly env uniq (zapper current_val)
1152 current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
1156 %************************************************************************
1158 \subsection{LUB and BOTH}
1160 %************************************************************************
1163 lub :: Demand -> Demand -> Demand
1166 lub Abs d2 = absLub d2
1168 lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
1170 lub (Call d1) (Call d2) = Call (d1 `lub` d2)
1171 lub d1@(Call _) (Box d2) = d1 `lub` d2 -- Just strip the box
1172 lub (Call _) d2@(Eval _) = d2 -- Presumably seq or vanilla eval
1173 lub d1@(Call _) d2 = d2 `lub` d1 -- Bot, Abs, Top
1175 -- For the Eval case, we use these approximation rules
1176 -- Box Bot <= Eval (Box Bot ...)
1177 -- Box Top <= Defer (Box Bot ...)
1178 -- Box (Eval ds) <= Eval (map Box ds)
1179 lub (Eval ds1) (Eval ds2) = Eval (ds1 `lubs` ds2)
1180 lub (Eval ds1) (Box Bot) = Eval (mapDmds (`lub` Box Bot) ds1)
1181 lub (Eval ds1) (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
1182 lub (Eval ds1) (Box Abs) = deferEval (mapDmds (`lub` Box Bot) ds1)
1183 lub d1@(Eval _) d2 = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
1185 lub (Box d1) (Box d2) = box (d1 `lub` d2)
1186 lub d1@(Box _) d2 = d2 `lub` d1
1188 lubs :: Demands -> Demands -> Demands
1189 lubs ds1 ds2 = zipWithDmds lub ds1 ds2
1191 ---------------------
1192 box :: Demand -> Demand
1193 -- box is the smart constructor for Box
1194 -- It computes <B,bot> & d
1195 -- INVARIANT: (Box d) => d = Bot, Abs, Eval
1196 -- Seems to be no point in allowing (Box (Call d))
1197 box (Call d) = Call d -- The odd man out. Why?
1199 box (Defer _) = lazyDmd
1200 box Top = lazyDmd -- Box Abs and Box Top
1201 box Abs = lazyDmd -- are the same <B,L>
1202 box d = Box d -- Bot, Eval
1205 defer :: Demand -> Demand
1207 -- defer is the smart constructor for Defer
1208 -- The idea is that (Defer ds) = <U(ds), L>
1210 -- It specifies what happens at a lazy function argument
1211 -- or a lambda; the L* operator
1212 -- Set the strictness part to L, but leave
1213 -- the boxity side unaffected
1214 -- It also ensures that Defer (Eval [LLLL]) = L
1219 defer (Call _) = lazyDmd -- Approximation here?
1220 defer (Box _) = lazyDmd
1221 defer (Defer ds) = Defer ds
1222 defer (Eval ds) = deferEval ds
1224 deferEval :: Demands -> Demand
1225 -- deferEval ds = defer (Eval ds)
1226 deferEval ds | allTop ds = Top
1227 | otherwise = Defer ds
1229 ---------------------
1230 absLub :: Demand -> Demand
1231 -- Computes (Abs `lub` d)
1232 -- For the Bot case consider
1233 -- f x y = if ... then x else error x
1234 -- Then for y we get Abs `lub` Bot, and we really
1239 absLub (Call _) = Top
1240 absLub (Box _) = Top
1241 absLub (Eval ds) = Defer (absLubs ds) -- Or (Defer ds)?
1242 absLub (Defer ds) = Defer (absLubs ds) -- Or (Defer ds)?
1244 absLubs :: Demands -> Demands
1245 absLubs = mapDmds absLub
1248 both :: Demand -> Demand -> Demand
1252 -- Note [Bottom demands]
1255 both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
1256 both Bot (Defer ds) = Eval (mapDmds (`both` Bot) ds)
1259 both Top Bot = errDmd
1262 both Top (Box d) = Box d
1263 both Top (Call d) = Call d
1264 both Top (Eval ds) = Eval (mapDmds (`both` Top) ds)
1265 both Top (Defer ds) -- = defer (Top `both` Eval ds)
1266 -- = defer (Eval (mapDmds (`both` Top) ds))
1267 = deferEval (mapDmds (`both` Top) ds)
1270 both (Box d1) (Box d2) = box (d1 `both` d2)
1271 both (Box d1) d2@(Call _) = box (d1 `both` d2)
1272 both (Box d1) d2@(Eval _) = box (d1 `both` d2)
1273 both (Box d1) (Defer _) = Box d1
1274 both d1@(Box _) d2 = d2 `both` d1
1276 both (Call d1) (Call d2) = Call (d1 `both` d2)
1277 both (Call d1) (Eval _) = Call d1 -- Could do better for (Poly Bot)?
1278 both (Call d1) (Defer _) = Call d1 -- Ditto
1279 both d1@(Call _) d2 = d2 `both` d1
1281 both (Eval ds1) (Eval ds2) = Eval (ds1 `boths` ds2)
1282 both (Eval ds1) (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
1283 both d1@(Eval _) d2 = d2 `both` d1
1285 both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
1286 both d1@(Defer _) d2 = d2 `both` d1
1288 boths :: Demands -> Demands -> Demands
1289 boths ds1 ds2 = zipWithDmds both ds1 ds2
1292 Note [Bottom demands]
1293 ~~~~~~~~~~~~~~~~~~~~~
1296 From 'error' itself we get demand Bot on x
1297 From the arg demand on x we get
1298 x :-> evalDmd = Box (Eval (Poly Abs))
1299 So we get Bot `both` Box (Eval (Poly Abs))
1300 = Seq Keep (Poly Bot)
1303 f x = if ... then error (fst x) else fst x
1304 Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
1306 which is what we want.
1311 x :-> Bot `both` Defer [SA]
1312 and we want the Bot demand to cancel out the Defer
1313 so that we get Eval [SA]. Otherwise we'd have the odd
1315 f x = error (fst x) -- Strictness U(SA)b
1316 g x = error ('y':fst x) -- Strictness Tb