2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[SaAbsInt]{Abstract interpreter for strictness analysis}
9 findDemand, findDemandAlts,
16 #include "HsVersions.h"
18 import CmdLineOpts ( opt_AllStrict, opt_NumbersStrict )
20 import CoreUnfold ( Unfolding(..) )
21 import Id ( Id, idType, getIdStrictness, getIdUnfolding )
22 import Const ( Con(..) )
23 import DataCon ( dataConTyCon, dataConArgTys )
24 import IdInfo ( StrictnessInfo(..) )
25 import Demand ( Demand(..), wwPrim, wwStrict, wwEnum, wwUnpackData,
28 import TyCon ( isProductTyCon, isEnumerationTyCon, isNewTyCon )
29 import BasicTypes ( NewOrData(..) )
30 import Type ( splitAlgTyConApp_maybe,
31 isUnLiftedType, Type )
32 import TyCon ( tyConUnique )
33 import PrelInfo ( numericTyKeys )
34 import Util ( isIn, nOfThem, zipWithEqual )
37 returnsRealWorld x = False -- ToDo: panic "SaAbsInt.returnsRealWorld (ToDo)"
40 %************************************************************************
42 \subsection[AbsVal-ops]{Operations on @AbsVals@}
44 %************************************************************************
46 Least upper bound, greatest lower bound.
49 lub, glb :: AbsVal -> AbsVal -> AbsVal
51 lub val1 val2 | isBot val1 = val2 -- The isBot test includes the case where
52 lub val1 val2 | isBot val2 = val1 -- one of the val's is a function which
53 -- always returns bottom, such as \y.x,
54 -- when x is bound to bottom.
56 lub (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "lub" lub xs ys)
58 lub _ _ = AbsTop -- Crude, but conservative
59 -- The crudity only shows up if there
60 -- are functions involved
62 -- Slightly funny glb; for absence analysis only;
63 -- AbsBot is the safe answer.
65 -- Using anyBot rather than just testing for AbsBot is important.
70 -- g = \x y z -> case x of
74 -- Now, the abstract value of the branches of the case will be an
75 -- AbsFun, but when testing for z's absence we want to spot that it's
76 -- an AbsFun which can't possibly return AbsBot. So when glb'ing we
77 -- mustn't be too keen to bale out and return AbsBot; the anyBot test
78 -- spots that (f x) can't possibly return AbsBot.
80 -- We have also tripped over the following interesting case:
85 -- Now, suppose f is bound to AbsTop. Does this expression mention z?
86 -- Obviously not. But the case will take the glb of AbsTop (for f) and
87 -- an AbsFun (for \y->1). We should not bale out and give AbsBot, because
88 -- that would say that it *does* mention z (or anything else for that matter).
89 -- Nor can we always return AbsTop, because the AbsFun might be something
90 -- like (\y->z), which obviously does mention z. The point is that we're
91 -- glbing two functions, and AbsTop is not actually the top of the function
92 -- lattice. It is more like (\xyz -> x|y|z); that is, AbsTop returns
93 -- poison iff any of its arguments do.
95 -- Deal with functions specially, because AbsTop isn't the
96 -- top of their domain.
99 | is_fun v1 || is_fun v2
100 = if not (anyBot v1) && not (anyBot v2)
106 is_fun (AbsFun _ _ _) = True
107 is_fun (AbsApproxFun _ _) = True -- Not used, but the glb works ok
110 -- The non-functional cases are quite straightforward
112 glb (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "glb" glb xs ys)
117 glb _ _ = AbsBot -- Be pessimistic
120 @isBot@ returns True if its argument is (a representation of) bottom. The
121 ``representation'' part is because we need to detect the bottom {\em function}
122 too. To detect the bottom function, bind its args to top, and see if it
125 Used only in strictness analysis:
127 isBot :: AbsVal -> Bool
130 isBot other = False -- Functions aren't bottom any more
134 Used only in absence analysis:
136 anyBot :: AbsVal -> Bool
138 anyBot AbsBot = True -- poisoned!
139 anyBot AbsTop = False
140 anyBot (AbsProd vals) = any anyBot vals
141 anyBot (AbsFun bndr body env) = anyBot (absEval AbsAnal body (addOneToAbsValEnv env bndr AbsTop))
142 anyBot (AbsApproxFun _ val) = anyBot val
145 @widen@ takes an @AbsVal@, $val$, and returns and @AbsVal@ which is
146 approximated by $val$. Furthermore, the result has no @AbsFun@s in
147 it, so it can be compared for equality by @sameVal@.
150 widen :: AnalysisKind -> AbsVal -> AbsVal
152 -- Widening is complicated by the fact that funtions are lifted
153 widen StrAnal the_fn@(AbsFun bndr body env)
154 = case widened_body of
155 AbsApproxFun ds val -> AbsApproxFun (d : ds) val
157 d = findRecDemand str_fn abs_fn bndr_ty
158 str_fn val = foldl (absApply StrAnal) the_fn
159 (val : [AbsTop | d <- ds])
161 other -> AbsApproxFun [d] widened_body
163 d = findRecDemand str_fn abs_fn bndr_ty
164 str_fn val = absApply StrAnal the_fn val
166 bndr_ty = idType bndr
167 widened_body = widen StrAnal (absApply StrAnal the_fn AbsTop)
168 abs_fn val = AbsBot -- Always says poison; so it looks as if
169 -- nothing is absent; safe
172 This stuff is now instead handled neatly by the fact that AbsApproxFun
173 contains an AbsVal inside it. SLPJ Jan 97
175 | isBot abs_body = AbsBot
176 -- It's worth checking for a function which is unconditionally
179 -- f x y = let g y = case x of ...
180 -- in (g ..) + (g ..)
182 -- Here, when we are considering strictness of f in x, we'll
183 -- evaluate the body of f with x bound to bottom. The current
184 -- strategy is to bind g to its *widened* value; without the isBot
185 -- (...) test above, we'd bind g to an AbsApproxFun, and deliver
186 -- Top, not Bot as the value of f's rhs. The test spots the
187 -- unconditional bottom-ness of g when x is bottom. (Another
188 -- alternative here would be to bind g to its exact abstract
189 -- value, but that entails lots of potential re-computation, at
190 -- every application of g.)
193 widen StrAnal (AbsProd vals) = AbsProd (map (widen StrAnal) vals)
194 widen StrAnal other_val = other_val
197 widen AbsAnal the_fn@(AbsFun bndr body env)
198 | anyBot widened_body = AbsBot
199 -- In the absence-analysis case it's *essential* to check
200 -- that the function has no poison in its body. If it does,
201 -- anywhere, then the whole function is poisonous.
204 = case widened_body of
205 AbsApproxFun ds val -> AbsApproxFun (d : ds) val
207 d = findRecDemand str_fn abs_fn bndr_ty
208 abs_fn val = foldl (absApply AbsAnal) the_fn
209 (val : [AbsTop | d <- ds])
211 other -> AbsApproxFun [d] widened_body
213 d = findRecDemand str_fn abs_fn bndr_ty
214 abs_fn val = absApply AbsAnal the_fn val
216 bndr_ty = idType bndr
217 widened_body = widen AbsAnal (absApply AbsAnal the_fn AbsTop)
218 str_fn val = AbsBot -- Always says non-termination;
219 -- that'll make findRecDemand peer into the
220 -- structure of the value.
222 widen AbsAnal (AbsProd vals) = AbsProd (map (widen AbsAnal) vals)
224 -- It's desirable to do a good job of widening for product
228 -- in ...(case p of (x,y) -> x)...
230 -- Now, is y absent in this expression? Currently the
231 -- analyser widens p before looking at p's scope, to avoid
232 -- lots of recomputation in the case where p is a function.
233 -- So if widening doesn't have a case for products, we'll
234 -- widen p to AbsBot (since when searching for absence in y we
235 -- bind y to poison ie AbsBot), and now we are lost.
237 widen AbsAnal other_val = other_val
239 -- WAS: if anyBot val then AbsBot else AbsTop
240 -- Nowadays widen is doing a better job on functions for absence analysis.
243 @crudeAbsWiden@ is used just for absence analysis, and always
244 returns AbsTop or AbsBot, so it widens to a two-point domain
247 crudeAbsWiden :: AbsVal -> AbsVal
248 crudeAbsWiden val = if anyBot val then AbsBot else AbsTop
251 @sameVal@ compares two abstract values for equality. It can't deal with
252 @AbsFun@, but that should have been removed earlier in the day by @widen@.
255 sameVal :: AbsVal -> AbsVal -> Bool -- Can't handle AbsFun!
258 sameVal (AbsFun _ _ _) _ = panic "sameVal: AbsFun: arg1"
259 sameVal _ (AbsFun _ _ _) = panic "sameVal: AbsFun: arg2"
262 sameVal AbsBot AbsBot = True
263 sameVal AbsBot other = False -- widen has reduced AbsFun bots to AbsBot
265 sameVal AbsTop AbsTop = True
266 sameVal AbsTop other = False -- Right?
268 sameVal (AbsProd vals1) (AbsProd vals2) = and (zipWithEqual "sameVal" sameVal vals1 vals2)
269 sameVal (AbsProd _) AbsTop = False
270 sameVal (AbsProd _) AbsBot = False
272 sameVal (AbsApproxFun str1 v1) (AbsApproxFun str2 v2) = str1 == str2 && sameVal v1 v2
273 sameVal (AbsApproxFun _ _) AbsTop = False
274 sameVal (AbsApproxFun _ _) AbsBot = False
276 sameVal val1 val2 = panic "sameVal: type mismatch or AbsFun encountered"
280 @evalStrictness@ compares a @Demand@ with an abstract value, returning
281 @True@ iff the abstract value is {\em less defined} than the demand.
282 (@True@ is the exciting answer; @False@ is always safe.)
285 evalStrictness :: Demand
287 -> Bool -- True iff the value is sure
288 -- to be less defined than the Demand
290 evalStrictness (WwLazy _) _ = False
291 evalStrictness WwStrict val = isBot val
292 evalStrictness WwEnum val = isBot val
294 evalStrictness (WwUnpack NewType _ (demand:_)) val
295 = evalStrictness demand val
297 evalStrictness (WwUnpack DataType _ demand_info) val
301 AbsProd vals -> or (zipWithEqual "evalStrictness" evalStrictness demand_info vals)
302 _ -> pprTrace "evalStrictness?" empty False
304 evalStrictness WwPrim val
307 AbsBot -> True -- Can happen: consider f (g x), where g is a
308 -- recursive function returning an Int# that diverges
310 other -> pprPanic "evalStrictness: WwPrim:" (ppr other)
313 For absence analysis, we're interested in whether "poison" in the
314 argument (ie a bottom therein) can propagate to the result of the
315 function call; that is, whether the specified demand can {\em
316 possibly} hit poison.
319 evalAbsence (WwLazy True) _ = False -- Can't possibly hit poison
320 -- with Absent demand
322 evalAbsence (WwUnpack NewType _ (demand:_)) val
323 = evalAbsence demand val
325 evalAbsence (WwUnpack DataType _ demand_info) val
327 AbsTop -> False -- No poison in here
328 AbsBot -> True -- Pure poison
329 AbsProd vals -> or (zipWithEqual "evalAbsence" evalAbsence demand_info vals)
330 _ -> panic "evalAbsence: other"
332 evalAbsence other val = anyBot val
333 -- The demand is conservative; even "Lazy" *might* evaluate the
334 -- argument arbitrarily so we have to look everywhere for poison
337 %************************************************************************
339 \subsection[absEval]{Evaluate an expression in the abstract domain}
341 %************************************************************************
344 -- The isBottomingId stuf is now dealt with via the Id's strictness info
345 -- absId anal var env | isBottomingId var
347 -- StrAnal -> AbsBot -- See discussion below
348 -- AbsAnal -> AbsTop -- Just want to see if there's any poison in
352 = case (lookupAbsValEnv env var, getIdStrictness var, getIdUnfolding var) of
354 (Just abs_val, _, _) ->
355 abs_val -- Bound in the environment
357 (Nothing, NoStrictnessInfo, CoreUnfolding _ _ unfolding) ->
358 -- We have an unfolding for the expr
359 -- Assume the unfolding has no free variables since it
360 -- came from inside the Id
361 absEval anal unfolding env
362 -- Notice here that we only look in the unfolding if we don't
363 -- have strictness info (an unusual situation).
364 -- We could have chosen to look in the unfolding if it exists,
365 -- and only try the strictness info if it doesn't, and that would
366 -- give more accurate results, at the cost of re-abstract-interpreting
367 -- the unfolding every time.
368 -- We found only one place where the look-at-unfolding-first
369 -- method gave better results, which is in the definition of
370 -- showInt in the Prelude. In its defintion, fromIntegral is
371 -- not inlined (it's big) but ab-interp-ing its unfolding gave
372 -- a better result than looking at its strictness only.
373 -- showInt :: Integral a => a -> [Char] -> [Char]
374 -- ! {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
375 -- "U(U(U(U(SA)AAAAAAAAL)AA)AAAAASAAASA)" {...} _N_ _N_ #-}
377 -- showInt :: Integral a => a -> [Char] -> [Char]
378 -- ! {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
379 -- "U(U(U(U(SL)LLLLLLLLL)LL)LLLLLSLLLLL)" _N_ _N_ #-}
382 (Nothing, strictness_info, _) ->
383 -- Includes MagicUnfolding, NoUnfolding
384 -- Try the strictness info
385 absValFromStrictness anal strictness_info
389 absEval :: AnalysisKind -> CoreExpr -> AbsValEnv -> AbsVal
391 absEval anal (Type ty) env = AbsTop
392 absEval anal (Var var) env = absId anal var env
395 Discussion about error (following/quoting Lennart): Any expression
396 'error e' is regarded as bottom (with HBC, with the -ffail-strict
399 Regarding it as bottom gives much better strictness properties for
403 f (x:xs) y = f xs (x+y)
405 f [] _ = error "no match"
407 f (x:xs) y = f xs (x+y)
409 is strict in y, which you really want. But, it may lead to
410 transformations that turn a call to \tr{error} into non-termination.
411 (The odds of this happening aren't good.)
413 Things are a little different for absence analysis, because we want
414 to make sure that any poison (?????)
417 absEval anal (Con (Literal _) args) env
418 = -- Literals terminate (strictness) and are not poison (absence)
421 absEval anal (Con (PrimOp _) args) env
422 = -- PrimOps evaluate all their arguments
423 if any anyBot [absEval anal arg env | arg <- args]
427 absEval anal (Con (DataCon con) args) env
428 | isProductTyCon (dataConTyCon con)
429 = -- Products; filter out type arguments
430 AbsProd [absEval anal a env | a <- args, isValArg a]
432 | otherwise -- Not single-constructor
434 StrAnal -> -- Strictness case: it's easy: it certainly terminates
436 AbsAnal -> -- In the absence case we need to be more
437 -- careful: look to see if there's any
438 -- poison in the components
439 if any anyBot [absEval AbsAnal arg env | arg <- args]
445 absEval anal (Lam bndr body) env
446 | isTyVar bndr = absEval anal body env -- Type lambda
447 | otherwise = AbsFun bndr body env -- Value lambda
449 absEval anal (App expr (Type ty)) env
450 = absEval anal expr env -- Type appplication
451 absEval anal (App f val_arg) env
452 = absApply anal (absEval anal f env) -- Value applicationn
453 (absEval anal val_arg env)
457 absEval anal expr@(Case scrut case_bndr alts) env
459 scrut_val = absEval anal scrut env
460 alts_env = addOneToAbsValEnv env case_bndr scrut_val
462 case (scrut_val, alts) of
463 (AbsBot, _) -> AbsBot
465 (AbsProd arg_vals, [(con, bndrs, rhs)])
467 -- The scrutinee is a product value, so it must be of a single-constr
468 -- type; so the constructor in this alternative must be the right one
469 -- so we can go ahead and bind the constructor args to the components
470 -- of the product value.
471 ASSERT(length arg_vals == length val_bndrs)
472 absEval anal rhs rhs_env
474 val_bndrs = filter isId bndrs
475 rhs_env = growAbsValEnvList alts_env (val_bndrs `zip` arg_vals)
477 other -> absEvalAlts anal alts alts_env
480 For @Lets@ we widen the value we get. This is nothing to
481 do with fixpointing. The reason is so that we don't get an explosion
482 in the amount of computation. For example, consider:
494 If we bind @f@ and @g@ to their exact abstract value, then we'll
495 ``execute'' one call to @f@ and {\em two} calls to @g@. This can blow
496 up exponentially. Widening cuts it off by making a fixed
497 approximation to @f@ and @g@, so that the bodies of @f@ and @g@ are
498 not evaluated again at all when they are called.
500 Of course, this can lose useful joint strictness, which is sad. An
501 alternative approach would be to try with a certain amount of ``fuel''
502 and be prepared to bale out.
505 absEval anal (Let (NonRec binder e1) e2) env
507 new_env = addOneToAbsValEnv env binder (widen anal (absEval anal e1 env))
509 -- The binder of a NonRec should *not* be of unboxed type,
510 -- hence no need to strictly evaluate the Rhs.
511 absEval anal e2 new_env
513 absEval anal (Let (Rec pairs) body) env
515 (binders,rhss) = unzip pairs
516 rhs_vals = cheapFixpoint anal binders rhss env -- Returns widened values
517 new_env = growAbsValEnvList env (binders `zip` rhs_vals)
519 absEval anal body new_env
521 absEval anal (Note note expr) env = absEval anal expr env
525 absEvalAlts :: AnalysisKind -> [CoreAlt] -> AbsValEnv -> AbsVal
526 absEvalAlts anal alts env
527 = combine anal (map go alts)
529 combine StrAnal = foldr1 lub -- Diverge only if all diverge
530 combine AbsAnal = foldr1 glb -- Find any poison
533 = absEval anal rhs rhs_env
535 rhs_env = growAbsValEnvList env (filter isId bndrs `zip` repeat AbsTop)
538 %************************************************************************
540 \subsection[absApply]{Apply an abstract function to an abstract argument}
542 %************************************************************************
547 absApply :: AnalysisKind -> AbsVal -> AbsVal -> AbsVal
549 absApply anal AbsBot arg = AbsBot
550 -- AbsBot represents the abstract bottom *function* too
552 absApply StrAnal AbsTop arg = AbsTop
553 absApply AbsAnal AbsTop arg = if anyBot arg
556 -- To be conservative, we have to assume that a function about
557 -- which we know nothing (AbsTop) might look at some part of
561 An @AbsFun@ with only one more argument needed---bind it and eval the
562 result. A @Lam@ with two or more args: return another @AbsFun@ with
563 an augmented environment.
566 absApply anal (AbsFun binder body env) arg
567 = absEval anal body (addOneToAbsValEnv env binder arg)
571 absApply StrAnal (AbsApproxFun (d:ds) val) arg
574 other -> AbsApproxFun ds val' -- Result is non-bot if there are still args
576 val' | evalStrictness d arg = AbsBot
579 absApply AbsAnal (AbsApproxFun (d:ds) val) arg
580 = if evalAbsence d arg
581 then AbsBot -- Poison in arg means poison in the application
584 other -> AbsApproxFun ds val
587 absApply anal f@(AbsProd _) arg = pprPanic ("absApply: Duff function: AbsProd." ++ show anal) ((ppr f) <+> (ppr arg))
594 %************************************************************************
596 \subsection[findStrictness]{Determine some binders' strictness}
598 %************************************************************************
600 @findStrictness@ applies the function \tr{\ ids -> expr} to
601 \tr{[bot,top,top,...]}, \tr{[top,bot,top,top,...]}, etc., (i.e., once
602 with @AbsBot@ in each argument position), and evaluates the resulting
603 abstract value; it returns a vector of @Demand@s saying whether the
604 result of doing this is guaranteed to be bottom. This tells the
605 strictness of the function in each of the arguments.
607 If an argument is of unboxed type, then we declare that function to be
608 strict in that argument.
610 We don't really have to make up all those lists of mostly-@AbsTops@;
611 unbound variables in an @AbsValEnv@ are implicitly mapped to that.
613 See notes on @addStrictnessInfoToId@.
616 findStrictness :: [Type] -- Types of args in which strictness is wanted
617 -> AbsVal -- Abstract strictness value of function
618 -> AbsVal -- Abstract absence value of function
619 -> [Demand] -- Resulting strictness annotation
621 findStrictness tys str_val abs_val
622 = map find_str tys_w_index
624 tys_w_index = tys `zip` [1..]
626 find_str (ty,n) = findRecDemand str_fn abs_fn ty
628 str_fn val = foldl (absApply StrAnal) str_val
629 (map (mk_arg val n) tys_w_index)
631 abs_fn val = foldl (absApply AbsAnal) abs_val
632 (map (mk_arg val n) tys_w_index)
634 mk_arg val n (_,m) | m==n = val
640 findDemand str_env abs_env expr binder
641 = findRecDemand str_fn abs_fn (idType binder)
643 str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
644 abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
646 findDemandAlts str_env abs_env alts binder
647 = findRecDemand str_fn abs_fn (idType binder)
649 str_fn val = absEvalAlts StrAnal alts (addOneToAbsValEnv str_env binder val)
650 abs_fn val = absEvalAlts AbsAnal alts (addOneToAbsValEnv abs_env binder val)
653 @findRecDemand@ is where we finally convert strictness/absence info
654 into ``Demands'' which we can pin on Ids (etc.).
656 NOTE: What do we do if something is {\em both} strict and absent?
657 Should \tr{f x y z = error "foo"} says that \tr{f}'s arguments are all
658 strict (because of bottoming effect of \tr{error}) or all absent
659 (because they're not used)?
661 Well, for practical reasons, we prefer absence over strictness. In
662 particular, it makes the ``default defaults'' for class methods (the
663 ones that say \tr{defm.foo dict = error "I don't exist"}) come out
664 nicely [saying ``the dict isn't used''], rather than saying it is
665 strict in every component of the dictionary [massive gratuitious
666 casing to take the dict apart].
668 But you could have examples where going for strictness would be better
669 than absence. Consider:
671 let x = something big
676 If \tr{x} is marked absent in \tr{f}, but not strict, and \tr{g} is
677 lazy, then the thunk for \tr{x} will be built. If \tr{f} was strict,
678 then we'd let-to-case it:
680 case something big of
686 findRecDemand :: (AbsVal -> AbsVal) -- The strictness function
687 -> (AbsVal -> AbsVal) -- The absence function
688 -> Type -- The type of the argument
691 findRecDemand str_fn abs_fn ty
692 = if isUnLiftedType ty then -- It's a primitive type!
695 else if not (anyBot (abs_fn AbsBot)) then -- It's absent
696 -- We prefer absence over strictness: see NOTE above.
699 else if not (opt_AllStrict ||
700 (opt_NumbersStrict && is_numeric_type ty) ||
701 (isBot (str_fn AbsBot))) then
702 WwLazy False -- It's not strict and we're not pretending
704 else -- It's strict (or we're pretending it is)!
706 case (splitAlgTyConApp_maybe ty) of
710 Just (tycon,tycon_arg_tys,[data_con]) | isProductTyCon tycon ->
711 -- Non-recursive, single constructor case
713 cmpnt_tys = dataConArgTys data_con tycon_arg_tys
714 prod_len = length cmpnt_tys
717 if isNewTyCon tycon then -- A newtype!
718 ASSERT( null (tail cmpnt_tys) )
720 demand = findRecDemand str_fn abs_fn (head cmpnt_tys)
728 str_fn (mkMainlyTopProd prod_len i cmpnt_val)
731 abs_fn (mkMainlyTopProd prod_len i cmpnt_val)
734 | (cmpnt_ty, i) <- cmpnt_tys `zip` [1..] ]
736 if null compt_strict_infos then
737 if isEnumerationTyCon tycon then wwEnum else wwStrict
739 wwUnpackData compt_strict_infos
742 -- Multi-constr data types, *or* an abstract data
743 -- types, *or* things we don't have a way of conveying
744 -- the info over module boundaries (class ops,
745 -- superdict sels, dfns).
746 if isEnumerationTyCon tycon then
752 = case (splitAlgTyConApp_maybe ty) of -- NB: duplicates stuff done above
755 | tyConUnique tycon `is_elem` numericTyKeys
757 _{-something else-} -> False
759 is_elem = isIn "is_numeric_type"
761 -- mkMainlyTopProd: make an AbsProd that is all AbsTops ("n"-1 of
762 -- them) except for a given value in the "i"th position.
764 mkMainlyTopProd :: Int -> Int -> AbsVal -> AbsVal
766 mkMainlyTopProd n i val
768 befores = nOfThem (i-1) AbsTop
769 afters = nOfThem (n-i) AbsTop
771 AbsProd (befores ++ (val : afters))
774 %************************************************************************
776 \subsection[fixpoint]{Fixpointer for the strictness analyser}
778 %************************************************************************
780 The @fixpoint@ functions take a list of \tr{(binder, expr)} pairs, an
781 environment, and returns the abstract value of each binder.
783 The @cheapFixpoint@ function makes a conservative approximation,
784 by binding each of the variables to Top in their own right hand sides.
785 That allows us to make rapid progress, at the cost of a less-than-wonderful
789 cheapFixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
791 cheapFixpoint AbsAnal [id] [rhs] env
792 = [crudeAbsWiden (absEval AbsAnal rhs new_env)]
794 new_env = addOneToAbsValEnv env id AbsTop -- Unsafe starting point!
795 -- In the just-one-binding case, we guarantee to
796 -- find a fixed point in just one iteration,
797 -- because we are using only a two-point domain.
798 -- This improves matters in cases like:
800 -- f x y = letrec g = ...g...
803 -- Here, y isn't used at all, but if g is bound to
804 -- AbsBot we simply get AbsBot as the next
807 cheapFixpoint anal ids rhss env
808 = [widen anal (absEval anal rhs new_env) | rhs <- rhss]
809 -- We do just one iteration, starting from a safe
810 -- approximation. This won't do a good job in situations
812 -- \x -> letrec f = ...g...
816 -- Here, f will end up bound to Top after one iteration,
817 -- and hence we won't spot the strictness in x.
818 -- (A second iteration would solve this. ToDo: try the effect of
819 -- really searching for a fixed point.)
821 new_env = growAbsValEnvList env [(id,safe_val) | id <- ids]
824 = case anal of -- The safe starting point
830 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
831 -> (key -> key -> Bool) -- Less-than predicate
832 -> [(key,val)] -- The assoc list
834 -> Maybe val -- The corresponding value
836 mkLookupFun eq lt alist s
837 = case [a | (s',a) <- alist, s' `eq` s] of
843 fixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
845 fixpoint anal [] _ env = []
847 fixpoint anal ids rhss env
848 = fix_loop initial_vals
851 = case anal of -- The (unsafe) starting point
852 StrAnal -> if (returnsRealWorld (idType id))
853 then AbsTop -- this is a massively horrible hack (SLPJ 95/05)
857 initial_vals = [ initial_val id | id <- ids ]
859 fix_loop :: [AbsVal] -> [AbsVal]
861 fix_loop current_widened_vals
863 new_env = growAbsValEnvList env (ids `zip` current_widened_vals)
864 new_vals = [ absEval anal rhs new_env | rhs <- rhss ]
865 new_widened_vals = map (widen anal) new_vals
867 if (and (zipWith sameVal current_widened_vals new_widened_vals)) then
870 -- NB: I was too chicken to make that a zipWithEqual,
871 -- lest I jump into a black hole. WDP 96/02
873 -- Return the widened values. We might get a slightly
874 -- better value by returning new_vals (which we used to
875 -- do, see below), but alas that means that whenever the
876 -- function is called we have to re-execute it, which is
881 -- Return the un-widened values which may be a bit better
882 -- than the widened ones, and are guaranteed safe, since
883 -- they are one iteration beyond current_widened_vals,
884 -- which itself is a fixed point.
886 fix_loop new_widened_vals
889 For absence analysis, we make do with a very very simple approach:
890 look for convergence in a two-point domain.
892 We used to use just one iteration, starting with the variables bound
893 to @AbsBot@, which is safe.
895 Prior to that, we used one iteration starting from @AbsTop@ (which
896 isn't safe). Why isn't @AbsTop@ safe? Consider:
904 Here, if p is @AbsBot@, then we'd better {\em not} end up with a ``fixed
905 point'' of @d@ being @(AbsTop, AbsTop)@! An @AbsBot@ initial value is
906 safe because it gives poison more often than really necessary, and
907 thus may miss some absence, but will never claim absence when it ain't
910 Anyway, one iteration starting with everything bound to @AbsBot@ give
915 Here, f would always end up bound to @AbsBot@, which ain't very
916 clever, because then it would introduce poison whenever it was
917 applied. Much better to start with f bound to @AbsTop@, and widen it
918 to @AbsBot@ if any poison shows up. In effect we look for convergence
919 in the two-point @AbsTop@/@AbsBot@ domain.
921 What we miss (compared with the cleverer strictness analysis) is
922 spotting that in this case
924 f = \ x y -> ...y...(f x y')...
926 \tr{x} is actually absent, since it is only passed round the loop, never
927 used. But who cares about missing that?
929 NB: despite only having a two-point domain, we may still have many
930 iterations, because there are several variables involved at once.