2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
10 module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs,
11 both {- needed by WwLib -}
14 #include "HsVersions.h"
16 import DynFlags ( DynFlags, DynFlag(..) )
17 import StaticFlags ( opt_MaxWorkerArgs )
18 import NewDemand -- All of it
21 import CoreUtils ( exprIsHNF, exprIsTrivial, exprArity )
22 import DataCon ( dataConTyCon )
23 import TyCon ( isProductTyCon, isRecursiveTyCon )
24 import Id ( Id, idType, idInlinePragma,
25 isDataConWorkId, isGlobalId, idArity,
27 idDemandInfo, idStrictness, idCprInfo, idName,
29 idNewStrictness, idNewStrictness_maybe,
30 setIdNewStrictness, idNewDemandInfo,
31 idNewDemandInfo_maybe,
35 import IdInfo ( newStrictnessFromOld, newDemand )
39 import TysWiredIn ( unboxedPairDataCon )
40 import TysPrim ( realWorldStatePrimTy )
41 import UniqFM ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
42 keysUFM, minusUFM, ufmToList, filterUFM )
43 import Type ( isUnLiftedType, coreEqType, splitTyConApp_maybe )
44 import Coercion ( coercionKind )
45 import CoreLint ( showPass, endPass )
46 import Util ( mapAndUnzip, lengthIs )
47 import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
49 import Maybes ( orElse, expectJust )
57 * set a noinline pragma on bottoming Ids
59 * Consider f x = x+1 `fatbar` error (show x)
60 We'd like to unbox x, even if that means reboxing it in the error case.
63 %************************************************************************
65 \subsection{Top level stuff}
67 %************************************************************************
70 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
71 dmdAnalPgm dflags binds
73 showPass dflags "Demand analysis" ;
74 let { binds_plus_dmds = do_prog binds } ;
76 endPass dflags "Demand analysis"
77 Opt_D_dump_stranal binds_plus_dmds ;
79 -- Only if OLD_STRICTNESS is on, because only then is the old
80 -- strictness analyser run
81 let { dmd_changes = get_changes binds_plus_dmds } ;
82 printDump (text "Changes in demands" $$ dmd_changes) ;
84 return binds_plus_dmds
87 do_prog :: [CoreBind] -> [CoreBind]
88 do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
90 dmdAnalTopBind :: SigEnv
93 dmdAnalTopBind sigs (NonRec id rhs)
95 ( _, _, (_, rhs1)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs)
96 (sigs2, _, (id2, rhs2)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs1)
97 -- Do two passes to improve CPR information
98 -- See comments with ignore_cpr_info in mk_sig_ty
99 -- and with extendSigsWithLam
101 (sigs2, NonRec id2 rhs2)
103 dmdAnalTopBind sigs (Rec pairs)
105 (sigs', _, pairs') = dmdFix TopLevel sigs pairs
106 -- We get two iterations automatically
107 -- c.f. the NonRec case above
113 dmdAnalTopRhs :: CoreExpr -> (StrictSig, CoreExpr)
114 -- Analyse the RHS and return
115 -- a) appropriate strictness info
116 -- b) the unfolding (decorated with stricntess info)
120 call_dmd = vanillaCall (exprArity rhs)
121 (_, rhs1) = dmdAnal emptySigEnv call_dmd rhs
122 (rhs_ty, rhs2) = dmdAnal emptySigEnv call_dmd rhs1
123 sig = mkTopSigTy rhs rhs_ty
124 -- Do two passes; see notes with extendSigsWithLam
125 -- Otherwise we get bogus CPR info for constructors like
126 -- newtype T a = MkT a
127 -- The constructor looks like (\x::T a -> x), modulo the coerce
128 -- extendSigsWithLam will optimistically give x a CPR tag the
129 -- first time, which is wrong in the end.
132 %************************************************************************
134 \subsection{The analyser itself}
136 %************************************************************************
139 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
141 dmdAnal sigs Abs e = (topDmdType, e)
144 | not (isStrictDmd dmd)
146 (res_ty, e') = dmdAnal sigs evalDmd e
148 (deferType res_ty, e')
149 -- It's important not to analyse e with a lazy demand because
150 -- a) When we encounter case s of (a,b) ->
151 -- we demand s with U(d1d2)... but if the overall demand is lazy
152 -- that is wrong, and we'd need to reduce the demand on s,
153 -- which is inconvenient
154 -- b) More important, consider
155 -- f (let x = R in x+x), where f is lazy
156 -- We still want to mark x as demanded, because it will be when we
157 -- enter the let. If we analyse f's arg with a Lazy demand, we'll
158 -- just mark x as Lazy
159 -- c) The application rule wouldn't be right either
160 -- Evaluating (f x) in a L demand does *not* cause
161 -- evaluation of f in a C(L) demand!
164 dmdAnal sigs dmd (Lit lit)
165 = (topDmdType, Lit lit)
167 dmdAnal sigs dmd (Var var)
168 = (dmdTransform sigs var dmd, Var var)
170 dmdAnal sigs dmd (Cast e co)
171 = (dmd_ty, Cast e' co)
173 (dmd_ty, e') = dmdAnal sigs dmd' e
174 to_co = snd (coercionKind co)
176 | Just (tc, args) <- splitTyConApp_maybe to_co
177 , isRecursiveTyCon tc = evalDmd
179 -- This coerce usually arises from a recursive
180 -- newtype, and we don't want to look inside them
181 -- for exactly the same reason that we don't look
182 -- inside recursive products -- we might not reach
183 -- a fixpoint. So revert to a vanilla Eval demand
185 dmdAnal sigs dmd (Note n e)
186 = (dmd_ty, Note n e')
188 (dmd_ty, e') = dmdAnal sigs dmd e
190 dmdAnal sigs dmd (App fun (Type ty))
191 = (fun_ty, App fun' (Type ty))
193 (fun_ty, fun') = dmdAnal sigs dmd fun
195 -- Lots of the other code is there to make this
196 -- beautiful, compositional, application rule :-)
197 dmdAnal sigs dmd e@(App fun arg) -- Non-type arguments
198 = let -- [Type arg handled above]
199 (fun_ty, fun') = dmdAnal sigs (Call dmd) fun
200 (arg_ty, arg') = dmdAnal sigs arg_dmd arg
201 (arg_dmd, res_ty) = splitDmdTy fun_ty
203 (res_ty `bothType` arg_ty, App fun' arg')
205 dmdAnal sigs dmd (Lam var body)
208 (body_ty, body') = dmdAnal sigs dmd body
210 (body_ty, Lam var body')
212 | Call body_dmd <- dmd -- A call demand: good!
214 sigs' = extendSigsWithLam sigs var
215 (body_ty, body') = dmdAnal sigs' body_dmd body
216 (lam_ty, var') = annotateLamIdBndr body_ty var
218 (lam_ty, Lam var' body')
220 | otherwise -- Not enough demand on the lambda; but do the body
221 = let -- anyway to annotate it and gather free var info
222 (body_ty, body') = dmdAnal sigs evalDmd body
223 (lam_ty, var') = annotateLamIdBndr body_ty var
225 (deferType lam_ty, Lam var' body')
227 dmdAnal sigs dmd (Case scrut case_bndr ty [alt@(DataAlt dc,bndrs,rhs)])
228 | let tycon = dataConTyCon dc,
229 isProductTyCon tycon,
230 not (isRecursiveTyCon tycon)
232 sigs_alt = extendSigEnv NotTopLevel sigs case_bndr case_bndr_sig
233 (alt_ty, alt') = dmdAnalAlt sigs_alt dmd alt
234 (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
235 (_, bndrs', _) = alt'
236 case_bndr_sig = cprSig
237 -- Inside the alternative, the case binder has the CPR property.
238 -- Meaning that a case on it will successfully cancel.
240 -- f True x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
243 -- We want f to have the CPR property:
244 -- f b x = case fw b x of { r -> I# r }
245 -- fw True x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
248 -- Figure out whether the demand on the case binder is used, and use
249 -- that to set the scrut_dmd. This is utterly essential.
250 -- Consider f x = case x of y { (a,b) -> k y a }
251 -- If we just take scrut_demand = U(L,A), then we won't pass x to the
252 -- worker, so the worker will rebuild
253 -- x = (a, absent-error)
254 -- and that'll crash.
255 -- So at one stage I had:
256 -- dead_case_bndr = isAbsentDmd (idNewDemandInfo case_bndr')
257 -- keepity | dead_case_bndr = Drop
258 -- | otherwise = Keep
261 -- case x of y { (a,b) -> h y + a }
262 -- where h : U(LL) -> T
263 -- The above code would compute a Keep for x, since y is not Abs, which is silly
264 -- The insight is, of course, that a demand on y is a demand on the
265 -- scrutinee, so we need to `both` it with the scrut demand
267 alt_dmd = Eval (Prod [idNewDemandInfo b | b <- bndrs', isId b])
268 scrut_dmd = alt_dmd `both`
269 idNewDemandInfo case_bndr'
271 (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut
273 (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' ty [alt'])
275 dmdAnal sigs dmd (Case scrut case_bndr ty alts)
277 (alt_tys, alts') = mapAndUnzip (dmdAnalAlt sigs dmd) alts
278 (scrut_ty, scrut') = dmdAnal sigs evalDmd scrut
279 (alt_ty, case_bndr') = annotateBndr (foldr1 lubType alt_tys) case_bndr
281 -- pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
282 (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' ty alts')
284 dmdAnal sigs dmd (Let (NonRec id rhs) body)
286 (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs NotTopLevel NonRecursive sigs (id, rhs)
287 (body_ty, body') = dmdAnal sigs' dmd body
288 (body_ty1, id2) = annotateBndr body_ty id1
289 body_ty2 = addLazyFVs body_ty1 lazy_fv
291 -- If the actual demand is better than the vanilla call
292 -- demand, you might think that we might do better to re-analyse
293 -- the RHS with the stronger demand.
294 -- But (a) That seldom happens, because it means that *every* path in
295 -- the body of the let has to use that stronger demand
296 -- (b) It often happens temporarily in when fixpointing, because
297 -- the recursive function at first seems to place a massive demand.
298 -- But we don't want to go to extra work when the function will
299 -- probably iterate to something less demanding.
300 -- In practice, all the times the actual demand on id2 is more than
301 -- the vanilla call demand seem to be due to (b). So we don't
302 -- bother to re-analyse the RHS.
303 (body_ty2, Let (NonRec id2 rhs') body')
305 dmdAnal sigs dmd (Let (Rec pairs) body)
307 bndrs = map fst pairs
308 (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
309 (body_ty, body') = dmdAnal sigs' dmd body
310 body_ty1 = addLazyFVs body_ty lazy_fv
312 sigs' `seq` body_ty `seq`
314 (body_ty2, _) = annotateBndrs body_ty1 bndrs
315 -- Don't bother to add demand info to recursive
316 -- binders as annotateBndr does;
317 -- being recursive, we can't treat them strictly.
318 -- But we do need to remove the binders from the result demand env
320 (body_ty2, Let (Rec pairs') body')
323 dmdAnalAlt sigs dmd (con,bndrs,rhs)
325 (rhs_ty, rhs') = dmdAnal sigs dmd rhs
326 (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
327 final_alt_ty | io_hack_reqd = alt_ty `lubType` topDmdType
330 -- There's a hack here for I/O operations. Consider
331 -- case foo x s of { (# s, r #) -> y }
332 -- Is this strict in 'y'. Normally yes, but what if 'foo' is an I/O
333 -- operation that simply terminates the program (not in an erroneous way)?
334 -- In that case we should not evaluate y before the call to 'foo'.
335 -- Hackish solution: spot the IO-like situation and add a virtual branch,
339 -- other -> return ()
340 -- So the 'y' isn't necessarily going to be evaluated
342 -- A more complete example where this shows up is:
343 -- do { let len = <expensive> ;
344 -- ; when (...) (exitWith ExitSuccess)
347 io_hack_reqd = con == DataAlt unboxedPairDataCon &&
348 idType (head bndrs) `coreEqType` realWorldStatePrimTy
350 (final_alt_ty, (con, bndrs', rhs'))
353 %************************************************************************
355 \subsection{Bindings}
357 %************************************************************************
360 dmdFix :: TopLevelFlag
361 -> SigEnv -- Does not include bindings for this binding
364 [(Id,CoreExpr)]) -- Binders annotated with stricness info
366 dmdFix top_lvl sigs orig_pairs
367 = loop 1 initial_sigs orig_pairs
369 bndrs = map fst orig_pairs
370 initial_sigs = extendSigEnvList sigs [(id, (initialSig id, top_lvl)) | id <- bndrs]
373 -> SigEnv -- Already contains the current sigs
375 -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
378 = (sigs', lazy_fv, pairs')
379 -- Note: use pairs', not pairs. pairs' is the result of
380 -- processing the RHSs with sigs (= sigs'), whereas pairs
381 -- is the result of processing the RHSs with the *previous*
382 -- iteration of sigs.
384 | n >= 10 = pprTrace "dmdFix loop" (ppr n <+> (vcat
385 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
386 text "env:" <+> ppr (ufmToList sigs),
387 text "binds:" <+> pprCoreBinding (Rec pairs)]))
388 (emptySigEnv, lazy_fv, orig_pairs) -- Safe output
389 -- The lazy_fv part is really important! orig_pairs has no strictness
390 -- info, including nothing about free vars. But if we have
391 -- letrec f = ....y..... in ...f...
392 -- where 'y' is free in f, we must record that y is mentioned,
393 -- otherwise y will get recorded as absent altogether
395 | otherwise = loop (n+1) sigs' pairs'
397 found_fixpoint = all (same_sig sigs sigs') bndrs
398 -- Use the new signature to do the next pair
399 -- The occurrence analyser has arranged them in a good order
400 -- so this can significantly reduce the number of iterations needed
401 ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
403 my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
404 = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
406 -- pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' )
407 ((sigs', lazy_fv'), pair')
410 (sigs', lazy_fv1, pair') = dmdAnalRhs top_lvl Recursive sigs (id,rhs)
411 lazy_fv' = plusUFM_C both lazy_fv lazy_fv1
412 -- old_sig = lookup sigs id
413 -- new_sig = lookup sigs' id
415 same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
416 lookup sigs var = case lookupVarEnv sigs var of
419 -- Get an initial strictness signature from the Id
420 -- itself. That way we make use of earlier iterations
421 -- of the fixpoint algorithm. (Cunning plan.)
422 -- Note that the cunning plan extends to the DmdEnv too,
423 -- since it is part of the strictness signature
424 initialSig id = idNewStrictness_maybe id `orElse` botSig
426 dmdAnalRhs :: TopLevelFlag -> RecFlag
427 -> SigEnv -> (Id, CoreExpr)
428 -> (SigEnv, DmdEnv, (Id, CoreExpr))
429 -- Process the RHS of the binding, add the strictness signature
430 -- to the Id, and augment the environment with the signature as well.
432 dmdAnalRhs top_lvl rec_flag sigs (id, rhs)
433 = (sigs', lazy_fv, (id', rhs'))
435 arity = idArity id -- The idArity should be up to date
436 -- The simplifier was run just beforehand
437 (rhs_dmd_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
438 (lazy_fv, sig_ty) = WARN( arity /= dmdTypeDepth rhs_dmd_ty && not (exprIsTrivial rhs), ppr id )
439 -- The RHS can be eta-reduced to just a variable,
440 -- in which case we should not complain.
441 mkSigTy top_lvl rec_flag id rhs rhs_dmd_ty
442 id' = id `setIdNewStrictness` sig_ty
443 sigs' = extendSigEnv top_lvl sigs id sig_ty
446 %************************************************************************
448 \subsection{Strictness signatures and types}
450 %************************************************************************
453 mkTopSigTy :: CoreExpr -> DmdType -> StrictSig
454 -- Take a DmdType and turn it into a StrictSig
455 -- NB: not used for never-inline things; hence False
456 mkTopSigTy rhs dmd_ty = snd (mk_sig_ty False False rhs dmd_ty)
458 mkSigTy :: TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
459 mkSigTy top_lvl rec_flag id rhs dmd_ty
460 = mk_sig_ty never_inline thunk_cpr_ok rhs dmd_ty
462 never_inline = isNeverActive (idInlinePragma id)
463 maybe_id_dmd = idNewDemandInfo_maybe id
464 -- Is Nothing the first time round
467 | isTopLevel top_lvl = False -- Top level things don't get
468 -- their demandInfo set at all
469 | isRec rec_flag = False -- Ditto recursive things
470 | Just dmd <- maybe_id_dmd = isStrictDmd dmd
471 | otherwise = True -- Optimistic, first time round
475 The thunk_cpr_ok stuff [CPR-AND-STRICTNESS]
476 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
477 If the rhs is a thunk, we usually forget the CPR info, because
478 it is presumably shared (else it would have been inlined, and
479 so we'd lose sharing if w/w'd it into a function). E.g.
481 let r = case expensive of
485 If we marked r as having the CPR property, then we'd w/w into
487 let $wr = \() -> case expensive of
493 But now r is a thunk, which won't be inlined, so we are no further ahead.
496 f x = let r = case expensive of (a,b) -> (b,a)
497 in if foo r then r else (x,x)
499 Does f have the CPR property? Well, no.
501 However, if the strictness analyser has figured out (in a previous
502 iteration) that it's strict, then we DON'T need to forget the CPR info.
503 Instead we can retain the CPR info and do the thunk-splitting transform
504 (see WorkWrap.splitThunk).
506 This made a big difference to PrelBase.modInt, which had something like
507 modInt = \ x -> let r = ... -> I# v in
508 ...body strict in r...
509 r's RHS isn't a value yet; but modInt returns r in various branches, so
510 if r doesn't have the CPR property then neither does modInt
511 Another case I found in practice (in Complex.magnitude), looks like this:
512 let k = if ... then I# a else I# b
513 in ... body strict in k ....
514 (For this example, it doesn't matter whether k is returned as part of
515 the overall result; but it does matter that k's RHS has the CPR property.)
516 Left to itself, the simplifier will make a join point thus:
517 let $j k = ...body strict in k...
518 if ... then $j (I# a) else $j (I# b)
519 With thunk-splitting, we get instead
520 let $j x = let k = I#x in ...body strict in k...
521 in if ... then $j a else $j b
522 This is much better; there's a good chance the I# won't get allocated.
524 The difficulty with this is that we need the strictness type to
525 look at the body... but we now need the body to calculate the demand
526 on the variable, so we can decide whether its strictness type should
527 have a CPR in it or not. Simple solution:
528 a) use strictness info from the previous iteration
529 b) make sure we do at least 2 iterations, by doing a second
530 round for top-level non-recs. Top level recs will get at
531 least 2 iterations except for totally-bottom functions
532 which aren't very interesting anyway.
534 NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
536 The Nothing case in thunk_cpr_ok [CPR-AND-STRICTNESS]
537 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
538 Demand info now has a 'Nothing' state, just like strictness info.
539 The analysis works from 'dangerous' towards a 'safe' state; so we
540 start with botSig for 'Nothing' strictness infos, and we start with
541 "yes, it's demanded" for 'Nothing' in the demand info. The
542 fixpoint iteration will sort it all out.
544 We can't start with 'not-demanded' because then consider
548 if ... then t else I# y else f x'
550 In the first iteration we'd have no demand info for x, so assume
551 not-demanded; then we'd get TopRes for f's CPR info. Next iteration
552 we'd see that t was demanded, and so give it the CPR property, but by
553 now f has TopRes, so it will stay TopRes. Instead, with the Nothing
554 setting the first time round, we say 'yes t is demanded' the first
557 However, this does mean that for non-recursive bindings we must
558 iterate twice to be sure of not getting over-optimistic CPR info,
559 in the case where t turns out to be not-demanded. This is handled
564 mk_sig_ty never_inline thunk_cpr_ok rhs (DmdType fv dmds res)
565 = (lazy_fv, mkStrictSig dmd_ty)
567 dmd_ty = DmdType strict_fv final_dmds res'
569 lazy_fv = filterUFM (not . isStrictDmd) fv
570 strict_fv = filterUFM isStrictDmd fv
571 -- We put the strict FVs in the DmdType of the Id, so
572 -- that at its call sites we unleash demands on its strict fvs.
573 -- An example is 'roll' in imaginary/wheel-sieve2
574 -- Something like this:
576 -- go y = if ... then roll (x-1) else x+1
579 -- We want to see that roll is strict in x, which is because
580 -- go is called. So we put the DmdEnv for x in go's DmdType.
583 -- f :: Int -> Int -> Int
584 -- f x y = let t = x+1
585 -- h z = if z==0 then t else
586 -- if z==1 then x+1 else
590 -- Calling h does indeed evaluate x, but we can only see
591 -- that if we unleash a demand on x at the call site for t.
593 -- Incidentally, here's a place where lambda-lifting h would
594 -- lose the cigar --- we couldn't see the joint strictness in t/x
597 -- We don't want to put *all* the fv's from the RHS into the
598 -- DmdType, because that makes fixpointing very slow --- the
599 -- DmdType gets full of lazy demands that are slow to converge.
601 final_dmds = setUnpackStrategy dmds
602 -- Set the unpacking strategy
605 RetCPR | ignore_cpr_info -> TopRes
607 ignore_cpr_info = not (exprIsHNF rhs || thunk_cpr_ok)
610 The unpack strategy determines whether we'll *really* unpack the argument,
611 or whether we'll just remember its strictness. If unpacking would give
612 rise to a *lot* of worker args, we may decide not to unpack after all.
615 setUnpackStrategy :: [Demand] -> [Demand]
617 = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
619 go :: Int -- Max number of args available for sub-components of [Demand]
621 -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
623 go n (Eval (Prod cs) : ds)
624 | n' >= 0 = Eval (Prod cs') `cons` go n'' ds
625 | otherwise = Box (Eval (Prod cs)) `cons` go n ds
628 n' = n + 1 - non_abs_args
629 -- Add one to the budget 'cos we drop the top-level arg
630 non_abs_args = nonAbsentArgs cs
631 -- Delete # of non-absent args to which we'll now be committed
633 go n (d:ds) = d `cons` go n ds
636 cons d (n,ds) = (n, d:ds)
638 nonAbsentArgs :: [Demand] -> Int
640 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
641 nonAbsentArgs (d : ds) = 1 + nonAbsentArgs ds
645 %************************************************************************
647 \subsection{Strictness signatures and types}
649 %************************************************************************
652 splitDmdTy :: DmdType -> (Demand, DmdType)
653 -- Split off one function argument
654 -- We already have a suitable demand on all
655 -- free vars, so no need to add more!
656 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
657 splitDmdTy ty@(DmdType fv [] res_ty) = (resTypeArgDmd res_ty, ty)
661 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
663 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
664 | isTopLevel top_lvl = dmd_ty -- Don't record top level things
665 | otherwise = DmdType (extendVarEnv fv var dmd) ds res
667 addLazyFVs (DmdType fv ds res) lazy_fvs
668 = DmdType both_fv1 ds res
670 both_fv = (plusUFM_C both fv lazy_fvs)
671 both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
672 -- This modifyEnv is vital. Consider
673 -- let f = \x -> (x,y)
675 -- Here, y is treated as a lazy-fv of f, but we must `both` that L
676 -- demand with the bottom coming up from 'error'
678 -- I got a loop in the fixpointer without this, due to an interaction
679 -- with the lazy_fv filtering in mkSigTy. Roughly, it was
681 -- = letrec g y = x `fatbar`
682 -- letrec h z = z + ...g...
685 -- In the initial iteration for f, f=Bot
686 -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
687 -- is lazy. Now consider the fixpoint iteration for g, esp the demands it
688 -- places on its free variables. Suppose it places none. Then the
689 -- x `fatbar` ...call to h...
690 -- will give a x->V demand for x. That turns into a L demand for x,
691 -- which floats out of the defn for h. Without the modifyEnv, that
692 -- L demand doesn't get both'd with the Bot coming up from the inner
693 -- call to f. So we just get an L demand for x for g.
695 -- A better way to say this is that the lazy-fv filtering should give the
696 -- same answer as putting the lazy fv demands in the function's type.
698 annotateBndr :: DmdType -> Var -> (DmdType, Var)
699 -- The returned env has the var deleted
700 -- The returned var is annotated with demand info
701 -- No effect on the argument demands
702 annotateBndr dmd_ty@(DmdType fv ds res) var
703 | isTyVar var = (dmd_ty, var)
704 | otherwise = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
706 (fv', dmd) = removeFV fv var res
708 annotateBndrs = mapAccumR annotateBndr
710 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
711 -- For lambdas we add the demand to the argument demands
712 -- Only called for Ids
714 (DmdType fv' (hacked_dmd:ds) res, setIdNewDemandInfo id hacked_dmd)
716 (fv', dmd) = removeFV fv id res
717 hacked_dmd = argDemand dmd
718 -- This call to argDemand is vital, because otherwise we label
719 -- a lambda binder with demand 'B'. But in terms of calling
720 -- conventions that's Abs, because we don't pass it. But
721 -- when we do a w/w split we get
722 -- fw x = (\x y:B -> ...) x (error "oops")
723 -- And then the simplifier things the 'B' is a strict demand
724 -- and evaluates the (error "oops"). Sigh
726 removeFV fv id res = (fv', zapUnlifted id dmd)
728 fv' = fv `delVarEnv` id
729 dmd = lookupVarEnv fv id `orElse` deflt
730 deflt | isBotRes res = Bot
733 -- For unlifted-type variables, we are only
734 -- interested in Bot/Abs/Box Abs
735 zapUnlifted is Bot = Bot
736 zapUnlifted id Abs = Abs
737 zapUnlifted id dmd | isUnLiftedType (idType id) = lazyDmd
741 %************************************************************************
743 \subsection{Strictness signatures}
745 %************************************************************************
748 type SigEnv = VarEnv (StrictSig, TopLevelFlag)
749 -- We use the SigEnv to tell us whether to
750 -- record info about a variable in the DmdEnv
751 -- We do so if it's a LocalId, but not top-level
753 -- The DmdEnv gives the demand on the free vars of the function
754 -- when it is given enough args to satisfy the strictness signature
756 emptySigEnv = emptyVarEnv
758 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
759 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
761 extendSigEnvList = extendVarEnvList
763 extendSigsWithLam :: SigEnv -> Id -> SigEnv
764 -- Extend the SigEnv when we meet a lambda binder
765 -- If the binder is marked demanded with a product demand, then give it a CPR
766 -- signature, because in the likely event that this is a lambda on a fn defn
767 -- [we only use this when the lambda is being consumed with a call demand],
768 -- it'll be w/w'd and so it will be CPR-ish. E.g.
769 -- f = \x::(Int,Int). if ...strict in x... then
773 -- We want f to have the CPR property because x does, by the time f has been w/w'd
775 -- Also note that we only want to do this for something that
776 -- definitely has product type, else we may get over-optimistic
777 -- CPR results (e.g. from \x -> x!).
779 extendSigsWithLam sigs id
780 = case idNewDemandInfo_maybe id of
781 Nothing -> extendVarEnv sigs id (cprSig, NotTopLevel)
782 -- Optimistic in the Nothing case;
783 -- See notes [CPR-AND-STRICTNESS]
784 Just (Eval (Prod ds)) -> extendVarEnv sigs id (cprSig, NotTopLevel)
788 dmdTransform :: SigEnv -- The strictness environment
789 -> Id -- The function
790 -> Demand -- The demand on the function
791 -> DmdType -- The demand type of the function in this context
792 -- Returned DmdEnv includes the demand on
793 -- this function plus demand on its free variables
795 dmdTransform sigs var dmd
797 ------ DATA CONSTRUCTOR
798 | isDataConWorkId var -- Data constructor
800 StrictSig dmd_ty = idNewStrictness var -- It must have a strictness sig
801 DmdType _ _ con_res = dmd_ty
804 if arity == call_depth then -- Saturated, so unleash the demand
806 -- Important! If we Keep the constructor application, then
807 -- we need the demands the constructor places (always lazy)
808 -- If not, we don't need to. For example:
809 -- f p@(x,y) = (p,y) -- S(AL)
811 -- It's vital that we don't calculate Absent for a!
812 dmd_ds = case res_dmd of
813 Box (Eval ds) -> mapDmds box ds
817 -- ds can be empty, when we are just seq'ing the thing
818 -- If so we must make up a suitable bunch of demands
819 arg_ds = case dmd_ds of
820 Poly d -> replicate arity d
821 Prod ds -> ASSERT( ds `lengthIs` arity ) ds
824 mkDmdType emptyDmdEnv arg_ds con_res
825 -- Must remember whether it's a product, hence con_res, not TopRes
829 ------ IMPORTED FUNCTION
830 | isGlobalId var, -- Imported function
831 let StrictSig dmd_ty = idNewStrictness var
832 = if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
837 ------ LOCAL LET/REC BOUND THING
838 | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
840 fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
841 | otherwise = deferType dmd_ty
842 -- NB: it's important to use deferType, and not just return topDmdType
843 -- Consider let { f x y = p + x } in f 1
844 -- The application isn't saturated, but we must nevertheless propagate
845 -- a lazy demand for p!
847 addVarDmd top_lvl fn_ty var dmd
849 ------ LOCAL NON-LET/REC BOUND THING
850 | otherwise -- Default case
854 (call_depth, res_dmd) = splitCallDmd dmd
858 %************************************************************************
862 %************************************************************************
865 splitCallDmd :: Demand -> (Int, Demand)
866 splitCallDmd (Call d) = case splitCallDmd d of
868 splitCallDmd d = (0, d)
870 vanillaCall :: Arity -> Demand
871 vanillaCall 0 = evalDmd
872 vanillaCall n = Call (vanillaCall (n-1))
874 deferType :: DmdType -> DmdType
875 deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
876 -- Notice that we throw away info about both arguments and results
877 -- For example, f = let ... in \x -> x
878 -- We don't want to get a stricness type V->T for f.
881 deferEnv :: DmdEnv -> DmdEnv
882 deferEnv fv = mapVarEnv defer fv
886 argDemand :: Demand -> Demand
887 -- The 'Defer' demands are just Lazy at function boundaries
888 -- Ugly! Ask John how to improve it.
889 argDemand Top = lazyDmd
890 argDemand (Defer d) = lazyDmd
891 argDemand (Eval ds) = Eval (mapDmds argDemand ds)
892 argDemand (Box Bot) = evalDmd
893 argDemand (Box d) = box (argDemand d)
894 argDemand Bot = Abs -- Don't pass args that are consumed (only) by bottom
899 -------------------------
900 -- Consider (if x then y else []) with demand V
901 -- Then the first branch gives {y->V} and the second
902 -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
903 -- in the result env.
904 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
905 = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
907 lub_fv = plusUFM_C lub fv1 fv2
908 lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
909 lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
910 -- lub is the identity for Bot
912 -- Extend the shorter argument list to match the longer
913 lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
915 lub_ds ds1 [] = map (`lub` resTypeArgDmd r2) ds1
916 lub_ds [] ds2 = map (resTypeArgDmd r1 `lub`) ds2
918 -----------------------------------
919 -- (t1 `bothType` t2) takes the argument/result info from t1,
920 -- using t2 just for its free-var info
921 -- NB: Don't forget about r2! It might be BotRes, which is
922 -- a bottom demand on all the in-scope variables.
923 -- Peter: can this be done more neatly?
924 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
925 = DmdType both_fv2 ds1 (r1 `bothRes` r2)
927 both_fv = plusUFM_C both fv1 fv2
928 both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
929 both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
930 -- both is the identity for Abs
937 lubRes RetCPR RetCPR = RetCPR
938 lubRes r1 r2 = TopRes
940 -- If either diverges, the whole thing does
941 -- Otherwise take CPR info from the first
942 bothRes r1 BotRes = BotRes
947 modifyEnv :: Bool -- No-op if False
948 -> (Demand -> Demand) -- The zapper
949 -> DmdEnv -> DmdEnv -- Env1 and Env2
950 -> DmdEnv -> DmdEnv -- Transform this env
951 -- Zap anything in Env1 but not in Env2
952 -- Assume: dom(env) includes dom(Env1) and dom(Env2)
954 modifyEnv need_to_modify zapper env1 env2 env
955 | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
958 zap uniq env = addToUFM_Directly env uniq (zapper current_val)
960 current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
964 %************************************************************************
966 \subsection{LUB and BOTH}
968 %************************************************************************
971 lub :: Demand -> Demand -> Demand
974 lub Abs d2 = absLub d2
976 lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
978 lub (Call d1) (Call d2) = Call (d1 `lub` d2)
979 lub d1@(Call _) (Box d2) = d1 `lub` d2 -- Just strip the box
980 lub d1@(Call _) d2@(Eval _) = d2 -- Presumably seq or vanilla eval
981 lub d1@(Call _) d2 = d2 `lub` d1 -- Bot, Abs, Top
983 -- For the Eval case, we use these approximation rules
984 -- Box Bot <= Eval (Box Bot ...)
985 -- Box Top <= Defer (Box Bot ...)
986 -- Box (Eval ds) <= Eval (map Box ds)
987 lub (Eval ds1) (Eval ds2) = Eval (ds1 `lubs` ds2)
988 lub (Eval ds1) (Box Bot) = Eval (mapDmds (`lub` Box Bot) ds1)
989 lub (Eval ds1) (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
990 lub (Eval ds1) (Box Abs) = deferEval (mapDmds (`lub` Box Bot) ds1)
991 lub d1@(Eval _) d2 = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
993 lub (Box d1) (Box d2) = box (d1 `lub` d2)
994 lub d1@(Box _) d2 = d2 `lub` d1
996 lubs ds1 ds2 = zipWithDmds lub ds1 ds2
998 ---------------------
999 -- box is the smart constructor for Box
1000 -- It computes <B,bot> & d
1001 -- INVARIANT: (Box d) => d = Bot, Abs, Eval
1002 -- Seems to be no point in allowing (Box (Call d))
1003 box (Call d) = Call d -- The odd man out. Why?
1005 box (Defer _) = lazyDmd
1006 box Top = lazyDmd -- Box Abs and Box Top
1007 box Abs = lazyDmd -- are the same <B,L>
1008 box d = Box d -- Bot, Eval
1011 defer :: Demand -> Demand
1013 -- defer is the smart constructor for Defer
1014 -- The idea is that (Defer ds) = <U(ds), L>
1016 -- It specifies what happens at a lazy function argument
1017 -- or a lambda; the L* operator
1018 -- Set the strictness part to L, but leave
1019 -- the boxity side unaffected
1020 -- It also ensures that Defer (Eval [LLLL]) = L
1025 defer (Call _) = lazyDmd -- Approximation here?
1026 defer (Box _) = lazyDmd
1027 defer (Defer ds) = Defer ds
1028 defer (Eval ds) = deferEval ds
1030 -- deferEval ds = defer (Eval ds)
1031 deferEval ds | allTop ds = Top
1032 | otherwise = Defer ds
1034 ---------------------
1035 absLub :: Demand -> Demand
1036 -- Computes (Abs `lub` d)
1037 -- For the Bot case consider
1038 -- f x y = if ... then x else error x
1039 -- Then for y we get Abs `lub` Bot, and we really
1044 absLub (Call _) = Top
1045 absLub (Box _) = Top
1046 absLub (Eval ds) = Defer (absLubs ds) -- Or (Defer ds)?
1047 absLub (Defer ds) = Defer (absLubs ds) -- Or (Defer ds)?
1049 absLubs = mapDmds absLub
1052 both :: Demand -> Demand -> Demand
1058 both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
1061 -- From 'error' itself we get demand Bot on x
1062 -- From the arg demand on x we get
1063 -- x :-> evalDmd = Box (Eval (Poly Abs))
1064 -- So we get Bot `both` Box (Eval (Poly Abs))
1065 -- = Seq Keep (Poly Bot)
1068 -- f x = if ... then error (fst x) else fst x
1069 -- Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
1071 -- which is what we want.
1074 both Top Bot = errDmd
1077 both Top (Box d) = Box d
1078 both Top (Call d) = Call d
1079 both Top (Eval ds) = Eval (mapDmds (`both` Top) ds)
1080 both Top (Defer ds) -- = defer (Top `both` Eval ds)
1081 -- = defer (Eval (mapDmds (`both` Top) ds))
1082 = deferEval (mapDmds (`both` Top) ds)
1085 both (Box d1) (Box d2) = box (d1 `both` d2)
1086 both (Box d1) d2@(Call _) = box (d1 `both` d2)
1087 both (Box d1) d2@(Eval _) = box (d1 `both` d2)
1088 both (Box d1) (Defer d2) = Box d1
1089 both d1@(Box _) d2 = d2 `both` d1
1091 both (Call d1) (Call d2) = Call (d1 `both` d2)
1092 both (Call d1) (Eval ds2) = Call d1 -- Could do better for (Poly Bot)?
1093 both (Call d1) (Defer ds2) = Call d1 -- Ditto
1094 both d1@(Call _) d2 = d1 `both` d1
1096 both (Eval ds1) (Eval ds2) = Eval (ds1 `boths` ds2)
1097 both (Eval ds1) (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
1098 both d1@(Eval ds1) d2 = d2 `both` d1
1100 both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
1101 both d1@(Defer ds1) d2 = d2 `both` d1
1103 boths ds1 ds2 = zipWithDmds both ds1 ds2
1108 %************************************************************************
1110 \subsection{Miscellaneous
1112 %************************************************************************
1116 #ifdef OLD_STRICTNESS
1117 get_changes binds = vcat (map get_changes_bind binds)
1119 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
1120 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
1122 get_changes_pr (id,rhs)
1123 = get_changes_var id $$ get_changes_expr rhs
1126 | isId var = get_changes_str var $$ get_changes_dmd var
1129 get_changes_expr (Type t) = empty
1130 get_changes_expr (Var v) = empty
1131 get_changes_expr (Lit l) = empty
1132 get_changes_expr (Note n e) = get_changes_expr e
1133 get_changes_expr (App e1 e2) = get_changes_expr e1 $$ get_changes_expr e2
1134 get_changes_expr (Lam b e) = {- get_changes_var b $$ -} get_changes_expr e
1135 get_changes_expr (Let b e) = get_changes_bind b $$ get_changes_expr e
1136 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
1138 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
1141 | new_better && old_better = empty
1142 | new_better = message "BETTER"
1143 | old_better = message "WORSE"
1144 | otherwise = message "INCOMPARABLE"
1146 message word = text word <+> text "strictness for" <+> ppr id <+> info
1147 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1148 new = squashSig (idNewStrictness id) -- Don't report spurious diffs that the old
1149 -- strictness analyser can't track
1150 old = newStrictnessFromOld (idName id) (idArity id) (idStrictness id) (idCprInfo id)
1151 old_better = old `betterStrictness` new
1152 new_better = new `betterStrictness` old
1155 | isUnLiftedType (idType id) = empty -- Not useful
1156 | new_better && old_better = empty
1157 | new_better = message "BETTER"
1158 | old_better = message "WORSE"
1159 | otherwise = message "INCOMPARABLE"
1161 message word = text word <+> text "demand for" <+> ppr id <+> info
1162 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1163 new = squashDmd (argDemand (idNewDemandInfo id)) -- To avoid spurious improvements
1165 old = newDemand (idDemandInfo id)
1166 new_better = new `betterDemand` old
1167 old_better = old `betterDemand` new
1169 betterStrictness :: StrictSig -> StrictSig -> Bool
1170 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
1172 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
1174 betterDemand :: Demand -> Demand -> Bool
1175 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
1176 betterDemand d1 d2 = (d1 `lub` d2) == d2
1178 squashSig (StrictSig (DmdType fv ds res))
1179 = StrictSig (DmdType emptyDmdEnv (map squashDmd ds) res)
1181 -- squash just gets rid of call demands
1182 -- which the old analyser doesn't track
1183 squashDmd (Call d) = evalDmd
1184 squashDmd (Box d) = Box (squashDmd d)
1185 squashDmd (Eval ds) = Eval (mapDmds squashDmd ds)
1186 squashDmd (Defer ds) = Defer (mapDmds squashDmd ds)