2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
4 \section[SaAbsInt]{Abstract interpreter for strictness analysis}
7 #include "HsVersions.h"
21 import CoreUnfold ( UnfoldingDetails(..), FormSummary )
22 import CoreUtils ( unTagBinders )
23 import Id ( idType, getIdStrictness, getIdUnfolding,
26 import IdInfo ( StrictnessInfo(..), Demand(..),
27 wwPrim, wwStrict, wwEnum, wwUnpack
29 import MagicUFs ( MagicUnfoldingFun )
30 import Maybes ( maybeToBool )
31 import Outputable ( Outputable(..){-instance * []-} )
32 import PprStyle ( PprStyle(..) )
33 import PrelInfo ( intTyCon, integerTyCon, doubleTyCon,
34 floatTyCon, wordTyCon, addrTyCon
36 import Pretty ( ppStr )
37 import PrimOp ( PrimOp(..) )
39 import TyCon ( maybeTyConSingleCon, isEnumerationTyCon,
42 import Type ( maybeAppDataTyCon, isPrimType )
43 import Util ( isIn, isn'tIn, nOfThem, zipWithEqual,
44 pprTrace, panic, pprPanic, assertPanic
47 getInstantiatedDataConSig = panic "SaAbsInt.getInstantiatedDataConSig (ToDo)"
48 returnsRealWorld = panic "SaAbsInt.returnsRealWorld (ToDo)"
51 %************************************************************************
53 \subsection[AbsVal-ops]{Operations on @AbsVals@}
55 %************************************************************************
57 Least upper bound, greatest lower bound.
60 lub, glb :: AbsVal -> AbsVal -> AbsVal
62 lub val1 val2 | isBot val1 = val2 -- The isBot test includes the case where
63 lub val1 val2 | isBot val2 = val1 -- one of the val's is a function which
64 -- always returns bottom, such as \y.x,
65 -- when x is bound to bottom.
67 lub (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual lub xs ys)
69 lub _ _ = AbsTop -- Crude, but conservative
70 -- The crudity only shows up if there
71 -- are functions involved
73 -- Slightly funny glb; for absence analysis only;
74 -- AbsBot is the safe answer.
76 -- Using anyBot rather than just testing for AbsBot is important.
81 -- g = \x y z -> case x of
85 -- Now, the abstract value of the branches of the case will be an
86 -- AbsFun, but when testing for z's absence we want to spot that it's
87 -- an AbsFun which can't possibly return AbsBot. So when glb'ing we
88 -- mustn't be too keen to bale out and return AbsBot; the anyBot test
89 -- spots that (f x) can't possibly return AbsBot.
91 -- We have also tripped over the following interesting case:
96 -- Now, suppose f is bound to AbsTop. Does this expression mention z?
97 -- Obviously not. But the case will take the glb of AbsTop (for f) and
98 -- an AbsFun (for \y->1). We should not bale out and give AbsBot, because
99 -- that would say that it *does* mention z (or anything else for that matter).
100 -- Nor can we always return AbsTop, because the AbsFun might be something
101 -- like (\y->z), which obviously does mention z. The point is that we're
102 -- glbing two functions, and AbsTop is not actually the top of the function
103 -- lattice. It is more like (\xyz -> x|y|z); that is, AbsTop returns
104 -- poison iff any of its arguments do.
106 -- Deal with functions specially, because AbsTop isn't the
107 -- top of their domain.
110 | is_fun v1 || is_fun v2
111 = if not (anyBot v1) && not (anyBot v2)
117 is_fun (AbsFun _ _ _) = True
118 is_fun (AbsApproxFun _) = True -- Not used, but the glb works ok
121 -- The non-functional cases are quite straightforward
123 glb (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual glb xs ys)
128 glb _ _ = AbsBot -- Be pessimistic
134 -> AbsVal -- Value of scrutinee
135 -> [AbsVal] -- Value of branches (at least one)
138 -- For strictness analysis, see if the scrutinee is bottom; if so
139 -- return bottom; otherwise, the lub of the branches.
141 combineCaseValues StrAnal AbsBot branches = AbsBot
142 combineCaseValues StrAnal other_scrutinee branches
143 -- Scrutinee can only be AbsBot, AbsProd or AbsTop
144 = ASSERT(ok_scrutinee)
148 = case other_scrutinee of {
149 AbsTop -> True; -- i.e., cool
150 AbsProd _ -> True; -- ditto
151 _ -> False -- party over
154 -- For absence analysis, check if the scrutinee is all poison (isBot)
155 -- If so, return poison (AbsBot); otherwise, any nested poison will come
156 -- out from looking at the branches, so just glb together the branches
157 -- to get the worst one.
159 combineCaseValues AbsAnal AbsBot branches = AbsBot
160 combineCaseValues AbsAnal other_scrutinee branches
161 -- Scrutinee can only be AbsBot, AbsProd or AbsTop
162 = ASSERT(ok_scrutinee)
164 result = foldr1 glb branches
166 tracer = if at_least_one_AbsFun && at_least_one_AbsTop
168 pprTrace "combineCase:" (ppr PprDebug branches)
177 = case other_scrutinee of {
178 AbsTop -> True; -- i.e., cool
179 AbsProd _ -> True; -- ditto
180 _ -> False -- party over
183 at_least_one_AbsFun = foldr ((||) . is_AbsFun) False branches
184 at_least_one_AbsTop = foldr ((||) . is_AbsTop) False branches
185 no_AbsBots = foldr ((&&) . is_not_AbsBot) True branches
187 is_AbsFun x = case x of { AbsFun _ _ _ -> True; _ -> False }
188 is_AbsTop x = case x of { AbsTop -> True; _ -> False }
189 is_not_AbsBot x = case x of { AbsBot -> False; _ -> True }
192 @isBot@ returns True if its argument is (a representation of) bottom. The
193 ``representation'' part is because we need to detect the bottom {\em function}
194 too. To detect the bottom function, bind its args to top, and see if it
197 Used only in strictness analysis:
199 isBot :: AbsVal -> Bool
202 isBot (AbsFun args body env) = isBot (absEval StrAnal body env)
203 -- Don't bother to extend the envt because
204 -- unbound variables default to AbsTop anyway
208 Used only in absence analysis:
210 anyBot :: AbsVal -> Bool
212 anyBot AbsBot = True -- poisoned!
213 anyBot AbsTop = False
214 anyBot (AbsProd vals) = any anyBot vals
215 anyBot (AbsFun args body env) = anyBot (absEval AbsAnal body env)
216 anyBot (AbsApproxFun demands) = False
218 -- AbsApproxFun can only arise in absence analysis from the Demand
219 -- info of an imported value; whatever it is we're looking for is
220 -- certainly not present over in the imported value.
223 @widen@ takes an @AbsVal@, $val$, and returns and @AbsVal@ which is
224 approximated by $val$. Furthermore, the result has no @AbsFun@s in
225 it, so it can be compared for equality by @sameVal@.
228 widen :: AnalysisKind -> AbsVal -> AbsVal
230 widen StrAnal (AbsFun args body env)
231 | isBot (absEval StrAnal body env) = AbsBot
233 = ASSERT (not (null args))
234 AbsApproxFun (map (findDemandStrOnly env body) args)
236 -- It's worth checking for a function which is unconditionally
239 -- f x y = let g y = case x of ...
240 -- in (g ..) + (g ..)
242 -- Here, when we are considering strictness of f in x, we'll
243 -- evaluate the body of f with x bound to bottom. The current
244 -- strategy is to bind g to its *widened* value; without the isBot
245 -- (...) test above, we'd bind g to an AbsApproxFun, and deliver
246 -- Top, not Bot as the value of f's rhs. The test spots the
247 -- unconditional bottom-ness of g when x is bottom. (Another
248 -- alternative here would be to bind g to its exact abstract
249 -- value, but that entails lots of potential re-computation, at
250 -- every application of g.)
252 widen StrAnal (AbsProd vals) = AbsProd (map (widen StrAnal) vals)
253 widen StrAnal other_val = other_val
256 widen AbsAnal (AbsFun args body env)
257 | anyBot (absEval AbsAnal body env) = AbsBot
258 -- In the absence-analysis case it's *essential* to check
259 -- that the function has no poison in its body. If it does,
260 -- anywhere, then the whole function is poisonous.
263 = ASSERT (not (null args))
264 AbsApproxFun (map (findDemandAbsOnly env body) args)
266 widen AbsAnal (AbsProd vals) = AbsProd (map (widen AbsAnal) vals)
268 -- It's desirable to do a good job of widening for product
272 -- in ...(case p of (x,y) -> x)...
274 -- Now, is y absent in this expression? Currently the
275 -- analyser widens p before looking at p's scope, to avoid
276 -- lots of recomputation in the case where p is a function.
277 -- So if widening doesn't have a case for products, we'll
278 -- widen p to AbsBot (since when searching for absence in y we
279 -- bind y to poison ie AbsBot), and now we are lost.
281 widen AbsAnal other_val = other_val
283 -- WAS: if anyBot val then AbsBot else AbsTop
284 -- Nowadays widen is doing a better job on functions for absence analysis.
287 @crudeAbsWiden@ is used just for absence analysis, and always
288 returns AbsTop or AbsBot, so it widens to a two-point domain
291 crudeAbsWiden :: AbsVal -> AbsVal
292 crudeAbsWiden val = if anyBot val then AbsBot else AbsTop
295 @sameVal@ compares two abstract values for equality. It can't deal with
296 @AbsFun@, but that should have been removed earlier in the day by @widen@.
299 sameVal :: AbsVal -> AbsVal -> Bool -- Can't handle AbsFun!
302 sameVal (AbsFun _ _ _) _ = panic "sameVal: AbsFun: arg1"
303 sameVal _ (AbsFun _ _ _) = panic "sameVal: AbsFun: arg2"
306 sameVal AbsBot AbsBot = True
307 sameVal AbsBot other = False -- widen has reduced AbsFun bots to AbsBot
309 sameVal AbsTop AbsTop = True
310 sameVal AbsTop other = False -- Right?
312 sameVal (AbsProd vals1) (AbsProd vals2) = and (zipWithEqual sameVal vals1 vals2)
313 sameVal (AbsProd _) AbsTop = False
314 sameVal (AbsProd _) AbsBot = False
316 sameVal (AbsApproxFun str1) (AbsApproxFun str2) = str1 == str2
317 sameVal (AbsApproxFun _) AbsTop = False
318 sameVal (AbsApproxFun _) AbsBot = False
320 sameVal val1 val2 = panic "sameVal: type mismatch or AbsFun encountered"
324 @evalStrictness@ compares a @Demand@ with an abstract value, returning
325 @True@ iff the abstract value is {\em less defined} than the demand.
326 (@True@ is the exciting answer; @False@ is always safe.)
329 evalStrictness :: Demand
331 -> Bool -- True iff the value is sure
332 -- to be less defined than the Demand
334 evalStrictness (WwLazy _) _ = False
335 evalStrictness WwStrict val = isBot val
336 evalStrictness WwEnum val = isBot val
338 evalStrictness (WwUnpack demand_info) val
342 AbsProd vals -> or (zipWithEqual evalStrictness demand_info vals)
343 _ -> trace "evalStrictness?" False
345 evalStrictness WwPrim val
349 other -> -- A primitive value should be defined, never bottom;
350 -- hence this paranoia check
351 pprPanic "evalStrictness: WwPrim:" (ppr PprDebug other)
354 For absence analysis, we're interested in whether "poison" in the
355 argument (ie a bottom therein) can propagate to the result of the
356 function call; that is, whether the specified demand can {\em
357 possibly} hit poison.
360 evalAbsence (WwLazy True) _ = False -- Can't possibly hit poison
361 -- with Absent demand
363 evalAbsence (WwUnpack demand_info) val
365 AbsTop -> False -- No poison in here
366 AbsBot -> True -- Pure poison
367 AbsProd vals -> or (zipWithEqual evalAbsence demand_info vals)
368 _ -> panic "evalAbsence: other"
370 evalAbsence other val = anyBot val
371 -- The demand is conservative; even "Lazy" *might* evaluate the
372 -- argument arbitrarily so we have to look everywhere for poison
375 %************************************************************************
377 \subsection[absEval]{Evaluate an expression in the abstract domain}
379 %************************************************************************
382 -- The isBottomingId stuf is now dealt with via the Id's strictness info
383 -- absId anal var env | isBottomingId var
385 -- StrAnal -> AbsBot -- See discussion below
386 -- AbsAnal -> AbsTop -- Just want to see if there's any poison in
392 case (lookupAbsValEnv env var, getIdStrictness var, getIdUnfolding var) of
394 (Just abs_val, _, _) ->
395 abs_val -- Bound in the environment
397 (Nothing, NoStrictnessInfo, LitForm _) ->
398 AbsTop -- Literals all terminate, and have no poison
400 (Nothing, NoStrictnessInfo, ConForm _ _) ->
401 AbsTop -- An imported constructor won't have
402 -- bottom components, nor poison!
404 (Nothing, NoStrictnessInfo, GenForm _ _ unfolding _) ->
405 -- We have an unfolding for the expr
406 -- Assume the unfolding has no free variables since it
407 -- came from inside the Id
408 absEval anal (unTagBinders unfolding) env
409 -- Notice here that we only look in the unfolding if we don't
410 -- have strictness info (an unusual situation).
411 -- We could have chosen to look in the unfolding if it exists,
412 -- and only try the strictness info if it doesn't, and that would
413 -- give more accurate results, at the cost of re-abstract-interpreting
414 -- the unfolding every time.
415 -- We found only one place where the look-at-unfolding-first
416 -- method gave better results, which is in the definition of
417 -- showInt in the Prelude. In its defintion, fromIntegral is
418 -- not inlined (it's big) but ab-interp-ing its unfolding gave
419 -- a better result than looking at its strictness only.
420 -- showInt :: Integral a => a -> [Char] -> [Char]
421 -- ! {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
422 -- "U(U(U(U(SA)AAAAAAAAL)AA)AAAAASAAASA)" {...} _N_ _N_ #-}
424 -- showInt :: Integral a => a -> [Char] -> [Char]
425 -- ! {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
426 -- "U(U(U(U(SL)LLLLLLLLL)LL)LLLLLSLLLLL)" _N_ _N_ #-}
429 (Nothing, strictness_info, _) ->
430 -- Includes MagicForm, IWantToBeINLINEd, NoUnfoldingDetails
431 -- Try the strictness info
432 absValFromStrictness anal strictness_info
435 -- Done via strictness now
436 -- GenForm _ BottomForm _ _ -> AbsBot
438 -- pprTrace "absId:" (ppBesides [ppr PprDebug var, ppStr "=:", pp_anal anal, ppStr ":=",ppr PprDebug result]) (
442 pp_anal StrAnal = ppStr "STR"
443 pp_anal AbsAnal = ppStr "ABS"
445 absEvalAtom anal (VarArg v) env = absId anal v env
446 absEvalAtom anal (LitArg _) env = AbsTop
450 absEval :: AnalysisKind -> CoreExpr -> AbsValEnv -> AbsVal
452 absEval anal (Var var) env = absId anal var env
454 absEval anal (Lit _) env = AbsTop
455 -- What if an unboxed literal? That's OK: it terminates, so its
456 -- abstract value is AbsTop.
458 -- For absence analysis, a literal certainly isn't the "poison" variable
461 Discussion about \tr{error} (following/quoting Lennart): Any expression
462 \tr{error e} is regarded as bottom (with HBC, with the
463 \tr{-ffail-strict} flag, on with \tr{-O}).
465 Regarding it as bottom gives much better strictness properties for
469 f (x:xs) y = f xs (x+y)
471 f [] _ = error "no match"
473 f (x:xs) y = f xs (x+y)
475 is strict in \tr{y}, which you really want. But, it may lead to
476 transformations that turn a call to \tr{error} into non-termination.
477 (The odds of this happening aren't good.)
480 Things are a little different for absence analysis, because we want
481 to make sure that any poison (?????)
484 absEval StrAnal (Prim SeqOp [TyArg _, e]) env
486 if isBot (absEvalAtom StrAnal e env) then AbsBot else AbsTop
487 -- This is a special case to ensure that seq# is strict in its argument.
488 -- The comments below (for most normal PrimOps) do not apply.
490 absEval StrAnal (Prim op es) env = AbsTop
491 -- The arguments are all of unboxed type, so they will already
492 -- have been eval'd. If the boxed version was bottom, we'll
493 -- already have returned bottom.
495 -- Actually, I believe we are saying that either (1) the
496 -- primOp uses unboxed args and they've been eval'ed, so
497 -- there's no need to force strictness here, _or_ the primOp
498 -- uses boxed args and we don't know whether or not it's
499 -- strict, so we assume laziness. (JSM)
501 absEval AbsAnal (Prim op as) env
502 = if any anyBot [absEvalAtom AbsAnal a env | a <- as, isValArg a]
505 -- For absence analysis, we want to see if the poison shows up...
507 absEval anal (Con con as) env
509 = AbsProd [absEvalAtom anal a env | a <- as, isValArg a]
511 | otherwise -- Not single-constructor
513 StrAnal -> -- Strictness case: it's easy: it certainly terminates
515 AbsAnal -> -- In the absence case we need to be more
516 -- careful: look to see if there's any
517 -- poison in the components
518 if any anyBot [absEvalAtom AbsAnal a env | a <- as, isValArg a]
522 (_,_,_, tycon) = dataConSig con
523 has_single_con = maybeToBool (maybeTyConSingleCon tycon)
527 absEval anal (Lam (ValBinder binder) body) env
528 = AbsFun [binder] body env
529 absEval anal (Lam other_binder expr) env
530 = absEval anal expr env
531 absEval anal (App f a) env | isValArg a
532 = absApply anal (absEval anal f env) (absEvalAtom anal a env)
533 absEval anal (App expr _) env
534 = absEval anal expr env
537 For primitive cases, just GLB the branches, then LUB with the expr part.
540 absEval anal (Case expr (PrimAlts alts deflt)) env
542 expr_val = absEval anal expr env
543 abs_alts = [ absEval anal rhs env | (_, rhs) <- alts ]
544 -- Don't bother to extend envt, because unbound vars
545 -- default to the conservative AbsTop
547 abs_deflt = absEvalDefault anal expr_val deflt env
549 combineCaseValues anal expr_val
550 (abs_deflt ++ abs_alts)
552 absEval anal (Case expr (AlgAlts alts deflt)) env
554 expr_val = absEval anal expr env
555 abs_alts = [ absEvalAlgAlt anal expr_val alt env | alt <- alts ]
556 abs_deflt = absEvalDefault anal expr_val deflt env
560 combineCaseValues anal expr_val
561 (abs_deflt ++ abs_alts)
566 _ -> pprTrace "absCase:ABS:" (ppAbove (ppCat [ppr PprDebug expr, ppr PprDebug result, ppr PprDebug expr_val, ppr PprDebug abs_deflt, ppr PprDebug abs_alts]) (ppr PprDebug (keysFM env `zip` eltsFM env)))
572 For @Lets@ we widen the value we get. This is nothing to
573 do with fixpointing. The reason is so that we don't get an explosion
574 in the amount of computation. For example, consider:
586 If we bind @f@ and @g@ to their exact abstract value, then we'll
587 ``execute'' one call to @f@ and {\em two} calls to @g@. This can blow
588 up exponentially. Widening cuts it off by making a fixed
589 approximation to @f@ and @g@, so that the bodies of @f@ and @g@ are
590 not evaluated again at all when they are called.
592 Of course, this can lose useful joint strictness, which is sad. An
593 alternative approach would be to try with a certain amount of ``fuel''
594 and be prepared to bale out.
597 absEval anal (Let (NonRec binder e1) e2) env
599 new_env = addOneToAbsValEnv env binder (widen anal (absEval anal e1 env))
601 -- The binder of a NonRec should *not* be of unboxed type,
602 -- hence no need to strictly evaluate the Rhs.
603 absEval anal e2 new_env
605 absEval anal (Let (Rec pairs) body) env
607 (binders,rhss) = unzip pairs
608 rhs_vals = cheapFixpoint anal binders rhss env -- Returns widened values
609 new_env = growAbsValEnvList env (binders `zip` rhs_vals)
611 absEval anal body new_env
613 absEval anal (SCC cc expr) env = absEval anal expr env
617 absEvalAlgAlt :: AnalysisKind -> AbsVal -> (Id,[Id],CoreExpr) -> AbsValEnv -> AbsVal
619 absEvalAlgAlt anal (AbsProd arg_vals) (con, args, rhs) env
620 = -- The scrutinee is a product value, so it must be of a single-constr
621 -- type; so the constructor in this alternative must be the right one
622 -- so we can go ahead and bind the constructor args to the components
623 -- of the product value.
624 ASSERT(length arg_vals == length args)
626 new_env = growAbsValEnvList env (args `zip` arg_vals)
628 absEval anal rhs new_env
630 absEvalAlgAlt anal other_scrutinee (con, args, rhs) env
631 = -- Scrutinised value is Top or Bot (it can't be a function!)
632 -- So just evaluate the rhs with all constr args bound to Top.
633 -- (If the scrutinee is Top we'll never evaluated this function
639 = case other_scrutinee of {
640 AbsTop -> True; -- i.e., OK
641 AbsBot -> True; -- ditto
642 _ -> False -- party over
646 absEvalDefault :: AnalysisKind
647 -> AbsVal -- Value of scrutinee
650 -> [AbsVal] -- Empty or singleton
652 absEvalDefault anal scrut_val NoDefault env = []
653 absEvalDefault anal scrut_val (BindDefault binder expr) env
654 = [absEval anal expr (addOneToAbsValEnv env binder scrut_val)]
657 %************************************************************************
659 \subsection[absApply]{Apply an abstract function to an abstract argument}
661 %************************************************************************
666 absApply :: AnalysisKind -> AbsVal -> AbsVal -> AbsVal
668 absApply anal AbsBot arg = AbsBot
669 -- AbsBot represents the abstract bottom *function* too
671 absApply StrAnal AbsTop arg = AbsTop
672 absApply AbsAnal AbsTop arg = if anyBot arg
675 -- To be conservative, we have to assume that a function about
676 -- which we know nothing (AbsTop) might look at some part of
680 An @AbsFun@ with only one more argument needed---bind it and eval the
681 result. A @Lam@ with two or more args: return another @AbsFun@ with
682 an augmented environment.
685 absApply anal (AbsFun [binder] body env) arg
686 = absEval anal body (addOneToAbsValEnv env binder arg)
688 absApply anal (AbsFun (binder:bs) body env) arg
689 = AbsFun bs body (addOneToAbsValEnv env binder arg)
693 absApply StrAnal (AbsApproxFun (arg1_demand:ds)) arg
694 = if evalStrictness arg1_demand arg
698 other -> AbsApproxFun ds
700 absApply AbsAnal (AbsApproxFun (arg1_demand:ds)) arg
701 = if evalAbsence arg1_demand arg
705 other -> AbsApproxFun ds
708 absApply anal (AbsApproxFun []) arg = panic ("absApply: Duff function: AbsApproxFun." ++ show anal)
709 absApply anal (AbsFun [] _ _) arg = panic ("absApply: Duff function: AbsFun." ++ show anal)
710 absApply anal (AbsProd _) arg = panic ("absApply: Duff function: AbsProd." ++ show anal)
717 %************************************************************************
719 \subsection[findStrictness]{Determine some binders' strictness}
721 %************************************************************************
723 @findStrictness@ applies the function \tr{\ ids -> expr} to
724 \tr{[bot,top,top,...]}, \tr{[top,bot,top,top,...]}, etc., (i.e., once
725 with @AbsBot@ in each argument position), and evaluates the resulting
726 abstract value; it returns a vector of @Demand@s saying whether the
727 result of doing this is guaranteed to be bottom. This tells the
728 strictness of the function in each of the arguments.
730 If an argument is of unboxed type, then we declare that function to be
731 strict in that argument.
733 We don't really have to make up all those lists of mostly-@AbsTops@;
734 unbound variables in an @AbsValEnv@ are implicitly mapped to that.
736 See notes on @addStrictnessInfoToId@.
739 findStrictness :: StrAnalFlags
740 -> [Type] -- Types of args in which strictness is wanted
741 -> AbsVal -- Abstract strictness value of function
742 -> AbsVal -- Abstract absence value of function
743 -> [Demand] -- Resulting strictness annotation
745 findStrictness strflags [] str_val abs_val = []
747 findStrictness strflags (ty:tys) str_val abs_val
749 demand = findRecDemand strflags [] str_fn abs_fn ty
750 str_fn val = absApply StrAnal str_val val
751 abs_fn val = absApply AbsAnal abs_val val
753 demands = findStrictness strflags tys
754 (absApply StrAnal str_val AbsTop)
755 (absApply AbsAnal abs_val AbsTop)
762 findDemandStrOnly str_env expr binder -- Only strictness environment available
763 = findRecDemand strflags [] str_fn abs_fn (idType binder)
765 str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
766 abs_fn val = AbsBot -- Always says poison; so it looks as if
767 -- nothing is absent; safe
768 strflags = getStrAnalFlags str_env
770 findDemandAbsOnly abs_env expr binder -- Only absence environment available
771 = findRecDemand strflags [] str_fn abs_fn (idType binder)
773 str_fn val = AbsBot -- Always says non-termination;
774 -- that'll make findRecDemand peer into the
775 -- structure of the value.
776 abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
777 strflags = getStrAnalFlags abs_env
780 findDemand str_env abs_env expr binder
781 = findRecDemand strflags [] str_fn abs_fn (idType binder)
783 str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
784 abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
785 strflags = getStrAnalFlags str_env
788 @findRecDemand@ is where we finally convert strictness/absence info
789 into ``Demands'' which we can pin on Ids (etc.).
791 NOTE: What do we do if something is {\em both} strict and absent?
792 Should \tr{f x y z = error "foo"} says that \tr{f}'s arguments are all
793 strict (because of bottoming effect of \tr{error}) or all absent
794 (because they're not used)?
796 Well, for practical reasons, we prefer absence over strictness. In
797 particular, it makes the ``default defaults'' for class methods (the
798 ones that say \tr{defm.foo dict = error "I don't exist"}) come out
799 nicely [saying ``the dict isn't used''], rather than saying it is
800 strict in every component of the dictionary [massive gratuitious
801 casing to take the dict apart].
803 But you could have examples where going for strictness would be better
804 than absence. Consider:
806 let x = something big
811 If \tr{x} is marked absent in \tr{f}, but not strict, and \tr{g} is
812 lazy, then the thunk for \tr{x} will be built. If \tr{f} was strict,
813 then we'd let-to-case it:
815 case something big of
821 findRecDemand :: StrAnalFlags
822 -> [TyCon] -- TyCons already seen; used to avoid
823 -- zooming into recursive types
824 -> (AbsVal -> AbsVal) -- The strictness function
825 -> (AbsVal -> AbsVal) -- The absence function
826 -> Type -- The type of the argument
829 findRecDemand strflags seen str_fn abs_fn ty
830 = if isPrimType ty then -- It's a primitive type!
833 else if not (anyBot (abs_fn AbsBot)) then -- It's absent
834 -- We prefer absence over strictness: see NOTE above.
837 else if not (all_strict ||
838 (num_strict && is_numeric_type ty) ||
839 (isBot (str_fn AbsBot))) then
840 WwLazy False -- It's not strict and we're not pretending
842 else -- It's strict (or we're pretending it is)!
844 case maybeAppDataTyCon ty of
848 Just (tycon,tycon_arg_tys,[data_con]) | tycon `not_elem` seen ->
849 -- Single constructor case, tycon not already seen higher up
851 (_,cmpnt_tys,_) = getInstantiatedDataConSig data_con tycon_arg_tys
852 prod_len = length cmpnt_tys
855 = [ findRecDemand strflags (tycon:seen)
857 str_fn (mkMainlyTopProd prod_len i cmpnt_val)
860 abs_fn (mkMainlyTopProd prod_len i cmpnt_val)
863 | (cmpnt_ty, i) <- cmpnt_tys `zip` [1..] ]
865 if null compt_strict_infos then
866 if isEnumerationTyCon tycon then wwEnum else wwStrict
868 wwUnpack compt_strict_infos
870 not_elem = isn'tIn "findRecDemand"
873 -- Multi-constr data types, *or* an abstract data
874 -- types, *or* things we don't have a way of conveying
875 -- the info over module boundaries (class ops,
876 -- superdict sels, dfns).
877 if isEnumerationTyCon tycon then
882 (all_strict, num_strict) = strflags
885 = case (maybeAppDataTyCon ty) of -- NB: duplicates stuff done above
889 [intTyCon, integerTyCon,
890 doubleTyCon, floatTyCon,
891 wordTyCon, addrTyCon]
893 _{-something else-} -> False
895 is_elem = isIn "is_numeric_type"
897 -- mkMainlyTopProd: make an AbsProd that is all AbsTops ("n"-1 of
898 -- them) except for a given value in the "i"th position.
900 mkMainlyTopProd :: Int -> Int -> AbsVal -> AbsVal
902 mkMainlyTopProd n i val
904 befores = nOfThem (i-1) AbsTop
905 afters = nOfThem (n-i) AbsTop
907 AbsProd (befores ++ (val : afters))
910 %************************************************************************
912 \subsection[fixpoint]{Fixpointer for the strictness analyser}
914 %************************************************************************
916 The @fixpoint@ functions take a list of \tr{(binder, expr)} pairs, an
917 environment, and returns the abstract value of each binder.
919 The @cheapFixpoint@ function makes a conservative approximation,
920 by binding each of the variables to Top in their own right hand sides.
921 That allows us to make rapid progress, at the cost of a less-than-wonderful
925 cheapFixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
927 cheapFixpoint AbsAnal [id] [rhs] env
928 = [crudeAbsWiden (absEval AbsAnal rhs new_env)]
930 new_env = addOneToAbsValEnv env id AbsTop -- Unsafe starting point!
931 -- In the just-one-binding case, we guarantee to
932 -- find a fixed point in just one iteration,
933 -- because we are using only a two-point domain.
934 -- This improves matters in cases like:
936 -- f x y = letrec g = ...g...
939 -- Here, y isn't used at all, but if g is bound to
940 -- AbsBot we simply get AbsBot as the next
943 cheapFixpoint anal ids rhss env
944 = [widen anal (absEval anal rhs new_env) | rhs <- rhss]
945 -- We do just one iteration, starting from a safe
946 -- approximation. This won't do a good job in situations
948 -- \x -> letrec f = ...g...
952 -- Here, f will end up bound to Top after one iteration,
953 -- and hence we won't spot the strictness in x.
954 -- (A second iteration would solve this. ToDo: try the effect of
955 -- really searching for a fixed point.)
957 new_env = growAbsValEnvList env [(id,safe_val) | id <- ids]
960 = case anal of -- The safe starting point
966 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
967 -> (key -> key -> Bool) -- Less-than predicate
968 -> [(key,val)] -- The assoc list
970 -> Maybe val -- The corresponding value
972 mkLookupFun eq lt alist s
973 = case [a | (s',a) <- alist, s' `eq` s] of
979 fixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
981 fixpoint anal [] _ env = []
983 fixpoint anal ids rhss env
984 = fix_loop initial_vals
987 = case anal of -- The (unsafe) starting point
988 StrAnal -> if (returnsRealWorld (idType id))
989 then AbsTop -- this is a massively horrible hack (SLPJ 95/05)
993 initial_vals = [ initial_val id | id <- ids ]
995 fix_loop :: [AbsVal] -> [AbsVal]
997 fix_loop current_widened_vals
999 new_env = growAbsValEnvList env (ids `zip` current_widened_vals)
1000 new_vals = [ absEval anal rhs new_env | rhs <- rhss ]
1001 new_widened_vals = map (widen anal) new_vals
1003 if (and (zipWith sameVal current_widened_vals new_widened_vals)) then
1004 current_widened_vals
1006 -- NB: I was too chicken to make that a zipWithEqual,
1007 -- lest I jump into a black hole. WDP 96/02
1009 -- Return the widened values. We might get a slightly
1010 -- better value by returning new_vals (which we used to
1011 -- do, see below), but alas that means that whenever the
1012 -- function is called we have to re-execute it, which is
1017 -- Return the un-widened values which may be a bit better
1018 -- than the widened ones, and are guaranteed safe, since
1019 -- they are one iteration beyond current_widened_vals,
1020 -- which itself is a fixed point.
1022 fix_loop new_widened_vals
1025 For absence analysis, we make do with a very very simple approach:
1026 look for convergence in a two-point domain.
1028 We used to use just one iteration, starting with the variables bound
1029 to @AbsBot@, which is safe.
1031 Prior to that, we used one iteration starting from @AbsTop@ (which
1032 isn't safe). Why isn't @AbsTop@ safe? Consider:
1040 Here, if p is @AbsBot@, then we'd better {\em not} end up with a ``fixed
1041 point'' of @d@ being @(AbsTop, AbsTop)@! An @AbsBot@ initial value is
1042 safe because it gives poison more often than really necessary, and
1043 thus may miss some absence, but will never claim absence when it ain't
1046 Anyway, one iteration starting with everything bound to @AbsBot@ give
1051 Here, f would always end up bound to @AbsBot@, which ain't very
1052 clever, because then it would introduce poison whenever it was
1053 applied. Much better to start with f bound to @AbsTop@, and widen it
1054 to @AbsBot@ if any poison shows up. In effect we look for convergence
1055 in the two-point @AbsTop@/@AbsBot@ domain.
1057 What we miss (compared with the cleverer strictness analysis) is
1058 spotting that in this case
1060 f = \ x y -> ...y...(f x y')...
1062 \tr{x} is actually absent, since it is only passed round the loop, never
1063 used. But who cares about missing that?
1065 NB: despite only having a two-point domain, we may still have many
1066 iterations, because there are several variables involved at once.