[project @ 2001-06-25 14:36:04 by simonpj]
[ghc-hetmet.git] / ghc / compiler / stranal / SaAbsInt.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SaAbsInt]{Abstract interpreter for strictness analysis}
5
6 \begin{code}
7 module SaAbsInt (
8         findStrictness,
9         findDemand, findDemandAlts,
10         absEval,
11         widen,
12         fixpoint,
13         isBot
14     ) where
15
16 #include "HsVersions.h"
17
18 import CmdLineOpts      ( opt_AllStrict, opt_NumbersStrict )
19 import CoreSyn
20 import CoreUnfold       ( maybeUnfoldingTemplate )
21 import Id               ( Id, idType, idStrictness, idUnfolding, isDataConId_maybe )
22 import DataCon          ( dataConTyCon, splitProductType_maybe, dataConRepArgTys )
23 import IdInfo           ( StrictnessInfo(..) )
24 import Demand           ( Demand(..), wwPrim, wwStrict, wwUnpack, wwLazy,
25                           mkStrictnessInfo, isLazy
26                         )
27 import SaLib
28 import TyCon            ( isProductTyCon, isRecursiveTyCon )
29 import Type             ( splitTyConApp_maybe, 
30                           isUnLiftedType, Type )
31 import TyCon            ( tyConUnique )
32 import PrelInfo         ( numericTyKeys )
33 import Util             ( isIn, nOfThem, zipWithEqual )
34 import Outputable       
35 \end{code}
36
37 %************************************************************************
38 %*                                                                      *
39 \subsection[AbsVal-ops]{Operations on @AbsVals@}
40 %*                                                                      *
41 %************************************************************************
42
43 Least upper bound, greatest lower bound.
44
45 \begin{code}
46 lub, glb :: AbsVal -> AbsVal -> AbsVal
47
48 lub AbsBot val2   = val2        
49 lub val1   AbsBot = val1        
50
51 lub (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "lub" lub xs ys)
52
53 lub _             _           = AbsTop  -- Crude, but conservative
54                                         -- The crudity only shows up if there
55                                         -- are functions involved
56
57 -- Slightly funny glb; for absence analysis only;
58 -- AbsBot is the safe answer.
59 --
60 -- Using anyBot rather than just testing for AbsBot is important.
61 -- Consider:
62 --
63 --   f = \a b -> ...
64 --
65 --   g = \x y z -> case x of
66 --                   []     -> f x
67 --                   (p:ps) -> f p
68 --
69 -- Now, the abstract value of the branches of the case will be an
70 -- AbsFun, but when testing for z's absence we want to spot that it's
71 -- an AbsFun which can't possibly return AbsBot.  So when glb'ing we
72 -- mustn't be too keen to bale out and return AbsBot; the anyBot test
73 -- spots that (f x) can't possibly return AbsBot.
74
75 -- We have also tripped over the following interesting case:
76 --      case x of
77 --        []     -> \y -> 1
78 --        (p:ps) -> f
79 --
80 -- Now, suppose f is bound to AbsTop.  Does this expression mention z?
81 -- Obviously not.  But the case will take the glb of AbsTop (for f) and
82 -- an AbsFun (for \y->1). We should not bale out and give AbsBot, because
83 -- that would say that it *does* mention z (or anything else for that matter).
84 -- Nor can we always return AbsTop, because the AbsFun might be something
85 -- like (\y->z), which obviously does mention z. The point is that we're
86 -- glbing two functions, and AbsTop is not actually the top of the function
87 -- lattice.  It is more like (\xyz -> x|y|z); that is, AbsTop returns
88 -- poison iff any of its arguments do.
89
90 -- Deal with functions specially, because AbsTop isn't the
91 -- top of their domain.
92
93 glb v1 v2
94   | is_fun v1 || is_fun v2
95   = if not (anyBot v1) && not (anyBot v2)
96     then
97         AbsTop
98     else
99         AbsBot
100   where
101     is_fun (AbsFun _ _)       = True
102     is_fun (AbsApproxFun _ _) = True    -- Not used, but the glb works ok
103     is_fun other              = False
104
105 -- The non-functional cases are quite straightforward
106
107 glb (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "glb" glb xs ys)
108
109 glb AbsTop       v2           = v2
110 glb v1           AbsTop       = v1
111
112 glb _            _            = AbsBot          -- Be pessimistic
113 \end{code}
114
115 @isBot@ returns True if its argument is (a representation of) bottom.  The
116 ``representation'' part is because we need to detect the bottom {\em function}
117 too.  To detect the bottom function, bind its args to top, and see if it
118 returns bottom.
119
120 Used only in strictness analysis:
121 \begin{code}
122 isBot :: AbsVal -> Bool
123
124 isBot AbsBot = True
125 isBot other  = False    -- Functions aren't bottom any more
126 \end{code}
127
128 Used only in absence analysis:
129
130 \begin{code}
131 anyBot :: AbsVal -> Bool
132
133 anyBot AbsBot                  = True   -- poisoned!
134 anyBot AbsTop                  = False
135 anyBot (AbsProd vals)          = any anyBot vals
136 anyBot (AbsFun bndr_ty abs_fn) = anyBot (abs_fn AbsTop)
137 anyBot (AbsApproxFun _ val)    = anyBot val
138 \end{code}
139
140 @widen@ takes an @AbsVal@, $val$, and returns and @AbsVal@ which is
141 approximated by $val$.  Furthermore, the result has no @AbsFun@s in
142 it, so it can be compared for equality by @sameVal@.
143
144 \begin{code}
145 widen :: AnalysisKind -> AbsVal -> AbsVal
146
147 -- Widening is complicated by the fact that funtions are lifted
148 widen StrAnal the_fn@(AbsFun bndr_ty _)
149   = case widened_body of
150         AbsApproxFun ds val -> AbsApproxFun (d : ds) val
151                             where
152                                d = findRecDemand str_fn abs_fn bndr_ty
153                                str_fn val = isBot (foldl (absApply StrAnal) the_fn 
154                                                          (val : [AbsTop | d <- ds]))
155
156         other               -> AbsApproxFun [d] widened_body
157                             where
158                                d = findRecDemand str_fn abs_fn bndr_ty
159                                str_fn val = isBot (absApply StrAnal the_fn val)
160   where
161     widened_body = widen StrAnal (absApply StrAnal the_fn AbsTop)
162     abs_fn val   = False        -- Always says poison; so it looks as if
163                                 -- nothing is absent; safe
164
165 {-      OLD comment... 
166         This stuff is now instead handled neatly by the fact that AbsApproxFun 
167         contains an AbsVal inside it.   SLPJ Jan 97
168
169   | isBot abs_body = AbsBot
170     -- It's worth checking for a function which is unconditionally
171     -- bottom.  Consider
172     --
173     --  f x y = let g y = case x of ...
174     --          in (g ..) + (g ..)
175     --
176     -- Here, when we are considering strictness of f in x, we'll
177     -- evaluate the body of f with x bound to bottom.  The current
178     -- strategy is to bind g to its *widened* value; without the isBot
179     -- (...) test above, we'd bind g to an AbsApproxFun, and deliver
180     -- Top, not Bot as the value of f's rhs.  The test spots the
181     -- unconditional bottom-ness of g when x is bottom.  (Another
182     -- alternative here would be to bind g to its exact abstract
183     -- value, but that entails lots of potential re-computation, at
184     -- every application of g.)
185 -}
186
187 widen StrAnal (AbsProd vals) = AbsProd (map (widen StrAnal) vals)
188 widen StrAnal other_val      = other_val
189
190
191 widen AbsAnal the_fn@(AbsFun bndr_ty _)
192   | anyBot widened_body = AbsBot
193         -- In the absence-analysis case it's *essential* to check
194         -- that the function has no poison in its body.  If it does,
195         -- anywhere, then the whole function is poisonous.
196
197   | otherwise
198   = case widened_body of
199         AbsApproxFun ds val -> AbsApproxFun (d : ds) val
200                             where
201                                d = findRecDemand str_fn abs_fn bndr_ty
202                                abs_fn val = not (anyBot (foldl (absApply AbsAnal) the_fn 
203                                                                 (val : [AbsTop | d <- ds])))
204
205         other               -> AbsApproxFun [d] widened_body
206                             where
207                                d = findRecDemand str_fn abs_fn bndr_ty
208                                abs_fn val = not (anyBot (absApply AbsAnal the_fn val))
209   where
210     widened_body = widen AbsAnal (absApply AbsAnal the_fn AbsTop)
211     str_fn val   = True         -- Always says non-termination;
212                                 -- that'll make findRecDemand peer into the
213                                 -- structure of the value.
214
215 widen AbsAnal (AbsProd vals) = AbsProd (map (widen AbsAnal) vals)
216
217         -- It's desirable to do a good job of widening for product
218         -- values.  Consider
219         --
220         --      let p = (x,y)
221         --      in ...(case p of (x,y) -> x)...
222         --
223         -- Now, is y absent in this expression?  Currently the
224         -- analyser widens p before looking at p's scope, to avoid
225         -- lots of recomputation in the case where p is a function.
226         -- So if widening doesn't have a case for products, we'll
227         -- widen p to AbsBot (since when searching for absence in y we
228         -- bind y to poison ie AbsBot), and now we are lost.
229
230 widen AbsAnal other_val = other_val
231
232 -- WAS:   if anyBot val then AbsBot else AbsTop
233 -- Nowadays widen is doing a better job on functions for absence analysis.
234 \end{code}
235
236 @crudeAbsWiden@ is used just for absence analysis, and always
237 returns AbsTop or AbsBot, so it widens to a two-point domain
238
239 \begin{code}
240 crudeAbsWiden :: AbsVal -> AbsVal
241 crudeAbsWiden val = if anyBot val then AbsBot else AbsTop
242 \end{code}
243
244 @sameVal@ compares two abstract values for equality.  It can't deal with
245 @AbsFun@, but that should have been removed earlier in the day by @widen@.
246
247 \begin{code}
248 sameVal :: AbsVal -> AbsVal -> Bool     -- Can't handle AbsFun!
249
250 #ifdef DEBUG
251 sameVal (AbsFun _ _) _ = panic "sameVal: AbsFun: arg1"
252 sameVal _ (AbsFun _ _) = panic "sameVal: AbsFun: arg2"
253 #endif
254
255 sameVal AbsBot AbsBot = True
256 sameVal AbsBot other  = False   -- widen has reduced AbsFun bots to AbsBot
257
258 sameVal AbsTop AbsTop = True
259 sameVal AbsTop other  = False           -- Right?
260
261 sameVal (AbsProd vals1) (AbsProd vals2) = and (zipWithEqual "sameVal" sameVal vals1 vals2)
262 sameVal (AbsProd _)     AbsTop          = False
263 sameVal (AbsProd _)     AbsBot          = False
264
265 sameVal (AbsApproxFun str1 v1) (AbsApproxFun str2 v2) = str1 == str2 && sameVal v1 v2
266 sameVal (AbsApproxFun _ _)     AbsTop                 = False
267 sameVal (AbsApproxFun _ _)     AbsBot                 = False
268
269 sameVal val1 val2 = panic "sameVal: type mismatch or AbsFun encountered"
270 \end{code}
271
272
273 @evalStrictness@ compares a @Demand@ with an abstract value, returning
274 @True@ iff the abstract value is {\em less defined} than the demand.
275 (@True@ is the exciting answer; @False@ is always safe.)
276
277 \begin{code}
278 evalStrictness :: Demand
279                -> AbsVal
280                -> Bool          -- True iff the value is sure
281                                 -- to be less defined than the Demand
282
283 evalStrictness (WwLazy _) _   = False
284 evalStrictness WwStrict   val = isBot val
285 evalStrictness WwEnum     val = isBot val
286
287 evalStrictness (WwUnpack _ demand_info) val
288   = case val of
289       AbsTop       -> False
290       AbsBot       -> True
291       AbsProd vals -> or (zipWithEqual "evalStrictness" evalStrictness demand_info vals)
292       _            -> pprTrace "evalStrictness?" empty False
293
294 evalStrictness WwPrim val
295   = case val of
296       AbsTop -> False
297       AbsBot -> True    -- Can happen: consider f (g x), where g is a 
298                         -- recursive function returning an Int# that diverges
299
300       other  -> pprPanic "evalStrictness: WwPrim:" (ppr other)
301 \end{code}
302
303 For absence analysis, we're interested in whether "poison" in the
304 argument (ie a bottom therein) can propagate to the result of the
305 function call; that is, whether the specified demand can {\em
306 possibly} hit poison.
307
308 \begin{code}
309 evalAbsence (WwLazy True) _ = False     -- Can't possibly hit poison
310                                         -- with Absent demand
311
312 evalAbsence (WwUnpack _ demand_info) val
313   = case val of
314         AbsTop       -> False           -- No poison in here
315         AbsBot       -> True            -- Pure poison
316         AbsProd vals -> or (zipWithEqual "evalAbsence" evalAbsence demand_info vals)
317         _            -> panic "evalAbsence: other"
318
319 evalAbsence other val = anyBot val
320   -- The demand is conservative; even "Lazy" *might* evaluate the
321   -- argument arbitrarily so we have to look everywhere for poison
322 \end{code}
323
324 %************************************************************************
325 %*                                                                      *
326 \subsection[absEval]{Evaluate an expression in the abstract domain}
327 %*                                                                      *
328 %************************************************************************
329
330 \begin{code}
331 -- The isBottomingId stuf is now dealt with via the Id's strictness info
332 -- absId anal var env | isBottomingId var
333 --   = case anal of
334 --      StrAnal -> AbsBot       -- See discussion below
335 --      AbsAnal -> AbsTop       -- Just want to see if there's any poison in
336                                 -- error's arg
337
338 absId anal var env
339   = case (lookupAbsValEnv env var, 
340           isDataConId_maybe var, 
341           idStrictness var, 
342           maybeUnfoldingTemplate (idUnfolding var)) of
343
344         (Just abs_val, _, _, _) ->
345                         abs_val -- Bound in the environment
346
347         (_, Just data_con, _, _) | isProductTyCon tycon &&
348                                    not (isRecursiveTyCon tycon)
349                 ->      -- A product.  We get infinite loops if we don't
350                         -- check for recursive products!
351                         -- The strictness info on the constructor 
352                         -- isn't expressive enough to contain its abstract value
353                    productAbsVal (dataConRepArgTys data_con) []
354                 where
355                    tycon = dataConTyCon data_con
356
357         (_, _, NoStrictnessInfo, Just 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_ #-}
376                 -- --- 42,44 ----
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_ #-}
380
381
382         (_, _, strictness_info, _) ->
383                         -- Includes NoUnfolding
384                         -- Try the strictness info
385                         absValFromStrictness anal strictness_info
386
387 productAbsVal []                 rev_abs_args = AbsProd (reverse rev_abs_args)
388 productAbsVal (arg_ty : arg_tys) rev_abs_args = AbsFun arg_ty (\ abs_arg -> productAbsVal arg_tys (abs_arg : rev_abs_args))
389 \end{code}
390
391 \begin{code}
392 absEval :: AnalysisKind -> CoreExpr -> AbsValEnv -> AbsVal
393
394 absEval anal (Type ty) env = AbsTop
395 absEval anal (Var var) env = absId anal var env
396 \end{code}
397
398 Discussion about error (following/quoting Lennart): Any expression
399 'error e' is regarded as bottom (with HBC, with the -ffail-strict
400 flag, on with -O).
401
402 Regarding it as bottom gives much better strictness properties for
403 some functions.  E.g.
404
405         f [x] y = x+y
406         f (x:xs) y = f xs (x+y)
407 i.e.
408         f [] _ = error "no match"
409         f [x] y = x+y
410         f (x:xs) y = f xs (x+y)
411
412 is strict in y, which you really want.  But, it may lead to
413 transformations that turn a call to \tr{error} into non-termination.
414 (The odds of this happening aren't good.)
415
416 Things are a little different for absence analysis, because we want
417 to make sure that any poison (?????)
418
419 \begin{code}
420 absEval anal (Lit _) env = AbsTop
421         -- Literals terminate (strictness) and are not poison (absence)
422 \end{code}
423
424 \begin{code}
425 absEval anal (Lam bndr body) env
426   | isTyVar bndr = absEval anal body env        -- Type lambda
427   | otherwise    = AbsFun (idType bndr) abs_fn  -- Value lambda
428   where
429     abs_fn arg = absEval anal body (addOneToAbsValEnv env bndr arg)
430
431 absEval anal (App expr (Type ty)) env
432   = absEval anal expr env                       -- Type appplication
433 absEval anal (App f val_arg) env
434   = absApply anal (absEval anal f env)          -- Value applicationn
435                   (absEval anal val_arg env)
436 \end{code}
437
438 \begin{code}
439 absEval anal expr@(Case scrut case_bndr alts) env
440   = let
441         scrut_val  = absEval anal scrut env
442         alts_env   = addOneToAbsValEnv env case_bndr scrut_val
443     in
444     case (scrut_val, alts) of
445         (AbsBot, _) -> AbsBot
446
447         (AbsProd arg_vals, [(con, bndrs, rhs)])
448                 | con /= DEFAULT ->
449                 -- The scrutinee is a product value, so it must be of a single-constr
450                 -- type; so the constructor in this alternative must be the right one
451                 -- so we can go ahead and bind the constructor args to the components
452                 -- of the product value.
453             ASSERT(length arg_vals == length val_bndrs)
454             absEval anal rhs rhs_env
455           where
456             val_bndrs = filter isId bndrs
457             rhs_env   = growAbsValEnvList alts_env (val_bndrs `zip` arg_vals)
458
459         other -> absEvalAlts anal alts alts_env
460 \end{code}
461
462 For @Lets@ we widen the value we get.  This is nothing to
463 do with fixpointing.  The reason is so that we don't get an explosion
464 in the amount of computation.  For example, consider:
465 \begin{verbatim}
466       let
467         g a = case a of
468                 q1 -> ...
469                 q2 -> ...
470         f x = case x of
471                 p1 -> ...g r...
472                 p2 -> ...g s...
473       in
474         f e
475 \end{verbatim}
476 If we bind @f@ and @g@ to their exact abstract value, then we'll
477 ``execute'' one call to @f@ and {\em two} calls to @g@.  This can blow
478 up exponentially.  Widening cuts it off by making a fixed
479 approximation to @f@ and @g@, so that the bodies of @f@ and @g@ are
480 not evaluated again at all when they are called.
481
482 Of course, this can lose useful joint strictness, which is sad.  An
483 alternative approach would be to try with a certain amount of ``fuel''
484 and be prepared to bale out.
485
486 \begin{code}
487 absEval anal (Let (NonRec binder e1) e2) env
488   = let
489         new_env = addOneToAbsValEnv env binder (widen anal (absEval anal e1 env))
490     in
491         -- The binder of a NonRec should *not* be of unboxed type,
492         -- hence no need to strictly evaluate the Rhs.
493     absEval anal e2 new_env
494
495 absEval anal (Let (Rec pairs) body) env
496   = let
497         (binders,rhss) = unzip pairs
498         rhs_vals = cheapFixpoint anal binders rhss env  -- Returns widened values
499         new_env  = growAbsValEnvList env (binders `zip` rhs_vals)
500     in
501     absEval anal body new_env
502
503 absEval anal (Note note expr) env = absEval anal expr env
504 \end{code}
505
506 \begin{code}
507 absEvalAlts :: AnalysisKind -> [CoreAlt] -> AbsValEnv -> AbsVal
508 absEvalAlts anal alts env
509   = combine anal (map go alts)
510   where
511     combine StrAnal = foldr1 lub        -- Diverge only if all diverge
512     combine AbsAnal = foldr1 glb        -- Find any poison
513
514     go (con, bndrs, rhs)
515       = absEval anal rhs rhs_env
516       where
517         rhs_env = growAbsValEnvList env (filter isId bndrs `zip` repeat AbsTop)
518 \end{code}
519
520 %************************************************************************
521 %*                                                                      *
522 \subsection[absApply]{Apply an abstract function to an abstract argument}
523 %*                                                                      *
524 %************************************************************************
525
526 Easy ones first:
527
528 \begin{code}
529 absApply :: AnalysisKind -> AbsVal -> AbsVal -> AbsVal
530
531 absApply anal AbsBot arg = AbsBot
532   -- AbsBot represents the abstract bottom *function* too
533
534 absApply StrAnal AbsTop arg = AbsTop
535 absApply AbsAnal AbsTop arg = if anyBot arg
536                               then AbsBot
537                               else AbsTop
538         -- To be conservative, we have to assume that a function about
539         -- which we know nothing (AbsTop) might look at some part of
540         -- its argument
541 \end{code}
542
543 An @AbsFun@ with only one more argument needed---bind it and eval the
544 result.  A @Lam@ with two or more args: return another @AbsFun@ with
545 an augmented environment.
546
547 \begin{code}
548 absApply anal (AbsFun bndr_ty abs_fn) arg = abs_fn arg
549 \end{code}
550
551 \begin{code}
552 absApply StrAnal (AbsApproxFun (d:ds) val) arg
553   = case ds of 
554         []    -> val'
555         other -> AbsApproxFun ds val'   -- Result is non-bot if there are still args
556   where
557     val' | evalStrictness d arg = AbsBot
558          | otherwise            = val
559
560 absApply AbsAnal (AbsApproxFun (d:ds) val) arg
561   = if evalAbsence d arg
562     then AbsBot         -- Poison in arg means poison in the application
563     else case ds of
564                 []    -> val
565                 other -> AbsApproxFun ds val
566
567 #ifdef DEBUG
568 absApply anal f@(AbsProd _) arg 
569   = pprPanic ("absApply: Duff function: AbsProd." ++ show anal) ((ppr f) <+> (ppr arg))
570 #endif
571 \end{code}
572
573
574
575
576 %************************************************************************
577 %*                                                                      *
578 \subsection[findStrictness]{Determine some binders' strictness}
579 %*                                                                      *
580 %************************************************************************
581
582 \begin{code}
583 findStrictness :: Id
584                -> AbsVal                -- Abstract strictness value of function
585                -> AbsVal                -- Abstract absence value of function
586                -> StrictnessInfo        -- Resulting strictness annotation
587
588 findStrictness id (AbsApproxFun str_ds str_res) (AbsApproxFun abs_ds _)
589         -- You might think there's really no point in describing detailed
590         -- strictness for a divergent function; 
591         -- If it's fully applied we get bottom regardless of the
592         -- argument.  If it's not fully applied we don't get bottom.
593         -- Finally, we don't want to regard the args of a divergent function
594         -- as 'interesting' for inlining purposes (see Simplify.prepareArgs)
595         --
596         -- HOWEVER, if we make diverging functions appear lazy, they
597         -- don't get wrappers, and then we get dreadful reboxing.
598         -- See notes with WwLib.worthSplitting
599   = find_strictness id str_ds str_res abs_ds
600
601 findStrictness id str_val abs_val 
602   | isBot str_val = mkStrictnessInfo ([], True)
603   | otherwise     = NoStrictnessInfo
604
605 -- The list of absence demands passed to combineDemands 
606 -- can be shorter than the list of absence demands
607 --
608 --      lookup = \ dEq -> letrec {
609 --                           lookup = \ key ds -> ...lookup...
610 --                        }
611 --                        in lookup
612 -- Here the strictness value takes three args, but the absence value
613 -- takes only one, for reasons I don't quite understand (see cheapFixpoint)
614
615 find_strictness id orig_str_ds orig_str_res orig_abs_ds
616   = mkStrictnessInfo (go orig_str_ds orig_abs_ds, res_bot)
617   where
618     res_bot = isBot orig_str_res
619
620     go str_ds abs_ds = zipWith mk_dmd str_ds (abs_ds ++ repeat wwLazy)
621
622     mk_dmd str_dmd (WwLazy True)
623          = WARN( not (res_bot || isLazy str_dmd),
624                  ppr id <+> ppr orig_str_ds <+> ppr orig_abs_ds )
625                 -- If the arg isn't used we jolly well don't expect the function
626                 -- to be strict in it.  Unless the function diverges.
627            WwLazy True  -- Best of all
628
629     mk_dmd (WwUnpack u str_ds) 
630            (WwUnpack _ abs_ds) = WwUnpack u (go str_ds abs_ds)
631
632     mk_dmd str_dmd abs_dmd = str_dmd
633 \end{code}
634
635
636 \begin{code}
637 findDemand dmd str_env abs_env expr binder
638   = findRecDemand str_fn abs_fn (idType binder)
639   where
640     str_fn val = evalStrictness   dmd (absEval StrAnal expr (addOneToAbsValEnv str_env binder val))
641     abs_fn val = not (evalAbsence dmd (absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)))
642
643 findDemandAlts dmd str_env abs_env alts binder
644   = findRecDemand str_fn abs_fn (idType binder)
645   where
646     str_fn val = evalStrictness   dmd (absEvalAlts StrAnal alts (addOneToAbsValEnv str_env binder val))
647     abs_fn val = not (evalAbsence dmd (absEvalAlts AbsAnal alts (addOneToAbsValEnv abs_env binder val)))
648 \end{code}
649
650 @findRecDemand@ is where we finally convert strictness/absence info
651 into ``Demands'' which we can pin on Ids (etc.).
652
653 NOTE: What do we do if something is {\em both} strict and absent?
654 Should \tr{f x y z = error "foo"} says that \tr{f}'s arguments are all
655 strict (because of bottoming effect of \tr{error}) or all absent
656 (because they're not used)?
657
658 Well, for practical reasons, we prefer absence over strictness.  In
659 particular, it makes the ``default defaults'' for class methods (the
660 ones that say \tr{defm.foo dict = error "I don't exist"}) come out
661 nicely [saying ``the dict isn't used''], rather than saying it is
662 strict in every component of the dictionary [massive gratuitious
663 casing to take the dict apart].
664
665 But you could have examples where going for strictness would be better
666 than absence.  Consider:
667 \begin{verbatim}
668         let x = something big
669         in
670         f x y z + g x
671 \end{verbatim}
672
673 If \tr{x} is marked absent in \tr{f}, but not strict, and \tr{g} is
674 lazy, then the thunk for \tr{x} will be built.  If \tr{f} was strict,
675 then we'd let-to-case it:
676 \begin{verbatim}
677         case something big of
678           x -> f x y z + g x
679 \end{verbatim}
680 Ho hum.
681
682 \begin{code}
683 findRecDemand :: (AbsVal -> Bool)       -- True => function applied to this value yields Bot
684               -> (AbsVal -> Bool)       -- True => function applied to this value yields no poison
685               -> Type       -- The type of the argument
686               -> Demand
687
688 findRecDemand str_fn abs_fn ty
689   = if isUnLiftedType ty then -- It's a primitive type!
690        wwPrim
691
692     else if abs_fn AbsBot then -- It's absent
693        -- We prefer absence over strictness: see NOTE above.
694        WwLazy True
695
696     else if not (opt_AllStrict ||
697                  (opt_NumbersStrict && is_numeric_type ty) ||
698                  str_fn AbsBot) then
699         WwLazy False -- It's not strict and we're not pretending
700
701     else -- It's strict (or we're pretending it is)!
702
703        case splitProductType_maybe ty of
704
705          Nothing -> wwStrict    -- Could have a test for wwEnum, but
706                                 -- we don't exploit it yet, so don't bother
707
708          Just (tycon,_,data_con,cmpnt_tys)      -- Single constructor case
709            | isRecursiveTyCon tycon             -- Recursive data type; don't unpack
710            ->   wwStrict                        --      (this applies to newtypes too:
711                                                 --      e.g.  data Void = MkVoid Void)
712
713            |  null compt_strict_infos           -- A nullary data type
714            ->   wwStrict
715
716            | otherwise                          -- Some other data type
717            ->   wwUnpack compt_strict_infos
718
719            where
720               prod_len = length cmpnt_tys
721               compt_strict_infos
722                 = [ findRecDemand
723                          (\ cmpnt_val ->
724                                str_fn (mkMainlyTopProd prod_len i cmpnt_val)
725                          )
726                          (\ cmpnt_val ->
727                                abs_fn (mkMainlyTopProd prod_len i cmpnt_val)
728                          )
729                      cmpnt_ty
730                   | (cmpnt_ty, i) <- cmpnt_tys `zip` [1..] ]
731
732   where
733     is_numeric_type ty
734       = case (splitTyConApp_maybe ty) of -- NB: duplicates stuff done above
735           Nothing         -> False
736           Just (tycon, _) -> tyConUnique tycon `is_elem` numericTyKeys
737       where
738         is_elem = isIn "is_numeric_type"
739
740     -- mkMainlyTopProd: make an AbsProd that is all AbsTops ("n"-1 of
741     -- them) except for a given value in the "i"th position.
742
743     mkMainlyTopProd :: Int -> Int -> AbsVal -> AbsVal
744
745     mkMainlyTopProd n i val
746       = let
747             befores = nOfThem (i-1) AbsTop
748             afters  = nOfThem (n-i) AbsTop
749         in
750         AbsProd (befores ++ (val : afters))
751 \end{code}
752
753 %************************************************************************
754 %*                                                                      *
755 \subsection[fixpoint]{Fixpointer for the strictness analyser}
756 %*                                                                      *
757 %************************************************************************
758
759 The @fixpoint@ functions take a list of \tr{(binder, expr)} pairs, an
760 environment, and returns the abstract value of each binder.
761
762 The @cheapFixpoint@ function makes a conservative approximation,
763 by binding each of the variables to Top in their own right hand sides.
764 That allows us to make rapid progress, at the cost of a less-than-wonderful
765 approximation.
766
767 \begin{code}
768 cheapFixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
769
770 cheapFixpoint AbsAnal [id] [rhs] env
771   = [crudeAbsWiden (absEval AbsAnal rhs new_env)]
772   where
773     new_env = addOneToAbsValEnv env id AbsTop   -- Unsafe starting point!
774                     -- In the just-one-binding case, we guarantee to
775                     -- find a fixed point in just one iteration,
776                     -- because we are using only a two-point domain.
777                     -- This improves matters in cases like:
778                     --
779                     --  f x y = letrec g = ...g...
780                     --          in g x
781                     --
782                     -- Here, y isn't used at all, but if g is bound to
783                     -- AbsBot we simply get AbsBot as the next
784                     -- iteration too.
785
786 cheapFixpoint anal ids rhss env
787   = [widen anal (absEval anal rhs new_env) | rhs <- rhss]
788                 -- We do just one iteration, starting from a safe
789                 -- approximation.  This won't do a good job in situations
790                 -- like:
791                 --      \x -> letrec f = ...g...
792                 --                   g = ...f...x...
793                 --            in
794                 --            ...f...
795                 -- Here, f will end up bound to Top after one iteration,
796                 -- and hence we won't spot the strictness in x.
797                 -- (A second iteration would solve this.  ToDo: try the effect of
798                 --  really searching for a fixed point.)
799   where
800     new_env = growAbsValEnvList env [(id,safe_val) | id <- ids]
801
802     safe_val
803       = case anal of    -- The safe starting point
804           StrAnal -> AbsTop
805           AbsAnal -> AbsBot
806 \end{code}
807
808 \begin{code}
809 fixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
810
811 fixpoint anal [] _ env = []
812
813 fixpoint anal ids rhss env
814   = fix_loop initial_vals
815   where
816     initial_val id
817       = case anal of    -- The (unsafe) starting point
818           AbsAnal -> AbsTop
819           StrAnal -> AbsBot
820                 -- At one stage for StrAnal we said:
821                 --   if (returnsRealWorld (idType id))
822                 --   then AbsTop -- this is a massively horrible hack (SLPJ 95/05)
823                 -- but no one has the foggiest idea what this hack did,
824                 -- and returnsRealWorld was a stub that always returned False
825                 -- So this comment is all that is left of the hack!
826
827     initial_vals = [ initial_val id | id <- ids ]
828
829     fix_loop :: [AbsVal] -> [AbsVal]
830
831     fix_loop current_widened_vals
832       = let
833             new_env  = growAbsValEnvList env (ids `zip` current_widened_vals)
834             new_vals = [ absEval anal rhs new_env | rhs <- rhss ]
835             new_widened_vals = map (widen anal) new_vals
836         in
837         if (and (zipWith sameVal current_widened_vals new_widened_vals)) then
838             current_widened_vals
839
840             -- NB: I was too chicken to make that a zipWithEqual,
841             -- lest I jump into a black hole.  WDP 96/02
842
843             -- Return the widened values.  We might get a slightly
844             -- better value by returning new_vals (which we used to
845             -- do, see below), but alas that means that whenever the
846             -- function is called we have to re-execute it, which is
847             -- expensive.
848
849             -- OLD VERSION
850             -- new_vals
851             -- Return the un-widened values which may be a bit better
852             -- than the widened ones, and are guaranteed safe, since
853             -- they are one iteration beyond current_widened_vals,
854             -- which itself is a fixed point.
855         else
856             fix_loop new_widened_vals
857 \end{code}
858
859 For absence analysis, we make do with a very very simple approach:
860 look for convergence in a two-point domain.
861
862 We used to use just one iteration, starting with the variables bound
863 to @AbsBot@, which is safe.
864
865 Prior to that, we used one iteration starting from @AbsTop@ (which
866 isn't safe).  Why isn't @AbsTop@ safe?  Consider:
867 \begin{verbatim}
868         letrec
869           x = ...p..d...
870           d = (x,y)
871         in
872         ...
873 \end{verbatim}
874 Here, if p is @AbsBot@, then we'd better {\em not} end up with a ``fixed
875 point'' of @d@ being @(AbsTop, AbsTop)@!  An @AbsBot@ initial value is
876 safe because it gives poison more often than really necessary, and
877 thus may miss some absence, but will never claim absence when it ain't
878 so.
879
880 Anyway, one iteration starting with everything bound to @AbsBot@ give
881 bad results for
882
883         f = \ x -> ...f...
884
885 Here, f would always end up bound to @AbsBot@, which ain't very
886 clever, because then it would introduce poison whenever it was
887 applied.  Much better to start with f bound to @AbsTop@, and widen it
888 to @AbsBot@ if any poison shows up. In effect we look for convergence
889 in the two-point @AbsTop@/@AbsBot@ domain.
890
891 What we miss (compared with the cleverer strictness analysis) is
892 spotting that in this case
893
894         f = \ x y -> ...y...(f x y')...
895
896 \tr{x} is actually absent, since it is only passed round the loop, never
897 used.  But who cares about missing that?
898
899 NB: despite only having a two-point domain, we may still have many
900 iterations, because there are several variables involved at once.