1 \section{Update Avoidance Analyser} -*-haskell-literate-*-
3 (c) Simon Marlow, Andre Santos 1992-1993
4 (c) The AQUA Project, Glasgow University, 1995-1996
6 %-----------------------------------------------------------------------------
7 \subsection{Module Interface}
10 #include "HsVersions.h"
13 > module UpdAnal ( updateAnalyse ) where
15 > IMP_Ubiq(){-uitous-}
18 > import Util ( panic )
20 > updateAnalyse :: [StgBinding] -> [StgBinding] {- Exported -}
21 > updateAnalyse = panic "UpdAnal.updateAnalyse"
23 > {- LATER: to end of file:
24 > --import Type ( splitFunTy, splitSigmaTy, Class, TyVarTemplate,
30 > --import SrcLoc ( mkUnknownSrcLoc )
33 > --import Unique ( getBuiltinUniques )
36 %-----------------------------------------------------------------------------
37 \subsection{Reverse application}
39 This is used instead of lazy pattern bindings to avoid space leaks.
44 %-----------------------------------------------------------------------------
47 List of closure references
50 > x `notInRefs` y = not (x `elementOfUniqSet` y)
52 A closure value: environment of closures that are evaluated on entry,
53 a list of closures that are referenced from the result, and an
54 abstract value for the evaluated closure.
56 An IdEnv is used for the reference counts, as these environments are
57 combined often. A generic environment is used for the main environment
58 mapping closure names to values; as a common operation is extension of
59 this environment, this representation should be efficient.
61 > -- partain: funny synonyms to cope w/ the fact
62 > -- that IdEnvs know longer know what their keys are
63 > -- (94/05) ToDo: improve
64 > type IdEnvInt = IdEnv (Id, Int)
65 > type IdEnvClosure = IdEnv (Id, Closure)
67 > -- backward-compat functions
68 > null_IdEnv :: IdEnv (Id, a)
69 > null_IdEnv = nullIdEnv
71 > unit_IdEnv :: Id -> a -> IdEnv (Id, a)
72 > unit_IdEnv k v = unitIdEnv k (k, v)
74 > mk_IdEnv :: [(Id, a)] -> IdEnv (Id, a)
75 > mk_IdEnv pairs = mkIdEnv [ (k, (k,v)) | (k,v) <- pairs ]
77 > grow_IdEnv :: IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
78 > grow_IdEnv env1 env2 = growIdEnv env1 env2
80 > addOneTo_IdEnv :: IdEnv (Id, a) -> Id -> a -> IdEnv (Id, a)
81 > addOneTo_IdEnv env k v = addOneToIdEnv env k (k, v)
83 > combine_IdEnvs :: (a->a->a) -> IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
84 > combine_IdEnvs combiner env1 env2 = combineIdEnvs new_combiner env1 env2
86 > new_combiner (id, x) (_, y) = (id, combiner x y)
88 > dom_IdEnv :: IdEnv (Id, a) -> Refs
89 > dom_IdEnv env = mkUniqSet [ i | (i,_) <- rngIdEnv env ]
91 > lookup_IdEnv :: IdEnv (Id, a) -> Id -> Maybe a
92 > lookup_IdEnv env key = case lookupIdEnv env key of
94 > Just (_,a) -> Just a
95 > -- end backward compat stuff
97 > type Closure = (IdEnvInt, Refs, AbFun)
99 > type AbVal = IdEnvClosure -> Closure
100 > data AbFun = Fun (Closure -> Closure)
102 > -- partain: speeding-up stuff
104 > type CaseBoundVars = IdSet
105 > noCaseBound = emptyUniqSet
106 > isCaseBound = elementOfUniqSet
107 > x `notCaseBound` y = not (isCaseBound x y)
108 > moreCaseBound :: CaseBoundVars -> [Id] -> CaseBoundVars
109 > moreCaseBound old new = old `unionUniqSets` mkUniqSet new
113 %----------------------------------------------------------------------------
114 \subsection{Environment lookup}
116 If the requested value is not in the environment, we return an unknown
117 value. Lookup is designed to be partially applied to a variable, and
118 repeatedly applied to different environments after that.
122 > = const (case updateInfoMaybe (getIdUpdateInfo v) of
123 > Nothing -> unknownClosure
124 > Just spec -> convertUpdateSpec spec)
126 > = \p -> case lookup_IdEnv p v of
128 > Nothing -> unknownClosure
130 %-----------------------------------------------------------------------------
131 Represent a list of references as an ordered list.
133 > mkRefs :: [Id] -> Refs
137 > noRefs = emptyUniqSet
139 > elemRefs = elementOfUniqSet
141 > merge :: [Refs] -> Refs
142 > merge xs = foldr merge2 emptyUniqSet xs
144 > merge2 :: Refs -> Refs -> Refs
145 > merge2 = unionUniqSets
147 %-----------------------------------------------------------------------------
148 \subsection{Some non-interesting values}
150 bottom will be used for abstract values that are not functions.
151 Hopefully its value will never be required!
154 > bottom = panic "Internal: (Update Analyser) bottom"
156 noClosure is a value that is definitely not a function (i.e. primitive
157 values and constructor applications). unknownClosure is a value about
158 which we have no information at all. This should occur rarely, but
159 could happen when an id is imported and the exporting module was not
160 compiled with the update analyser.
162 > noClosure, unknownClosure :: Closure
163 > noClosure = (null_IdEnv, noRefs, bottom)
164 > unknownClosure = (null_IdEnv, noRefs, dont_know noRefs)
166 dont_know is a black hole: it is something we know nothing about.
167 Applying dont_know to anything will generate a new dont_know that simply
168 contains more buried references.
170 > dont_know :: Refs -> AbFun
172 > = Fun (\(c,b,f) -> let b'' = dom_IdEnv c `merge2` b `merge2` b'
173 > in (null_IdEnv, b'', dont_know b''))
175 %-----------------------------------------------------------------------------
177 > getrefs :: IdEnvClosure -> [AbVal] -> Refs -> Refs
178 > getrefs p vs rest = foldr merge2 rest (getrefs' (map ($ p) vs))
181 > getrefs' ((c,b,_):rs) = dom_IdEnv c : b : getrefs' rs
183 %-----------------------------------------------------------------------------
185 udData is used when we are putting a list of closure references into a
186 data structure, or something else that we know nothing about.
188 > udData :: [StgArg] -> CaseBoundVars -> AbVal
190 > = \p -> (null_IdEnv, getrefs p local_ids noRefs, bottom)
191 > where local_ids = [ lookup v | (StgVarArg v) <- vs, v `notCaseBound` cvs ]
193 %-----------------------------------------------------------------------------
194 \subsection{Analysing an atom}
196 > udAtom :: CaseBoundVars -> StgArg -> AbVal
197 > udAtom cvs (StgVarArg v)
198 > | v `isCaseBound` cvs = const unknownClosure
199 > | otherwise = lookup v
201 > udAtom cvs _ = const noClosure
203 %-----------------------------------------------------------------------------
204 \subsection{Analysing an STG expression}
206 > ud :: StgExpr -- Expression to be analysed
207 > -> CaseBoundVars -- List of case-bound vars
208 > -> IdEnvClosure -- Current environment
209 > -> (StgExpr, AbVal) -- (New expression, abstract value)
211 > ud e@(StgPrim _ vs _) cvs p = (e, udData vs cvs)
212 > ud e@(StgCon _ vs _) cvs p = (e, udData vs cvs)
213 > ud e@(StgSCC ty lab a) cvs p = ud a cvs p =: \(a', abval_a) ->
214 > (StgSCC ty lab a', abval_a)
216 Here is application. The first thing to do is analyse the head, and
217 get an abstract function. Multiple applications are performed by using
218 a foldl with the function doApp. Closures are actually passed to the
219 abstract function iff the atom is a local variable.
221 I've left the type signature for doApp in to make things a bit clearer.
223 > ud e@(StgApp a atoms lvs) cvs p
226 > abval_atoms = map (udAtom cvs) atoms
227 > abval_a = udAtom cvs a
229 > let doApp :: Closure -> AbVal -> Closure
230 > doApp (c, b, Fun f) abval_atom =
231 > abval_atom p =: \e@(_,_,_) ->
232 > f e =: \(c', b', f') ->
233 > (combine_IdEnvs (+) c' c, b', f')
234 > in foldl doApp (abval_a p) abval_atoms
236 > ud (StgCase expr lve lva uniq alts) cvs p
237 > = ud expr cvs p =: \(expr', abval_selector) ->
238 > udAlt alts p =: \(alts', abval_alts) ->
241 > abval_selector p =: \(c, b, abfun_selector) ->
242 > abval_alts p =: \(cs, bs, abfun_alts) ->
243 > let bs' = b `merge2` bs in
244 > (combine_IdEnvs (+) c cs, bs', dont_know bs')
246 > (StgCase expr' lve lva uniq alts', abval_case)
249 > udAlt :: StgCaseAlts
251 > -> (StgCaseAlts, AbVal)
253 > udAlt (StgAlgAlts ty [alt] StgNoDefault) p
254 > = udAlgAlt p alt =: \(alt', abval) ->
255 > (StgAlgAlts ty [alt'] StgNoDefault, abval)
256 > udAlt (StgAlgAlts ty [] def) p
257 > = udDef def p =: \(def', abval) ->
258 > (StgAlgAlts ty [] def', abval)
259 > udAlt (StgAlgAlts ty alts def) p
260 > = udManyAlts alts def udAlgAlt (StgAlgAlts ty) p
261 > udAlt (StgPrimAlts ty [alt] StgNoDefault) p
262 > = udPrimAlt p alt =: \(alt', abval) ->
263 > (StgPrimAlts ty [alt'] StgNoDefault, abval)
264 > udAlt (StgPrimAlts ty [] def) p
265 > = udDef def p =: \(def', abval) ->
266 > (StgPrimAlts ty [] def', abval)
267 > udAlt (StgPrimAlts ty alts def) p
268 > = udManyAlts alts def udPrimAlt (StgPrimAlts ty) p
271 > = ud e cvs p =: \(e', v) -> ((l, e'), v)
273 > udAlgAlt p (id, vs, use_mask, e)
274 > = ud e (moreCaseBound cvs vs) p =: \(e', v) -> ((id, vs, use_mask, e'), v)
276 > udDef :: StgCaseDefault
278 > -> (StgCaseDefault, AbVal)
280 > udDef StgNoDefault p
281 > = (StgNoDefault, \p -> (null_IdEnv, noRefs, dont_know noRefs))
282 > udDef (StgBindDefault v is_used expr) p
283 > = ud expr (moreCaseBound cvs [v]) p =: \(expr', abval) ->
284 > (StgBindDefault v is_used expr', abval)
286 > udManyAlts alts def udalt stgalts p
287 > = udDef def p =: \(def', abval_def) ->
288 > unzip (map (udalt p) alts) =: \(alts', abvals_alts) ->
291 > abval_def p =: \(cd, bd, _) ->
292 > unzip3 (map ($ p) abvals_alts) =: \(cs, bs, _) ->
293 > let bs' = merge (bd:bs) in
294 > (foldr (combine_IdEnvs max) cd cs, bs', dont_know bs')
295 > in (stgalts alts' def', abval_alts)
297 The heart of the analysis: here we decide whether to make a specific
298 closure updatable or not, based on the results of analysing the body.
300 > ud (StgLet binds body) cvs p
301 > = udBinding binds cvs p =: \(binds', vs, abval1, abval2) ->
302 > abval1 p =: \(cs, p') ->
303 > grow_IdEnv p p' =: \p ->
304 > ud body cvs p =: \(body', abval_body) ->
305 > abval_body p =: \(c, b, abfun) ->
306 > tag b (combine_IdEnvs (+) cs c) binds' =: \tagged_binds ->
309 > = abval2 p =: \(c1, p') ->
310 > abval_body (grow_IdEnv p p') =: \(c2, b, abfun) ->
311 > (combine_IdEnvs (+) c1 c2, b, abfun)
313 > (StgLet tagged_binds body', abval)
315 %-----------------------------------------------------------------------------
316 \subsection{Analysing bindings}
318 For recursive sets of bindings we perform one iteration of a fixed
319 point algorithm, using (dont_know fv) as a safe approximation to the
320 real fixed point, where fv are the (mappings in the environment of
321 the) free variables of the function.
323 We'll return two new environments, one with the new closures in and
324 one without. There's no point in carrying around closures when their
325 respective bindings have already been analysed.
327 We don't need to find anything out about closures with arguments,
328 constructor closures etc.
330 > udBinding :: StgBinding
335 > IdEnvClosure -> (IdEnvInt, IdEnvClosure),
336 > IdEnvClosure -> (IdEnvInt, IdEnvClosure))
338 > udBinding (StgNonRec v rhs) cvs p
339 > = udRhs rhs cvs p =: \(rhs', abval) ->
340 > abval p =: \(c, b, abfun) ->
342 > abval_rhs a = \p ->
343 > abval p =: \(c, b, abfun) ->
344 > (c, unit_IdEnv v (a, b, abfun))
346 > StgRhsClosure _ _ _ Updatable [] _ -> unit_IdEnv v 1
348 > in (StgNonRec v rhs', [v], abval_rhs a, abval_rhs null_IdEnv)
350 > udBinding (StgRec ve) cvs p
351 > = (StgRec ve', [], abval_rhs, abval_rhs)
353 > (vs, ve', abvals) = unzip3 (map udBind ve)
354 > fv = (map lookup . filter (`notCaseBound` cvs) . concat . map collectfv) ve
358 > p' = grow_IdEnv (mk_IdEnv (vs `zip` (repeat closure))) p
359 > closure = (null_IdEnv, fv', dont_know fv')
360 > fv' = getrefs p fv vs'
361 > (cs, ps) = unzip (doRec vs abvals)
364 > doRec (v:vs) (abval:as)
365 > = abval p' =: \(c,b,abfun) ->
366 > (c, (v,(null_IdEnv, b, abfun))) : doRec vs as
369 > (foldr (combine_IdEnvs (+)) null_IdEnv cs, mk_IdEnv ps)
372 > = udRhs rhs cvs p =: \(rhs', abval) ->
373 > (v,(v,rhs'), abval)
375 > collectfv (_, StgRhsClosure _ _ fv _ _ _) = fv
376 > collectfv (_, StgRhsCon _ con args) = [ v | (StgVarArg v) <- args ]
378 %-----------------------------------------------------------------------------
379 \subsection{Analysing Right-Hand Sides}
381 > udRhs e@(StgRhsCon _ _ vs) cvs p = (e, udData vs cvs)
383 > udRhs (StgRhsClosure cc bi fv u [] body) cvs p
384 > = ud body cvs p =: \(body', abval_body) ->
385 > (StgRhsClosure cc bi fv u [] body', abval_body)
387 Here is the code for closures with arguments. A closure has a number
388 of arguments, which correspond to a set of nested lambda expressions.
389 We build up the analysis using foldr with the function doLam to
390 analyse each lambda expression.
392 > udRhs (StgRhsClosure cc bi fv u args body) cvs p
393 > = ud body cvs p =: \(body', abval_body) ->
395 > fv' = map lookup (filter (`notCaseBound` cvs) fv)
397 > foldr doLam (\b -> abval_body) args (getrefs p fv' noRefs) p
399 > (StgRhsClosure cc bi fv u args body', abval_rhs)
402 > doLam :: Id -> (Refs -> AbVal) -> Refs -> AbVal
405 > Fun (\x@(c',b',_) ->
406 > let b'' = dom_IdEnv c' `merge2` b' `merge2` b in
407 > f b'' (addOneTo_IdEnv p i x)))
409 %-----------------------------------------------------------------------------
410 \subsection{Adjusting Update flags}
412 The closure is tagged single entry iff it is used at most once, it is
413 not referenced from inside a data structure or function, and it has no
414 arguments (closures with arguments are re-entrant).
416 > tag :: Refs -> IdEnvInt -> StgBinding -> StgBinding
418 > tag b c r@(StgNonRec v (StgRhsClosure cc bi fv Updatable [] body))
419 > = if (v `notInRefs` b) && (lookupc c v <= 1)
420 > then -- trace "One!" (
421 > StgNonRec v (StgRhsClosure cc bi fv SingleEntry [] body)
424 > tag b c other = other
426 > lookupc c v = case lookup_IdEnv c v of
430 %-----------------------------------------------------------------------------
431 \subsection{Top Level analysis}
433 Should we tag top level closures? This could have good implications
434 for CAFs (i.e. they could be made non-updateable if only used once,
435 thus preventing a space leak).
437 > updateAnalyse :: [StgBinding] -> [StgBinding] {- Exported -}
439 > = udProgram bs null_IdEnv
441 > udProgram :: [StgBinding] -> IdEnvClosure -> [StgBinding]
442 > udProgram [] p = []
444 > = udBinding d noCaseBound p =: \(d', vs, _, abval_bind) ->
445 > abval_bind p =: \(_, p') ->
446 > grow_IdEnv p p' =: \p'' ->
447 > attachUpdateInfoToBinds d' p'' =: \d'' ->
448 > d'' : udProgram ds p''
450 %-----------------------------------------------------------------------------
451 \subsection{Exporting Update Information}
453 Convert the exported representation of a function's update function
454 into a real Closure value.
456 > convertUpdateSpec :: UpdateSpec -> Closure
457 > convertUpdateSpec = mkClosure null_IdEnv noRefs noRefs
459 > mkClosure :: IdEnvInt -> Refs -> Refs -> UpdateSpec -> Closure
461 > mkClosure c b b' [] = (c, b', dont_know b')
462 > mkClosure c b b' (0 : ns) = (null_IdEnv, b, Fun (\ _ -> mkClosure c b b' ns))
463 > mkClosure c b b' (1 : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
465 > (combine_IdEnvs (+) c c')
466 > (dom_IdEnv c' `merge2` b'' `merge2` b)
469 > mkClosure c b b' (n : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
471 > (dom_IdEnv c' `merge2` b'' `merge2` b)
472 > (dom_IdEnv c' `merge2` b'' `merge2` b')
475 Convert a Closure into a representation that can be placed in a .hi file.
477 > mkUpdateSpec :: Id -> Closure -> UpdateSpec
478 > mkUpdateSpec v f = {- removeSuperfluous2s -} (map countUses ids)
480 > (c,b,_) = foldl doApp f ids
481 > ids = map mkid (getBuiltinUniques arity)
482 > mkid u = mkSysLocal SLIT("upd") u noType mkUnknownSrcLoc
483 > countUses u = if u `elemRefs` b then 2 else min (lookupc c u) 2
484 > noType = panic "UpdAnal: no type!"
486 > doApp (c,b,Fun f) i
487 > = f (unit_IdEnv i 1, noRefs, dont_know noRefs) =: \(c',b',f') ->
488 > (combine_IdEnvs (+) c' c, b', f')
490 > (_,dict_tys,tau_ty) = (splitSigmaTy . idType) v
491 > (reg_arg_tys, _) = splitFunTy tau_ty
492 > arity = length dict_tys + length reg_arg_tys
494 removeSuperfluous2s = reverse . dropWhile (> 1) . reverse
496 %-----------------------------------------------------------------------------
497 \subsection{Attaching the update information to top-level bindings}
499 This is so that the information can later be retrieved for printing
500 out in the .hi file. This is not an ideal solution, however it will
503 > attachUpdateInfoToBinds b p
505 > StgNonRec v rhs -> StgNonRec (attachOne v) rhs
506 > StgRec bs -> StgRec [ (attachOne v, rhs) | (v, rhs) <- bs ]
509 > | externallyVisibleId v
510 > = let c = lookup v p in
512 > (mkUpdateInfo (mkUpdateSpec v c))
516 %-----------------------------------------------------------------------------