2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[StrictAnal]{``Simple'' Mycroft-style strictness analyser}
6 The original version(s) of all strictness-analyser code (except the
7 Semantique analyser) was written by Andy Gill.
10 #ifndef OLD_STRICTNESS
11 module StrictAnal ( ) where
15 module StrictAnal ( saBinds ) where
17 #include "HsVersions.h"
19 import DynFlags ( DynFlags, DynFlag(..) )
21 import Id ( setIdStrictness, setInlinePragma,
22 idDemandInfo, setIdDemandInfo, isBottomingId,
25 import CoreLint ( showPass, endPass )
26 import ErrUtils ( dumpIfSet_dyn )
29 import Demand ( Demand, wwStrict, isStrict, isLazy )
30 import Util ( zipWith3Equal, stretchZipWith, compareLength )
31 import BasicTypes ( Activation( NeverActive ) )
36 %************************************************************************
38 \subsection[Thoughts]{Random thoughts}
40 %************************************************************************
42 A note about worker-wrappering. If we have
45 f = let v = <expensive>
48 and we deduce that f is strict, it is nevertheless NOT safe to worker-wapper to
50 f = \x -> case x of Int x# -> fw x#
51 fw = \x# -> let x = Int x#
56 because this obviously loses laziness, since now <expensive>
57 is done each time. Alas.
59 WATCH OUT! This can mean that something is unboxed only to be
60 boxed again. For example
64 Here g is strict, and *will* split into worker-wrapper. A call to
65 g, with the wrapper inlined will then be
67 case arg of Int a# -> gw a#
69 Now g calls f, which has no wrapper, so it has to box it.
71 gw = \a# -> f (Int a#)
76 %************************************************************************
78 \subsection[iface-StrictAnal]{Interface to the outside world}
80 %************************************************************************
82 @saBinds@ decorates bindings with strictness info. A later
83 worker-wrapper pass can use this info to create wrappers and
87 saBinds :: DynFlags -> [CoreBind] -> IO [CoreBind]
90 showPass dflags "Strictness analysis";
92 -- Mark each binder with its strictness
93 #ifndef OMIT_STRANAL_STATS
94 let { (binds_w_strictness, sa_stats) = saTopBinds binds nullSaStats };
95 dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "Strictness analysis statistics"
98 let { binds_w_strictness = saTopBindsBinds binds };
101 endPass dflags "Strictness analysis" Opt_D_dump_stranal
106 %************************************************************************
108 \subsection[saBinds]{Strictness analysis of bindings}
110 %************************************************************************
112 [Some of the documentation about types, etc., in \tr{SaLib} may be
113 helpful for understanding this module.]
115 @saTopBinds@ tags each binder in the program with its @Demand@.
116 That tells how each binder is {\em used}; if @Strict@, then the binder
117 is sure to be evaluated to HNF; if @NonStrict@ it may or may not be;
118 if @Absent@, then it certainly is not used. [DATED; ToDo: update]
120 (The above info is actually recorded for posterity in each binder's
121 IdInfo, notably its @DemandInfo@.)
123 We proceed by analysing the bindings top-to-bottom, building up an
124 environment which maps @Id@s to their abstract values (i.e., an
125 @AbsValEnv@ maps an @Id@ to its @AbsVal@).
128 saTopBinds :: [CoreBind] -> SaM [CoreBind] -- not exported
132 starting_abs_env = nullAbsValEnv
134 do_it starting_abs_env starting_abs_env binds
136 do_it _ _ [] = returnSa []
137 do_it senv aenv (b:bs)
138 = saTopBind senv aenv b `thenSa` \ (senv2, aenv2, new_b) ->
139 do_it senv2 aenv2 bs `thenSa` \ new_bs ->
140 returnSa (new_b : new_bs)
143 @saTopBind@ is only used for the top level. We don't add any demand
144 info to these ids because we can't work it out. In any case, it
145 doesn't do us any good to know whether top-level binders are sure to
146 be used; we can't turn top-level @let@s into @case@s.
149 saTopBind :: StrictEnv -> AbsenceEnv
151 -> SaM (StrictEnv, AbsenceEnv, CoreBind)
153 saTopBind str_env abs_env (NonRec binder rhs)
154 = saExpr minDemand str_env abs_env rhs `thenSa` \ new_rhs ->
156 str_rhs = absEval StrAnal rhs str_env
157 abs_rhs = absEval AbsAnal rhs abs_env
159 widened_str_rhs = widen StrAnal str_rhs
160 widened_abs_rhs = widen AbsAnal abs_rhs
161 -- The widening above is done for efficiency reasons.
162 -- See notes on Let case in SaAbsInt.lhs
165 = addStrictnessInfoToTopId
166 widened_str_rhs widened_abs_rhs
169 -- Augment environments with a mapping of the
170 -- binder to its abstract values, computed by absEval
171 new_str_env = addOneToAbsValEnv str_env binder widened_str_rhs
172 new_abs_env = addOneToAbsValEnv abs_env binder widened_abs_rhs
174 returnSa (new_str_env, new_abs_env, NonRec new_binder new_rhs)
176 saTopBind str_env abs_env (Rec pairs)
178 (binders,rhss) = unzip pairs
179 str_rhss = fixpoint StrAnal binders rhss str_env
180 abs_rhss = fixpoint AbsAnal binders rhss abs_env
181 -- fixpoint returns widened values
182 new_str_env = growAbsValEnvList str_env (binders `zip` str_rhss)
183 new_abs_env = growAbsValEnvList abs_env (binders `zip` abs_rhss)
184 new_binders = zipWith3Equal "saTopBind" addStrictnessInfoToTopId
185 str_rhss abs_rhss binders
187 mapSa (saExpr minDemand new_str_env new_abs_env) rhss `thenSa` \ new_rhss ->
189 new_pairs = new_binders `zip` new_rhss
191 returnSa (new_str_env, new_abs_env, Rec new_pairs)
194 -- Top level divergent bindings are marked NOINLINE
195 -- This avoids fruitless inlining of top level error functions
196 addStrictnessInfoToTopId str_val abs_val bndr
197 = if isBottomingId new_id then
198 new_id `setInlinePragma` NeverActive
202 new_id = addStrictnessInfoToId str_val abs_val bndr
205 %************************************************************************
207 \subsection[saExpr]{Strictness analysis of an expression}
209 %************************************************************************
211 @saExpr@ computes the strictness of an expression within a given
215 saExpr :: Demand -> StrictEnv -> AbsenceEnv -> CoreExpr -> SaM CoreExpr
216 -- The demand is the least demand we expect on the
217 -- expression. WwStrict is the least, because we're only
218 -- interested in the expression at all if it's being evaluated,
219 -- but the demand may be more. E.g.
221 -- where f has strictness u(LL), will evaluate E with demand u(LL)
224 minDemands = repeat minDemand
226 -- When we find an application, do the arguments
227 -- with demands gotten from the function
228 saApp str_env abs_env (fun, args)
229 = sequenceSa sa_args `thenSa` \ args' ->
230 saExpr minDemand str_env abs_env fun `thenSa` \ fun' ->
231 returnSa (mkApps fun' args')
233 arg_dmds = case fun of
234 Var var -> case lookupAbsValEnv str_env var of
235 Just (AbsApproxFun ds _)
236 | compareLength ds args /= LT
237 -- 'ds' is at least as long as 'args'.
242 sa_args = stretchZipWith isTypeArg (error "saApp:dmd")
244 -- The arg_dmds are for value args only, we need to skip
245 -- over the type args when pairing up with the demands
246 -- Hence the stretchZipWith
248 sa_arg arg dmd = saExpr dmd' str_env abs_env arg
250 -- Bring arg demand up to minDemand
251 dmd' | isLazy dmd = minDemand
254 saExpr _ _ _ e@(Var _) = returnSa e
255 saExpr _ _ _ e@(Lit _) = returnSa e
256 saExpr _ _ _ e@(Type _) = returnSa e
258 saExpr dmd str_env abs_env (Lam bndr body)
259 = -- Don't bother to set the demand-info on a lambda binder
260 -- We do that only for let(rec)-bound functions
261 saExpr minDemand str_env abs_env body `thenSa` \ new_body ->
262 returnSa (Lam bndr new_body)
264 saExpr dmd str_env abs_env e@(App fun arg)
265 = saApp str_env abs_env (collectArgs e)
267 saExpr dmd str_env abs_env (Note note expr)
268 = saExpr dmd str_env abs_env expr `thenSa` \ new_expr ->
269 returnSa (Note note new_expr)
271 saExpr dmd str_env abs_env (Case expr case_bndr alts)
272 = saExpr minDemand str_env abs_env expr `thenSa` \ new_expr ->
273 mapSa sa_alt alts `thenSa` \ new_alts ->
275 new_case_bndr = addDemandInfoToCaseBndr dmd str_env abs_env alts case_bndr
277 returnSa (Case new_expr new_case_bndr new_alts)
279 sa_alt (con, binders, rhs)
280 = saExpr dmd str_env abs_env rhs `thenSa` \ new_rhs ->
282 new_binders = map add_demand_info binders
283 add_demand_info bndr | isTyVar bndr = bndr
284 | otherwise = addDemandInfoToId dmd str_env abs_env rhs bndr
286 tickCases new_binders `thenSa_` -- stats
287 returnSa (con, new_binders, new_rhs)
289 saExpr dmd str_env abs_env (Let (NonRec binder rhs) body)
290 = -- Analyse the RHS in the environment at hand
292 -- Find the demand on the RHS
293 rhs_dmd = findDemand dmd str_env abs_env body binder
295 -- Bind this binder to the abstract value of the RHS; analyse
296 -- the body of the `let' in the extended environment.
297 str_rhs_val = absEval StrAnal rhs str_env
298 abs_rhs_val = absEval AbsAnal rhs abs_env
300 widened_str_rhs = widen StrAnal str_rhs_val
301 widened_abs_rhs = widen AbsAnal abs_rhs_val
302 -- The widening above is done for efficiency reasons.
303 -- See notes on Let case in SaAbsInt.lhs
305 new_str_env = addOneToAbsValEnv str_env binder widened_str_rhs
306 new_abs_env = addOneToAbsValEnv abs_env binder widened_abs_rhs
308 -- Now determine the strictness of this binder; use that info
309 -- to record DemandInfo/StrictnessInfo in the binder.
310 new_binder = addStrictnessInfoToId
311 widened_str_rhs widened_abs_rhs
312 (binder `setIdDemandInfo` rhs_dmd)
314 tickLet new_binder `thenSa_` -- stats
315 saExpr rhs_dmd str_env abs_env rhs `thenSa` \ new_rhs ->
316 saExpr dmd new_str_env new_abs_env body `thenSa` \ new_body ->
317 returnSa (Let (NonRec new_binder new_rhs) new_body)
319 saExpr dmd str_env abs_env (Let (Rec pairs) body)
321 (binders,rhss) = unzip pairs
322 str_vals = fixpoint StrAnal binders rhss str_env
323 abs_vals = fixpoint AbsAnal binders rhss abs_env
324 -- fixpoint returns widened values
325 new_str_env = growAbsValEnvList str_env (binders `zip` str_vals)
326 new_abs_env = growAbsValEnvList abs_env (binders `zip` abs_vals)
328 saExpr dmd new_str_env new_abs_env body `thenSa` \ new_body ->
329 mapSa (saExpr minDemand new_str_env new_abs_env) rhss `thenSa` \ new_rhss ->
331 -- DON'T add demand info in a Rec!
332 -- a) it's useless: we can't do let-to-case
333 -- b) it's incorrect. Consider
334 -- letrec x = ...y...
337 -- When we ask whether y is demanded we'll bind y to bottom and
338 -- evaluate the body of the letrec. But that will result in our
339 -- deciding that y is absent, which is plain wrong!
340 -- It's much easier simply not to do this.
342 improved_binders = zipWith3Equal "saExpr" addStrictnessInfoToId
343 str_vals abs_vals binders
345 new_pairs = improved_binders `zip` new_rhss
347 returnSa (Let (Rec new_pairs) new_body)
351 %************************************************************************
353 \subsection[computeInfos]{Add computed info to binders}
355 %************************************************************************
357 Important note (Sept 93). @addStrictnessInfoToId@ is used only for
358 let(rec) bound variables, and is use to attach the strictness (not
359 demand) info to the binder. We are careful to restrict this
360 strictness info to the lambda-bound arguments which are actually
361 visible, at the top level, lest we accidentally lose laziness by
362 eagerly looking for an "extra" argument. So we "dig for lambdas" in a
363 rather syntactic way.
365 A better idea might be to have some kind of arity analysis to
366 tell how many args could safely be grabbed.
369 addStrictnessInfoToId
370 :: AbsVal -- Abstract strictness value
371 -> AbsVal -- Ditto absence
373 -> Id -- Augmented with strictness
375 addStrictnessInfoToId str_val abs_val binder
376 = binder `setIdStrictness` findStrictness binder str_val abs_val
380 addDemandInfoToId :: Demand -> StrictEnv -> AbsenceEnv
381 -> CoreExpr -- The scope of the id
383 -> Id -- Id augmented with Demand info
385 addDemandInfoToId dmd str_env abs_env expr binder
386 = binder `setIdDemandInfo` (findDemand dmd str_env abs_env expr binder)
388 addDemandInfoToCaseBndr dmd str_env abs_env alts binder
389 = binder `setIdDemandInfo` (findDemandAlts dmd str_env abs_env alts binder)
392 %************************************************************************
394 \subsection{Monad used herein for stats}
396 %************************************************************************
400 = SaStats FastInt FastInt -- total/marked-demanded lambda-bound
401 FastInt FastInt -- total/marked-demanded case-bound
402 FastInt FastInt -- total/marked-demanded let-bound
403 -- (excl. top-level; excl. letrecs)
405 nullSaStats = SaStats (_ILIT 0) (_ILIT 0) (_ILIT 0) (_ILIT 0) (_ILIT 0) (_ILIT 0)
407 thenSa :: SaM a -> (a -> SaM b) -> SaM b
408 thenSa_ :: SaM a -> SaM b -> SaM b
409 returnSa :: a -> SaM a
411 {-# INLINE thenSa #-}
412 {-# INLINE thenSa_ #-}
413 {-# INLINE returnSa #-}
415 tickLambda :: Id -> SaM ()
416 tickCases :: [CoreBndr] -> SaM ()
417 tickLet :: Id -> SaM ()
419 #ifndef OMIT_STRANAL_STATS
420 type SaM a = SaStats -> (a, SaStats)
422 thenSa expr cont stats
423 = case (expr stats) of { (result, stats1) ->
426 thenSa_ expr cont stats
427 = case (expr stats) of { (_, stats1) ->
430 returnSa x stats = (x, stats)
432 tickLambda var (SaStats tlam dlam tc dc tlet dlet)
433 = case (tick_demanded var (0,0)) of { (totB, demandedB) ->
434 let tot = iUnbox totB ; demanded = iUnbox demandedB
436 ((), SaStats (tlam +# tot) (dlam +# demanded) tc dc tlet dlet) }
438 tickCases vars (SaStats tlam dlam tc dc tlet dlet)
439 = case (foldr tick_demanded (0,0) vars) of { (totB, demandedB) ->
440 let tot = iUnbox totB ; demanded = iUnbox demandedB
442 ((), SaStats tlam dlam (tc +# tot) (dc +# demanded) tlet dlet) }
444 tickLet var (SaStats tlam dlam tc dc tlet dlet)
445 = case (tick_demanded var (0,0)) of { (totB, demandedB) ->
446 let tot = iUnbox totB ; demanded = iUnbox demandedB
448 ((), SaStats tlam dlam tc dc (tlet +# tot) (dlet +# demanded)) }
450 tick_demanded var (tot, demanded)
451 | isTyVar var = (tot, demanded)
454 if (isStrict (idDemandInfo var))
458 pp_stats (SaStats tlam dlam tc dc tlet dlet)
459 = hcat [ptext SLIT("Lambda vars: "), int (iBox dlam), char '/', int (iBox tlam),
460 ptext SLIT("; Case vars: "), int (iBox dc), char '/', int (iBox tc),
461 ptext SLIT("; Let vars: "), int (iBox dlet), char '/', int (iBox tlet)
464 #else /* OMIT_STRANAL_STATS */
468 thenSa expr cont = cont expr
470 thenSa_ expr cont = cont
474 tickLambda var = panic "OMIT_STRANAL_STATS: tickLambda"
475 tickCases vars = panic "OMIT_STRANAL_STATS: tickCases"
476 tickLet var = panic "OMIT_STRANAL_STATS: tickLet"
478 #endif /* OMIT_STRANAL_STATS */
480 mapSa :: (a -> SaM b) -> [a] -> SaM [b]
482 mapSa f [] = returnSa []
483 mapSa f (x:xs) = f x `thenSa` \ r ->
484 mapSa f xs `thenSa` \ rs ->
487 sequenceSa :: [SaM a] -> SaM [a]
488 sequenceSa [] = returnSa []
489 sequenceSa (m:ms) = m `thenSa` \ r ->
490 sequenceSa ms `thenSa` \ rs ->
493 #endif /* OLD_STRICTNESS */