11c621fb3342ac10c11b3063954c547252c82ccb
[ghc-hetmet.git] / ghc / compiler / stranal / SaAbsInt.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[SaAbsInt]{Abstract interpreter for strictness analysis}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module SaAbsInt (
10         findStrictness,
11         findDemand,
12         absEval,
13         widen,
14         fixpoint,
15         isBot
16     ) where
17
18 import Ubiq{-uitous-}
19
20 import CoreSyn
21 import CoreUnfold       ( UnfoldingDetails(..), FormSummary )
22 import CoreUtils        ( unTagBinders )
23 import Id               ( idType, getIdStrictness, getIdUnfolding,
24                           dataConSig, dataConArgTys
25                         )
26 import IdInfo           ( StrictnessInfo(..), Demand(..),
27                           wwPrim, wwStrict, wwEnum, wwUnpack
28                         )
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
35                         )
36 import Pretty           ( ppStr )
37 import PrimOp           ( PrimOp(..) )
38 import SaLib
39 import TyCon            ( maybeTyConSingleCon, isEnumerationTyCon,
40                           TyCon{-instance Eq-}
41                         )
42 import Type             ( maybeAppDataTyCon, isPrimType )
43 import Util             ( isIn, isn'tIn, nOfThem, zipWithEqual,
44                           pprTrace, panic, pprPanic, assertPanic
45                         )
46
47 returnsRealWorld = panic "SaAbsInt.returnsRealWorld (ToDo)"
48 \end{code}
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection[AbsVal-ops]{Operations on @AbsVals@}
53 %*                                                                      *
54 %************************************************************************
55
56 Least upper bound, greatest lower bound.
57
58 \begin{code}
59 lub, glb :: AbsVal -> AbsVal -> AbsVal
60
61 lub val1 val2 | isBot val1    = val2    -- The isBot test includes the case where
62 lub val1 val2 | isBot val2    = val1    -- one of the val's is a function which
63                                         -- always returns bottom, such as \y.x,
64                                         -- when x is bound to bottom.
65
66 lub (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual lub xs ys)
67
68 lub _             _           = AbsTop  -- Crude, but conservative
69                                         -- The crudity only shows up if there
70                                         -- are functions involved
71
72 -- Slightly funny glb; for absence analysis only;
73 -- AbsBot is the safe answer.
74 --
75 -- Using anyBot rather than just testing for AbsBot is important.
76 -- Consider:
77 --
78 --   f = \a b -> ...
79 --
80 --   g = \x y z -> case x of
81 --                   []     -> f x
82 --                   (p:ps) -> f p
83 --
84 -- Now, the abstract value of the branches of the case will be an
85 -- AbsFun, but when testing for z's absence we want to spot that it's
86 -- an AbsFun which can't possibly return AbsBot.  So when glb'ing we
87 -- mustn't be too keen to bale out and return AbsBot; the anyBot test
88 -- spots that (f x) can't possibly return AbsBot.
89
90 -- We have also tripped over the following interesting case:
91 --      case x of
92 --        []     -> \y -> 1
93 --        (p:ps) -> f
94 --
95 -- Now, suppose f is bound to AbsTop.  Does this expression mention z?
96 -- Obviously not.  But the case will take the glb of AbsTop (for f) and
97 -- an AbsFun (for \y->1). We should not bale out and give AbsBot, because
98 -- that would say that it *does* mention z (or anything else for that matter).
99 -- Nor can we always return AbsTop, because the AbsFun might be something
100 -- like (\y->z), which obviously does mention z. The point is that we're
101 -- glbing two functions, and AbsTop is not actually the top of the function
102 -- lattice.  It is more like (\xyz -> x|y|z); that is, AbsTop returns
103 -- poison iff any of its arguments do.
104
105 -- Deal with functions specially, because AbsTop isn't the
106 -- top of their domain.
107
108 glb v1 v2
109   | is_fun v1 || is_fun v2
110   = if not (anyBot v1) && not (anyBot v2)
111     then
112         AbsTop
113     else
114         AbsBot
115   where
116     is_fun (AbsFun _ _ _)   = True
117     is_fun (AbsApproxFun _) = True      -- Not used, but the glb works ok
118     is_fun other            = False
119
120 -- The non-functional cases are quite straightforward
121
122 glb (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual glb xs ys)
123
124 glb AbsTop       v2           = v2
125 glb v1           AbsTop       = v1
126
127 glb _            _            = AbsBot          -- Be pessimistic
128
129
130
131 combineCaseValues
132         :: AnalysisKind
133         -> AbsVal       -- Value of scrutinee
134         -> [AbsVal]     -- Value of branches (at least one)
135         -> AbsVal       -- Result
136
137 -- For strictness analysis, see if the scrutinee is bottom; if so
138 -- return bottom; otherwise, the lub of the branches.
139
140 combineCaseValues StrAnal AbsBot          branches = AbsBot
141 combineCaseValues StrAnal other_scrutinee branches
142         -- Scrutinee can only be AbsBot, AbsProd or AbsTop
143   = ASSERT(ok_scrutinee)
144     foldr1 lub branches
145   where
146     ok_scrutinee
147       = case other_scrutinee of {
148           AbsTop    -> True;    -- i.e., cool
149           AbsProd _ -> True;    -- ditto
150           _         -> False    -- party over
151         }
152
153 -- For absence analysis, check if the scrutinee is all poison (isBot)
154 -- If so, return poison (AbsBot); otherwise, any nested poison will come
155 -- out from looking at the branches, so just glb together the branches
156 -- to get the worst one.
157
158 combineCaseValues AbsAnal AbsBot          branches = AbsBot
159 combineCaseValues AbsAnal other_scrutinee branches
160         -- Scrutinee can only be AbsBot, AbsProd or AbsTop
161   = ASSERT(ok_scrutinee)
162     let
163         result = foldr1 glb branches
164
165         tracer = if at_least_one_AbsFun && at_least_one_AbsTop
166                     && no_AbsBots then
167                     pprTrace "combineCase:" (ppr PprDebug branches)
168                  else
169                     id
170     in
171 --    tracer (
172     result
173 --    )
174   where
175     ok_scrutinee
176       = case other_scrutinee of {
177           AbsTop    -> True;    -- i.e., cool
178           AbsProd _ -> True;    -- ditto
179           _         -> False    -- party over
180         }
181
182     at_least_one_AbsFun = foldr ((||) . is_AbsFun) False branches
183     at_least_one_AbsTop = foldr ((||) . is_AbsTop) False branches
184     no_AbsBots = foldr ((&&) . is_not_AbsBot) True branches
185
186     is_AbsFun x = case x of { AbsFun _ _ _ -> True; _ -> False }
187     is_AbsTop x = case x of { AbsTop -> True; _ -> False }
188     is_not_AbsBot x = case x of { AbsBot -> False; _ -> True }
189 \end{code}
190
191 @isBot@ returns True if its argument is (a representation of) bottom.  The
192 ``representation'' part is because we need to detect the bottom {\em function}
193 too.  To detect the bottom function, bind its args to top, and see if it
194 returns bottom.
195
196 Used only in strictness analysis:
197 \begin{code}
198 isBot :: AbsVal -> Bool
199
200 isBot AbsBot                 = True
201 isBot (AbsFun args body env) = isBot (absEval StrAnal body env)
202                                -- Don't bother to extend the envt because
203                                -- unbound variables default to AbsTop anyway
204 isBot other                  = False
205 \end{code}
206
207 Used only in absence analysis:
208 \begin{code}
209 anyBot :: AbsVal -> Bool
210
211 anyBot AbsBot                 = True    -- poisoned!
212 anyBot AbsTop                 = False
213 anyBot (AbsProd vals)         = any anyBot vals
214 anyBot (AbsFun args body env) = anyBot (absEval AbsAnal body env)
215 anyBot (AbsApproxFun demands) = False
216
217     -- AbsApproxFun can only arise in absence analysis from the Demand
218     -- info of an imported value; whatever it is we're looking for is
219     -- certainly not present over in the imported value.
220 \end{code}
221
222 @widen@ takes an @AbsVal@, $val$, and returns and @AbsVal@ which is
223 approximated by $val$.  Furthermore, the result has no @AbsFun@s in
224 it, so it can be compared for equality by @sameVal@.
225
226 \begin{code}
227 widen :: AnalysisKind -> AbsVal -> AbsVal
228
229 widen StrAnal (AbsFun args body env)
230   | isBot (absEval StrAnal body env) = AbsBot
231   | otherwise
232   = ASSERT (not (null args))
233     AbsApproxFun (map (findDemandStrOnly env body) args)
234
235     -- It's worth checking for a function which is unconditionally
236     -- bottom.  Consider
237     --
238     --  f x y = let g y = case x of ...
239     --          in (g ..) + (g ..)
240     --
241     -- Here, when we are considering strictness of f in x, we'll
242     -- evaluate the body of f with x bound to bottom.  The current
243     -- strategy is to bind g to its *widened* value; without the isBot
244     -- (...) test above, we'd bind g to an AbsApproxFun, and deliver
245     -- Top, not Bot as the value of f's rhs.  The test spots the
246     -- unconditional bottom-ness of g when x is bottom.  (Another
247     -- alternative here would be to bind g to its exact abstract
248     -- value, but that entails lots of potential re-computation, at
249     -- every application of g.)
250
251 widen StrAnal (AbsProd vals) = AbsProd (map (widen StrAnal) vals)
252 widen StrAnal other_val      = other_val
253
254
255 widen AbsAnal (AbsFun args body env)
256   | anyBot (absEval AbsAnal body env) = AbsBot
257         -- In the absence-analysis case it's *essential* to check
258         -- that the function has no poison in its body.  If it does,
259         -- anywhere, then the whole function is poisonous.
260
261   | otherwise
262   = ASSERT (not (null args))
263     AbsApproxFun (map (findDemandAbsOnly env body) args)
264
265 widen AbsAnal (AbsProd vals) = AbsProd (map (widen AbsAnal) vals)
266
267         -- It's desirable to do a good job of widening for product
268         -- values.  Consider
269         --
270         --      let p = (x,y)
271         --      in ...(case p of (x,y) -> x)...
272         --
273         -- Now, is y absent in this expression?  Currently the
274         -- analyser widens p before looking at p's scope, to avoid
275         -- lots of recomputation in the case where p is a function.
276         -- So if widening doesn't have a case for products, we'll
277         -- widen p to AbsBot (since when searching for absence in y we
278         -- bind y to poison ie AbsBot), and now we are lost.
279
280 widen AbsAnal other_val = other_val
281
282 -- WAS:   if anyBot val then AbsBot else AbsTop
283 -- Nowadays widen is doing a better job on functions for absence analysis.
284 \end{code}
285
286 @crudeAbsWiden@ is used just for absence analysis, and always
287 returns AbsTop or AbsBot, so it widens to a two-point domain
288
289 \begin{code}
290 crudeAbsWiden :: AbsVal -> AbsVal
291 crudeAbsWiden val = if anyBot val then AbsBot else AbsTop
292 \end{code}
293
294 @sameVal@ compares two abstract values for equality.  It can't deal with
295 @AbsFun@, but that should have been removed earlier in the day by @widen@.
296
297 \begin{code}
298 sameVal :: AbsVal -> AbsVal -> Bool     -- Can't handle AbsFun!
299
300 #ifdef DEBUG
301 sameVal (AbsFun _ _ _) _ = panic "sameVal: AbsFun: arg1"
302 sameVal _ (AbsFun _ _ _) = panic "sameVal: AbsFun: arg2"
303 #endif
304
305 sameVal AbsBot AbsBot = True
306 sameVal AbsBot other  = False   -- widen has reduced AbsFun bots to AbsBot
307
308 sameVal AbsTop AbsTop = True
309 sameVal AbsTop other  = False           -- Right?
310
311 sameVal (AbsProd vals1) (AbsProd vals2) = and (zipWithEqual sameVal vals1 vals2)
312 sameVal (AbsProd _)     AbsTop          = False
313 sameVal (AbsProd _)     AbsBot          = False
314
315 sameVal (AbsApproxFun str1) (AbsApproxFun str2) = str1 == str2
316 sameVal (AbsApproxFun _)    AbsTop              = False
317 sameVal (AbsApproxFun _)    AbsBot              = False
318
319 sameVal val1 val2 = panic "sameVal: type mismatch or AbsFun encountered"
320 \end{code}
321
322
323 @evalStrictness@ compares a @Demand@ with an abstract value, returning
324 @True@ iff the abstract value is {\em less defined} than the demand.
325 (@True@ is the exciting answer; @False@ is always safe.)
326
327 \begin{code}
328 evalStrictness :: Demand
329                -> AbsVal
330                -> Bool          -- True iff the value is sure
331                                 -- to be less defined than the Demand
332
333 evalStrictness (WwLazy _) _   = False
334 evalStrictness WwStrict   val = isBot val
335 evalStrictness WwEnum     val = isBot val
336
337 evalStrictness (WwUnpack demand_info) val
338   = case val of
339       AbsTop       -> False
340       AbsBot       -> True
341       AbsProd vals -> or (zipWithEqual evalStrictness demand_info vals)
342       _            -> trace "evalStrictness?" False
343
344 evalStrictness WwPrim val
345   = case val of
346       AbsTop -> False
347
348       other  ->   -- A primitive value should be defined, never bottom;
349                   -- hence this paranoia check
350                 pprPanic "evalStrictness: WwPrim:" (ppr PprDebug other)
351 \end{code}
352
353 For absence analysis, we're interested in whether "poison" in the
354 argument (ie a bottom therein) can propagate to the result of the
355 function call; that is, whether the specified demand can {\em
356 possibly} hit poison.
357
358 \begin{code}
359 evalAbsence (WwLazy True) _ = False     -- Can't possibly hit poison
360                                         -- with Absent demand
361
362 evalAbsence (WwUnpack demand_info) val
363   = case val of
364         AbsTop       -> False           -- No poison in here
365         AbsBot       -> True            -- Pure poison
366         AbsProd vals -> or (zipWithEqual evalAbsence demand_info vals)
367         _            -> panic "evalAbsence: other"
368
369 evalAbsence other val = anyBot val
370   -- The demand is conservative; even "Lazy" *might* evaluate the
371   -- argument arbitrarily so we have to look everywhere for poison
372 \end{code}
373
374 %************************************************************************
375 %*                                                                      *
376 \subsection[absEval]{Evaluate an expression in the abstract domain}
377 %*                                                                      *
378 %************************************************************************
379
380 \begin{code}
381 -- The isBottomingId stuf is now dealt with via the Id's strictness info
382 -- absId anal var env | isBottomingId var
383 --   = case anal of
384 --      StrAnal -> AbsBot       -- See discussion below
385 --      AbsAnal -> AbsTop       -- Just want to see if there's any poison in
386                                 -- error's arg
387
388 absId anal var env
389   = let
390      result =
391       case (lookupAbsValEnv env var, getIdStrictness var, getIdUnfolding var) of
392
393         (Just abs_val, _, _) ->
394                         abs_val -- Bound in the environment
395
396         (Nothing, NoStrictnessInfo, LitForm _) ->
397                         AbsTop  -- Literals all terminate, and have no poison
398
399         (Nothing, NoStrictnessInfo, ConForm _ _) ->
400                         AbsTop -- An imported constructor won't have
401                                -- bottom components, nor poison!
402
403         (Nothing, NoStrictnessInfo, GenForm _ _ unfolding _) ->
404                         -- We have an unfolding for the expr
405                         -- Assume the unfolding has no free variables since it
406                         -- came from inside the Id
407                         absEval anal (unTagBinders unfolding) env
408                 -- Notice here that we only look in the unfolding if we don't
409                 -- have strictness info (an unusual situation).
410                 -- We could have chosen to look in the unfolding if it exists,
411                 -- and only try the strictness info if it doesn't, and that would
412                 -- give more accurate results, at the cost of re-abstract-interpreting
413                 -- the unfolding every time.
414                 -- We found only one place where the look-at-unfolding-first
415                 -- method gave better results, which is in the definition of
416                 -- showInt in the Prelude.  In its defintion, fromIntegral is
417                 -- not inlined (it's big) but ab-interp-ing its unfolding gave
418                 -- a better result than looking at its strictness only.
419                 --  showInt :: Integral a => a -> [Char] -> [Char]
420                 -- !       {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
421                 --         "U(U(U(U(SA)AAAAAAAAL)AA)AAAAASAAASA)" {...} _N_ _N_ #-}
422                 -- --- 42,44 ----
423                 --   showInt :: Integral a => a -> [Char] -> [Char]
424                 -- !       {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
425                 --        "U(U(U(U(SL)LLLLLLLLL)LL)LLLLLSLLLLL)" _N_ _N_ #-}
426
427
428         (Nothing, strictness_info, _) ->
429                         -- Includes MagicForm, IWantToBeINLINEd, NoUnfoldingDetails
430                         -- Try the strictness info
431                         absValFromStrictness anal strictness_info
432
433
434         --      Done via strictness now
435         --        GenForm _ BottomForm _ _ -> AbsBot
436     in
437     -- pprTrace "absId:" (ppBesides [ppr PprDebug var, ppStr "=:", pp_anal anal, ppStr ":=",ppr PprDebug result]) (
438     result
439     -- )
440   where
441     pp_anal StrAnal = ppStr "STR"
442     pp_anal AbsAnal = ppStr "ABS"
443
444 absEvalAtom anal (VarArg v) env = absId anal v env
445 absEvalAtom anal (LitArg _) env = AbsTop
446 \end{code}
447
448 \begin{code}
449 absEval :: AnalysisKind -> CoreExpr -> AbsValEnv -> AbsVal
450
451 absEval anal (Var var) env = absId anal var env
452
453 absEval anal (Lit _) env = AbsTop
454     -- What if an unboxed literal?  That's OK: it terminates, so its
455     -- abstract value is AbsTop.
456
457     -- For absence analysis, a literal certainly isn't the "poison" variable
458 \end{code}
459
460 Discussion about \tr{error} (following/quoting Lennart): Any expression
461 \tr{error e} is regarded as bottom (with HBC, with the
462 \tr{-ffail-strict} flag, on with \tr{-O}).
463
464 Regarding it as bottom gives much better strictness properties for
465 some functions.  E.g.
466 \begin{verbatim}
467         f [x] y = x+y
468         f (x:xs) y = f xs (x+y)
469 i.e.
470         f [] _ = error "no match"
471         f [x] y = x+y
472         f (x:xs) y = f xs (x+y)
473 \end{verbatim}
474 is strict in \tr{y}, which you really want.  But, it may lead to
475 transformations that turn a call to \tr{error} into non-termination.
476 (The odds of this happening aren't good.)
477
478
479 Things are a little different for absence analysis, because we want
480 to make sure that any poison (?????)
481
482 \begin{code}
483 absEval StrAnal (Prim SeqOp [TyArg _, e]) env
484   = ASSERT(isValArg e)
485     if isBot (absEvalAtom StrAnal e env) then AbsBot else AbsTop
486         -- This is a special case to ensure that seq# is strict in its argument.
487         -- The comments below (for most normal PrimOps) do not apply.
488
489 absEval StrAnal (Prim op es) env = AbsTop
490         -- The arguments are all of unboxed type, so they will already
491         -- have been eval'd.  If the boxed version was bottom, we'll
492         -- already have returned bottom.
493
494         -- Actually, I believe we are saying that either (1) the
495         -- primOp uses unboxed args and they've been eval'ed, so
496         -- there's no need to force strictness here, _or_ the primOp
497         -- uses boxed args and we don't know whether or not it's
498         -- strict, so we assume laziness. (JSM)
499
500 absEval AbsAnal (Prim op as) env
501   = if any anyBot [absEvalAtom AbsAnal a env | a <- as, isValArg a]
502     then AbsBot
503     else AbsTop
504         -- For absence analysis, we want to see if the poison shows up...
505
506 absEval anal (Con con as) env
507   | has_single_con
508   = AbsProd [absEvalAtom anal a env | a <- as, isValArg a]
509
510   | otherwise   -- Not single-constructor
511   = case anal of
512         StrAnal ->      -- Strictness case: it's easy: it certainly terminates
513                    AbsTop
514         AbsAnal ->      -- In the absence case we need to be more
515                         -- careful: look to see if there's any
516                         -- poison in the components
517                    if any anyBot [absEvalAtom AbsAnal a env | a <- as, isValArg a]
518                    then AbsBot
519                    else AbsTop
520   where
521     (_,_,_, tycon) = dataConSig con
522     has_single_con = maybeToBool (maybeTyConSingleCon tycon)
523 \end{code}
524
525 \begin{code}
526 absEval anal (Lam (ValBinder binder) body) env
527   = AbsFun [binder] body env
528 absEval anal (Lam other_binder expr) env
529   = absEval  anal expr env
530 absEval anal (App f a) env | isValArg a
531   = absApply anal (absEval anal f env) (absEvalAtom anal a env)
532 absEval anal (App expr _) env
533   = absEval anal expr env
534 \end{code}
535
536 For primitive cases, just GLB the branches, then LUB with the expr part.
537
538 \begin{code}
539 absEval anal (Case expr (PrimAlts alts deflt)) env
540   = let
541         expr_val    = absEval anal expr env
542         abs_alts    = [ absEval anal rhs env | (_, rhs) <- alts ]
543                         -- Don't bother to extend envt, because unbound vars
544                         -- default to the conservative AbsTop
545
546         abs_deflt   = absEvalDefault anal expr_val deflt env
547     in
548         combineCaseValues anal expr_val
549                                (abs_deflt ++ abs_alts)
550
551 absEval anal (Case expr (AlgAlts alts deflt)) env
552   = let
553         expr_val  = absEval anal expr env
554         abs_alts  = [ absEvalAlgAlt anal expr_val alt env | alt <- alts ]
555         abs_deflt = absEvalDefault anal expr_val deflt env
556     in
557     let
558         result =
559           combineCaseValues anal expr_val
560                                 (abs_deflt ++ abs_alts)
561     in
562 {-
563     (case anal of
564         StrAnal -> id
565         _ -> 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)))
566     )
567 -}
568     result
569 \end{code}
570
571 For @Lets@ we widen the value we get.  This is nothing to
572 do with fixpointing.  The reason is so that we don't get an explosion
573 in the amount of computation.  For example, consider:
574 \begin{verbatim}
575       let
576         g a = case a of
577                 q1 -> ...
578                 q2 -> ...
579         f x = case x of
580                 p1 -> ...g r...
581                 p2 -> ...g s...
582       in
583         f e
584 \end{verbatim}
585 If we bind @f@ and @g@ to their exact abstract value, then we'll
586 ``execute'' one call to @f@ and {\em two} calls to @g@.  This can blow
587 up exponentially.  Widening cuts it off by making a fixed
588 approximation to @f@ and @g@, so that the bodies of @f@ and @g@ are
589 not evaluated again at all when they are called.
590
591 Of course, this can lose useful joint strictness, which is sad.  An
592 alternative approach would be to try with a certain amount of ``fuel''
593 and be prepared to bale out.
594
595 \begin{code}
596 absEval anal (Let (NonRec binder e1) e2) env
597   = let
598         new_env = addOneToAbsValEnv env binder (widen anal (absEval anal e1 env))
599     in
600         -- The binder of a NonRec should *not* be of unboxed type,
601         -- hence no need to strictly evaluate the Rhs.
602     absEval anal e2 new_env
603
604 absEval anal (Let (Rec pairs) body) env
605   = let
606         (binders,rhss) = unzip pairs
607         rhs_vals = cheapFixpoint anal binders rhss env  -- Returns widened values
608         new_env  = growAbsValEnvList env (binders `zip` rhs_vals)
609     in
610     absEval anal body new_env
611
612 absEval anal (SCC cc expr) env = absEval anal expr env
613 \end{code}
614
615 \begin{code}
616 absEvalAlgAlt :: AnalysisKind -> AbsVal -> (Id,[Id],CoreExpr) -> AbsValEnv -> AbsVal
617
618 absEvalAlgAlt anal (AbsProd arg_vals) (con, args, rhs) env
619   =     -- The scrutinee is a product value, so it must be of a single-constr
620         -- type; so the constructor in this alternative must be the right one
621         -- so we can go ahead and bind the constructor args to the components
622         -- of the product value.
623     ASSERT(length arg_vals == length args)
624     let
625          new_env = growAbsValEnvList env (args `zip` arg_vals)
626     in
627     absEval anal rhs new_env
628
629 absEvalAlgAlt anal other_scrutinee (con, args, rhs) env
630   =     -- Scrutinised value is Top or Bot (it can't be a function!)
631         -- So just evaluate the rhs with all constr args bound to Top.
632         -- (If the scrutinee is Top we'll never evaluated this function
633         -- call anyway!)
634     ASSERT(ok_scrutinee)
635     absEval anal rhs env
636   where
637     ok_scrutinee
638       = case other_scrutinee of {
639           AbsTop -> True;   -- i.e., OK
640           AbsBot -> True;   -- ditto
641           _      -> False   -- party over
642         }
643
644
645 absEvalDefault :: AnalysisKind
646                -> AbsVal                -- Value of scrutinee
647                -> CoreCaseDefault
648                -> AbsValEnv
649                -> [AbsVal]              -- Empty or singleton
650
651 absEvalDefault anal scrut_val NoDefault env = []
652 absEvalDefault anal scrut_val (BindDefault binder expr) env
653   = [absEval anal expr (addOneToAbsValEnv env binder scrut_val)]
654 \end{code}
655
656 %************************************************************************
657 %*                                                                      *
658 \subsection[absApply]{Apply an abstract function to an abstract argument}
659 %*                                                                      *
660 %************************************************************************
661
662 Easy ones first:
663
664 \begin{code}
665 absApply :: AnalysisKind -> AbsVal -> AbsVal -> AbsVal
666
667 absApply anal AbsBot arg = AbsBot
668   -- AbsBot represents the abstract bottom *function* too
669
670 absApply StrAnal AbsTop arg = AbsTop
671 absApply AbsAnal AbsTop arg = if anyBot arg
672                               then AbsBot
673                               else AbsTop
674         -- To be conservative, we have to assume that a function about
675         -- which we know nothing (AbsTop) might look at some part of
676         -- its argument
677 \end{code}
678
679 An @AbsFun@ with only one more argument needed---bind it and eval the
680 result.  A @Lam@ with two or more args: return another @AbsFun@ with
681 an augmented environment.
682
683 \begin{code}
684 absApply anal (AbsFun [binder] body env) arg
685   = absEval anal body (addOneToAbsValEnv env binder arg)
686
687 absApply anal (AbsFun (binder:bs) body env) arg
688   = AbsFun bs body (addOneToAbsValEnv env binder arg)
689 \end{code}
690
691 \begin{code}
692 absApply StrAnal (AbsApproxFun (arg1_demand:ds)) arg
693   = if evalStrictness arg1_demand arg
694     then AbsBot
695     else case ds of
696            []    -> AbsTop
697            other -> AbsApproxFun ds
698
699 absApply AbsAnal (AbsApproxFun (arg1_demand:ds)) arg
700   = if evalAbsence arg1_demand arg
701     then AbsBot
702     else case ds of
703            []    -> AbsTop
704            other -> AbsApproxFun ds
705
706 #ifdef DEBUG
707 absApply anal (AbsApproxFun []) arg = panic ("absApply: Duff function: AbsApproxFun." ++ show anal)
708 absApply anal (AbsFun [] _ _)   arg = panic ("absApply: Duff function: AbsFun." ++ show anal)
709 absApply anal (AbsProd _)       arg = panic ("absApply: Duff function: AbsProd." ++ show anal)
710 #endif
711 \end{code}
712
713
714
715
716 %************************************************************************
717 %*                                                                      *
718 \subsection[findStrictness]{Determine some binders' strictness}
719 %*                                                                      *
720 %************************************************************************
721
722 @findStrictness@ applies the function \tr{\ ids -> expr} to
723 \tr{[bot,top,top,...]}, \tr{[top,bot,top,top,...]}, etc., (i.e., once
724 with @AbsBot@ in each argument position), and evaluates the resulting
725 abstract value; it returns a vector of @Demand@s saying whether the
726 result of doing this is guaranteed to be bottom.  This tells the
727 strictness of the function in each of the arguments.
728
729 If an argument is of unboxed type, then we declare that function to be
730 strict in that argument.
731
732 We don't really have to make up all those lists of mostly-@AbsTops@;
733 unbound variables in an @AbsValEnv@ are implicitly mapped to that.
734
735 See notes on @addStrictnessInfoToId@.
736
737 \begin{code}
738 findStrictness :: StrAnalFlags
739                -> [Type]        -- Types of args in which strictness is wanted
740                -> AbsVal        -- Abstract strictness value of function
741                -> AbsVal        -- Abstract absence value of function
742                -> [Demand]      -- Resulting strictness annotation
743
744 findStrictness strflags [] str_val abs_val = []
745
746 findStrictness strflags (ty:tys) str_val abs_val
747   = let
748         demand       = findRecDemand strflags [] str_fn abs_fn ty
749         str_fn val   = absApply StrAnal str_val val
750         abs_fn val   = absApply AbsAnal abs_val val
751
752         demands = findStrictness strflags tys
753                         (absApply StrAnal str_val AbsTop)
754                         (absApply AbsAnal abs_val AbsTop)
755     in
756     demand : demands
757 \end{code}
758
759
760 \begin{code}
761 findDemandStrOnly str_env expr binder   -- Only strictness environment available
762   = findRecDemand strflags [] str_fn abs_fn (idType binder)
763   where
764     str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
765     abs_fn val = AbsBot         -- Always says poison; so it looks as if
766                                 -- nothing is absent; safe
767     strflags   = getStrAnalFlags str_env
768
769 findDemandAbsOnly abs_env expr binder   -- Only absence environment available
770   = findRecDemand strflags [] str_fn abs_fn (idType binder)
771   where
772     str_fn val = AbsBot         -- Always says non-termination;
773                                 -- that'll make findRecDemand peer into the
774                                 -- structure of the value.
775     abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
776     strflags   = getStrAnalFlags abs_env
777
778
779 findDemand str_env abs_env expr binder
780   = findRecDemand strflags [] str_fn abs_fn (idType binder)
781   where
782     str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
783     abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
784     strflags   = getStrAnalFlags str_env
785 \end{code}
786
787 @findRecDemand@ is where we finally convert strictness/absence info
788 into ``Demands'' which we can pin on Ids (etc.).
789
790 NOTE: What do we do if something is {\em both} strict and absent?
791 Should \tr{f x y z = error "foo"} says that \tr{f}'s arguments are all
792 strict (because of bottoming effect of \tr{error}) or all absent
793 (because they're not used)?
794
795 Well, for practical reasons, we prefer absence over strictness.  In
796 particular, it makes the ``default defaults'' for class methods (the
797 ones that say \tr{defm.foo dict = error "I don't exist"}) come out
798 nicely [saying ``the dict isn't used''], rather than saying it is
799 strict in every component of the dictionary [massive gratuitious
800 casing to take the dict apart].
801
802 But you could have examples where going for strictness would be better
803 than absence.  Consider:
804 \begin{verbatim}
805         let x = something big
806         in
807         f x y z + g x
808 \end{verbatim}
809
810 If \tr{x} is marked absent in \tr{f}, but not strict, and \tr{g} is
811 lazy, then the thunk for \tr{x} will be built.  If \tr{f} was strict,
812 then we'd let-to-case it:
813 \begin{verbatim}
814         case something big of
815           x -> f x y z + g x
816 \end{verbatim}
817 Ho hum.
818
819 \begin{code}
820 findRecDemand :: StrAnalFlags
821               -> [TyCon]            -- TyCons already seen; used to avoid
822                                     -- zooming into recursive types
823               -> (AbsVal -> AbsVal) -- The strictness function
824               -> (AbsVal -> AbsVal) -- The absence function
825               -> Type       -- The type of the argument
826               -> Demand
827
828 findRecDemand strflags seen str_fn abs_fn ty
829   = if isPrimType ty then -- It's a primitive type!
830        wwPrim
831
832     else if not (anyBot (abs_fn AbsBot)) then -- It's absent
833        -- We prefer absence over strictness: see NOTE above.
834        WwLazy True
835
836     else if not (all_strict ||
837                  (num_strict && is_numeric_type ty) ||
838                  (isBot (str_fn AbsBot))) then
839         WwLazy False -- It's not strict and we're not pretending
840
841     else -- It's strict (or we're pretending it is)!
842
843        case maybeAppDataTyCon ty of
844
845          Nothing    -> wwStrict
846
847          Just (tycon,tycon_arg_tys,[data_con]) | tycon `not_elem` seen ->
848            -- Single constructor case, tycon not already seen higher up
849            let
850               cmpnt_tys = dataConArgTys data_con tycon_arg_tys
851               prod_len = length cmpnt_tys
852
853               compt_strict_infos
854                 = [ findRecDemand strflags (tycon:seen)
855                          (\ cmpnt_val ->
856                                str_fn (mkMainlyTopProd prod_len i cmpnt_val)
857                          )
858                          (\ cmpnt_val ->
859                                abs_fn (mkMainlyTopProd prod_len i cmpnt_val)
860                          )
861                      cmpnt_ty
862                   | (cmpnt_ty, i) <- cmpnt_tys `zip` [1..] ]
863            in
864            if null compt_strict_infos then
865                  if isEnumerationTyCon tycon then wwEnum else wwStrict
866            else
867                  wwUnpack compt_strict_infos
868           where
869            not_elem = isn'tIn "findRecDemand"
870
871          Just (tycon,_,_) ->
872                 -- Multi-constr data types, *or* an abstract data
873                 -- types, *or* things we don't have a way of conveying
874                 -- the info over module boundaries (class ops,
875                 -- superdict sels, dfns).
876             if isEnumerationTyCon tycon then
877                 wwEnum
878             else
879                 wwStrict
880   where
881     (all_strict, num_strict) = strflags
882
883     is_numeric_type ty
884       = case (maybeAppDataTyCon ty) of -- NB: duplicates stuff done above
885           Nothing -> False
886           Just (tycon, _, _)
887             | tycon `is_elem`
888               [intTyCon, integerTyCon,
889                doubleTyCon, floatTyCon,
890                wordTyCon, addrTyCon]
891             -> True
892           _{-something else-} -> False
893       where
894         is_elem = isIn "is_numeric_type"
895
896     -- mkMainlyTopProd: make an AbsProd that is all AbsTops ("n"-1 of
897     -- them) except for a given value in the "i"th position.
898
899     mkMainlyTopProd :: Int -> Int -> AbsVal -> AbsVal
900
901     mkMainlyTopProd n i val
902       = let
903             befores = nOfThem (i-1) AbsTop
904             afters  = nOfThem (n-i) AbsTop
905         in
906         AbsProd (befores ++ (val : afters))
907 \end{code}
908
909 %************************************************************************
910 %*                                                                      *
911 \subsection[fixpoint]{Fixpointer for the strictness analyser}
912 %*                                                                      *
913 %************************************************************************
914
915 The @fixpoint@ functions take a list of \tr{(binder, expr)} pairs, an
916 environment, and returns the abstract value of each binder.
917
918 The @cheapFixpoint@ function makes a conservative approximation,
919 by binding each of the variables to Top in their own right hand sides.
920 That allows us to make rapid progress, at the cost of a less-than-wonderful
921 approximation.
922
923 \begin{code}
924 cheapFixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
925
926 cheapFixpoint AbsAnal [id] [rhs] env
927   = [crudeAbsWiden (absEval AbsAnal rhs new_env)]
928   where
929     new_env = addOneToAbsValEnv env id AbsTop   -- Unsafe starting point!
930                     -- In the just-one-binding case, we guarantee to
931                     -- find a fixed point in just one iteration,
932                     -- because we are using only a two-point domain.
933                     -- This improves matters in cases like:
934                     --
935                     --  f x y = letrec g = ...g...
936                     --          in g x
937                     --
938                     -- Here, y isn't used at all, but if g is bound to
939                     -- AbsBot we simply get AbsBot as the next
940                     -- iteration too.
941
942 cheapFixpoint anal ids rhss env
943   = [widen anal (absEval anal rhs new_env) | rhs <- rhss]
944                 -- We do just one iteration, starting from a safe
945                 -- approximation.  This won't do a good job in situations
946                 -- like:
947                 --      \x -> letrec f = ...g...
948                 --                   g = ...f...x...
949                 --            in
950                 --            ...f...
951                 -- Here, f will end up bound to Top after one iteration,
952                 -- and hence we won't spot the strictness in x.
953                 -- (A second iteration would solve this.  ToDo: try the effect of
954                 --  really searching for a fixed point.)
955   where
956     new_env = growAbsValEnvList env [(id,safe_val) | id <- ids]
957
958     safe_val
959       = case anal of    -- The safe starting point
960           StrAnal -> AbsTop
961           AbsAnal -> AbsBot
962 \end{code}
963
964 \begin{verbatim}
965 mkLookupFun :: (key -> key -> Bool)     -- Equality predicate
966             -> (key -> key -> Bool)     -- Less-than predicate
967             -> [(key,val)]              -- The assoc list
968             -> key                      -- The key
969             -> Maybe val                -- The corresponding value
970
971 mkLookupFun eq lt alist s
972   = case [a | (s',a) <- alist, s' `eq` s] of
973       []    -> Nothing
974       (a:_) -> Just a
975 \end{verbatim}
976
977 \begin{code}
978 fixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
979
980 fixpoint anal [] _ env = []
981
982 fixpoint anal ids rhss env
983   = fix_loop initial_vals
984   where
985     initial_val id
986       = case anal of    -- The (unsafe) starting point
987           StrAnal -> if (returnsRealWorld (idType id))
988                      then AbsTop -- this is a massively horrible hack (SLPJ 95/05)
989                      else AbsBot
990           AbsAnal -> AbsTop
991
992     initial_vals = [ initial_val id | id <- ids ]
993
994     fix_loop :: [AbsVal] -> [AbsVal]
995
996     fix_loop current_widened_vals
997       = let
998             new_env  = growAbsValEnvList env (ids `zip` current_widened_vals)
999             new_vals = [ absEval anal rhs new_env | rhs <- rhss ]
1000             new_widened_vals = map (widen anal) new_vals
1001         in
1002         if (and (zipWith sameVal current_widened_vals new_widened_vals)) then
1003             current_widened_vals
1004
1005             -- NB: I was too chicken to make that a zipWithEqual,
1006             -- lest I jump into a black hole.  WDP 96/02
1007
1008             -- Return the widened values.  We might get a slightly
1009             -- better value by returning new_vals (which we used to
1010             -- do, see below), but alas that means that whenever the
1011             -- function is called we have to re-execute it, which is
1012             -- expensive.
1013
1014             -- OLD VERSION
1015             -- new_vals
1016             -- Return the un-widened values which may be a bit better
1017             -- than the widened ones, and are guaranteed safe, since
1018             -- they are one iteration beyond current_widened_vals,
1019             -- which itself is a fixed point.
1020         else
1021             fix_loop new_widened_vals
1022 \end{code}
1023
1024 For absence analysis, we make do with a very very simple approach:
1025 look for convergence in a two-point domain.
1026
1027 We used to use just one iteration, starting with the variables bound
1028 to @AbsBot@, which is safe.
1029
1030 Prior to that, we used one iteration starting from @AbsTop@ (which
1031 isn't safe).  Why isn't @AbsTop@ safe?  Consider:
1032 \begin{verbatim}
1033         letrec
1034           x = ...p..d...
1035           d = (x,y)
1036         in
1037         ...
1038 \end{verbatim}
1039 Here, if p is @AbsBot@, then we'd better {\em not} end up with a ``fixed
1040 point'' of @d@ being @(AbsTop, AbsTop)@!  An @AbsBot@ initial value is
1041 safe because it gives poison more often than really necessary, and
1042 thus may miss some absence, but will never claim absence when it ain't
1043 so.
1044
1045 Anyway, one iteration starting with everything bound to @AbsBot@ give
1046 bad results for
1047
1048         f = \ x -> ...f...
1049
1050 Here, f would always end up bound to @AbsBot@, which ain't very
1051 clever, because then it would introduce poison whenever it was
1052 applied.  Much better to start with f bound to @AbsTop@, and widen it
1053 to @AbsBot@ if any poison shows up. In effect we look for convergence
1054 in the two-point @AbsTop@/@AbsBot@ domain.
1055
1056 What we miss (compared with the cleverer strictness analysis) is
1057 spotting that in this case
1058
1059         f = \ x y -> ...y...(f x y')...
1060
1061 \tr{x} is actually absent, since it is only passed round the loop, never
1062 used.  But who cares about missing that?
1063
1064 NB: despite only having a two-point domain, we may still have many
1065 iterations, because there are several variables involved at once.