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-}
17 > import Prelude hiding ( lookup )
20 > import Id ( SYN_IE(IdEnv), growIdEnv, addOneToIdEnv, combineIdEnvs, nullIdEnv,
21 > unitIdEnv, mkIdEnv, rngIdEnv, lookupIdEnv,
23 > getIdUpdateInfo, addIdUpdateInfo, mkSysLocal, idType, isImportedId,
24 > externallyVisibleId,
27 > import IdInfo ( UpdateInfo, SYN_IE(UpdateSpec), mkUpdateInfo, updateInfoMaybe )
28 > import Type ( splitFunTy, splitSigmaTy )
30 > import Unique ( getBuiltinUniques )
31 > import SrcLoc ( noSrcLoc )
32 > import Util ( panic )
35 %-----------------------------------------------------------------------------
36 \subsection{Reverse application}
38 This is used instead of lazy pattern bindings to avoid space leaks.
43 %-----------------------------------------------------------------------------
46 List of closure references
49 > x `notInRefs` y = not (x `elementOfUniqSet` y)
51 A closure value: environment of closures that are evaluated on entry,
52 a list of closures that are referenced from the result, and an
53 abstract value for the evaluated closure.
55 An IdEnv is used for the reference counts, as these environments are
56 combined often. A generic environment is used for the main environment
57 mapping closure names to values; as a common operation is extension of
58 this environment, this representation should be efficient.
60 > -- partain: funny synonyms to cope w/ the fact
61 > -- that IdEnvs know longer know what their keys are
62 > -- (94/05) ToDo: improve
63 > type IdEnvInt = IdEnv (Id, Int)
64 > type IdEnvClosure = IdEnv (Id, Closure)
66 > -- backward-compat functions
67 > null_IdEnv :: IdEnv (Id, a)
68 > null_IdEnv = nullIdEnv
70 > unit_IdEnv :: Id -> a -> IdEnv (Id, a)
71 > unit_IdEnv k v = unitIdEnv k (k, v)
73 > mk_IdEnv :: [(Id, a)] -> IdEnv (Id, a)
74 > mk_IdEnv pairs = mkIdEnv [ (k, (k,v)) | (k,v) <- pairs ]
76 > grow_IdEnv :: IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
77 > grow_IdEnv env1 env2 = growIdEnv env1 env2
79 > addOneTo_IdEnv :: IdEnv (Id, a) -> Id -> a -> IdEnv (Id, a)
80 > addOneTo_IdEnv env k v = addOneToIdEnv env k (k, v)
82 > combine_IdEnvs :: (a->a->a) -> IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
83 > combine_IdEnvs combiner env1 env2 = combineIdEnvs new_combiner env1 env2
85 > new_combiner (id, x) (_, y) = (id, combiner x y)
87 > dom_IdEnv :: IdEnv (Id, a) -> Refs
88 > dom_IdEnv env = mkUniqSet [ i | (i,_) <- rngIdEnv env ]
90 > lookup_IdEnv :: IdEnv (Id, a) -> Id -> Maybe a
91 > lookup_IdEnv env key = case lookupIdEnv env key of
93 > Just (_,a) -> Just a
94 > -- end backward compat stuff
96 > type Closure = (IdEnvInt, Refs, AbFun)
98 > type AbVal = IdEnvClosure -> Closure
99 > data AbFun = Fun (Closure -> Closure)
101 > -- partain: speeding-up stuff
103 > type CaseBoundVars = IdSet
104 > noCaseBound = emptyUniqSet
105 > isCaseBound = elementOfUniqSet
106 > x `notCaseBound` y = not (isCaseBound x y)
107 > moreCaseBound :: CaseBoundVars -> [Id] -> CaseBoundVars
108 > moreCaseBound old new = old `unionUniqSets` mkUniqSet new
112 %----------------------------------------------------------------------------
113 \subsection{Environment lookup}
115 If the requested value is not in the environment, we return an unknown
116 value. Lookup is designed to be partially applied to a variable, and
117 repeatedly applied to different environments after that.
121 > = const (case updateInfoMaybe (getIdUpdateInfo v) of
122 > Nothing -> unknownClosure
123 > Just spec -> convertUpdateSpec spec)
125 > = \p -> case lookup_IdEnv p v of
127 > Nothing -> unknownClosure
129 %-----------------------------------------------------------------------------
130 Represent a list of references as an ordered list.
132 > mkRefs :: [Id] -> Refs
136 > noRefs = emptyUniqSet
138 > elemRefs = elementOfUniqSet
140 > merge :: [Refs] -> Refs
141 > merge xs = foldr merge2 emptyUniqSet xs
143 > merge2 :: Refs -> Refs -> Refs
144 > merge2 = unionUniqSets
146 %-----------------------------------------------------------------------------
147 \subsection{Some non-interesting values}
149 bottom will be used for abstract values that are not functions.
150 Hopefully its value will never be required!
153 > bottom = panic "Internal: (Update Analyser) bottom"
155 noClosure is a value that is definitely not a function (i.e. primitive
156 values and constructor applications). unknownClosure is a value about
157 which we have no information at all. This should occur rarely, but
158 could happen when an id is imported and the exporting module was not
159 compiled with the update analyser.
161 > noClosure, unknownClosure :: Closure
162 > noClosure = (null_IdEnv, noRefs, bottom)
163 > unknownClosure = (null_IdEnv, noRefs, dont_know noRefs)
165 dont_know is a black hole: it is something we know nothing about.
166 Applying dont_know to anything will generate a new dont_know that simply
167 contains more buried references.
169 > dont_know :: Refs -> AbFun
171 > = Fun (\(c,b,f) -> let b'' = dom_IdEnv c `merge2` b `merge2` b'
172 > in (null_IdEnv, b'', dont_know b''))
174 %-----------------------------------------------------------------------------
176 > getrefs :: IdEnvClosure -> [AbVal] -> Refs -> Refs
177 > getrefs p vs rest = foldr merge2 rest (getrefs' (map ($ p) vs))
180 > getrefs' ((c,b,_):rs) = dom_IdEnv c : b : getrefs' rs
182 %-----------------------------------------------------------------------------
184 udData is used when we are putting a list of closure references into a
185 data structure, or something else that we know nothing about.
187 > udData :: [StgArg] -> CaseBoundVars -> AbVal
189 > = \p -> (null_IdEnv, getrefs p local_ids noRefs, bottom)
190 > where local_ids = [ lookup v | (StgVarArg v) <- vs, v `notCaseBound` cvs ]
192 %-----------------------------------------------------------------------------
193 \subsection{Analysing an atom}
195 > udAtom :: CaseBoundVars -> StgArg -> AbVal
196 > udAtom cvs (StgVarArg v)
197 > | v `isCaseBound` cvs = const unknownClosure
198 > | otherwise = lookup v
200 > udAtom cvs _ = const noClosure
202 %-----------------------------------------------------------------------------
203 \subsection{Analysing an STG expression}
205 > ud :: StgExpr -- Expression to be analysed
206 > -> CaseBoundVars -- List of case-bound vars
207 > -> IdEnvClosure -- Current environment
208 > -> (StgExpr, AbVal) -- (New expression, abstract value)
210 > ud e@(StgPrim _ vs _) cvs p = (e, udData vs cvs)
211 > ud e@(StgCon _ vs _) cvs p = (e, udData vs cvs)
212 > ud e@(StgSCC ty lab a) cvs p = ud a cvs p =: \(a', abval_a) ->
213 > (StgSCC ty lab a', abval_a)
215 Here is application. The first thing to do is analyse the head, and
216 get an abstract function. Multiple applications are performed by using
217 a foldl with the function doApp. Closures are actually passed to the
218 abstract function iff the atom is a local variable.
220 I've left the type signature for doApp in to make things a bit clearer.
222 > ud e@(StgApp a atoms lvs) cvs p
225 > abval_atoms = map (udAtom cvs) atoms
226 > abval_a = udAtom cvs a
228 > let doApp :: Closure -> AbVal -> Closure
229 > doApp (c, b, Fun f) abval_atom =
230 > abval_atom p =: \e@(_,_,_) ->
231 > f e =: \(c', b', f') ->
232 > (combine_IdEnvs (+) c' c, b', f')
233 > in foldl doApp (abval_a p) abval_atoms
235 > ud (StgCase expr lve lva uniq alts) cvs p
236 > = ud expr cvs p =: \(expr', abval_selector) ->
237 > udAlt alts p =: \(alts', abval_alts) ->
240 > abval_selector p =: \(c, b, abfun_selector) ->
241 > abval_alts p =: \(cs, bs, abfun_alts) ->
242 > let bs' = b `merge2` bs in
243 > (combine_IdEnvs (+) c cs, bs', dont_know bs')
245 > (StgCase expr' lve lva uniq alts', abval_case)
248 > udAlt :: StgCaseAlts
250 > -> (StgCaseAlts, AbVal)
252 > udAlt (StgAlgAlts ty [alt] StgNoDefault) p
253 > = udAlgAlt p alt =: \(alt', abval) ->
254 > (StgAlgAlts ty [alt'] StgNoDefault, abval)
255 > udAlt (StgAlgAlts ty [] def) p
256 > = udDef def p =: \(def', abval) ->
257 > (StgAlgAlts ty [] def', abval)
258 > udAlt (StgAlgAlts ty alts def) p
259 > = udManyAlts alts def udAlgAlt (StgAlgAlts ty) p
260 > udAlt (StgPrimAlts ty [alt] StgNoDefault) p
261 > = udPrimAlt p alt =: \(alt', abval) ->
262 > (StgPrimAlts ty [alt'] StgNoDefault, abval)
263 > udAlt (StgPrimAlts ty [] def) p
264 > = udDef def p =: \(def', abval) ->
265 > (StgPrimAlts ty [] def', abval)
266 > udAlt (StgPrimAlts ty alts def) p
267 > = udManyAlts alts def udPrimAlt (StgPrimAlts ty) p
270 > = ud e cvs p =: \(e', v) -> ((l, e'), v)
272 > udAlgAlt p (id, vs, use_mask, e)
273 > = ud e (moreCaseBound cvs vs) p =: \(e', v) -> ((id, vs, use_mask, e'), v)
275 > udDef :: StgCaseDefault
277 > -> (StgCaseDefault, AbVal)
279 > udDef StgNoDefault p
280 > = (StgNoDefault, \p -> (null_IdEnv, noRefs, dont_know noRefs))
281 > udDef (StgBindDefault v is_used expr) p
282 > = ud expr (moreCaseBound cvs [v]) p =: \(expr', abval) ->
283 > (StgBindDefault v is_used expr', abval)
285 > udManyAlts alts def udalt stgalts p
286 > = udDef def p =: \(def', abval_def) ->
287 > unzip (map (udalt p) alts) =: \(alts', abvals_alts) ->
290 > abval_def p =: \(cd, bd, _) ->
291 > unzip3 (map ($ p) abvals_alts) =: \(cs, bs, _) ->
292 > let bs' = merge (bd:bs) in
293 > (foldr (combine_IdEnvs max) cd cs, bs', dont_know bs')
294 > in (stgalts alts' def', abval_alts)
296 The heart of the analysis: here we decide whether to make a specific
297 closure updatable or not, based on the results of analysing the body.
299 > ud (StgLet binds body) cvs p
300 > = udBinding binds cvs p =: \(binds', vs, abval1, abval2) ->
301 > abval1 p =: \(cs, p') ->
302 > grow_IdEnv p p' =: \p ->
303 > ud body cvs p =: \(body', abval_body) ->
304 > abval_body p =: \(c, b, abfun) ->
305 > tag b (combine_IdEnvs (+) cs c) binds' =: \tagged_binds ->
308 > = abval2 p =: \(c1, p') ->
309 > abval_body (grow_IdEnv p p') =: \(c2, b, abfun) ->
310 > (combine_IdEnvs (+) c1 c2, b, abfun)
312 > (StgLet tagged_binds body', abval)
314 %-----------------------------------------------------------------------------
315 \subsection{Analysing bindings}
317 For recursive sets of bindings we perform one iteration of a fixed
318 point algorithm, using (dont_know fv) as a safe approximation to the
319 real fixed point, where fv are the (mappings in the environment of
320 the) free variables of the function.
322 We'll return two new environments, one with the new closures in and
323 one without. There's no point in carrying around closures when their
324 respective bindings have already been analysed.
326 We don't need to find anything out about closures with arguments,
327 constructor closures etc.
329 > udBinding :: StgBinding
334 > IdEnvClosure -> (IdEnvInt, IdEnvClosure),
335 > IdEnvClosure -> (IdEnvInt, IdEnvClosure))
337 > udBinding (StgNonRec v rhs) cvs p
338 > = udRhs rhs cvs p =: \(rhs', abval) ->
339 > abval p =: \(c, b, abfun) ->
341 > abval_rhs a = \p ->
342 > abval p =: \(c, b, abfun) ->
343 > (c, unit_IdEnv v (a, b, abfun))
345 > StgRhsClosure _ _ _ Updatable [] _ -> unit_IdEnv v 1
347 > in (StgNonRec v rhs', [v], abval_rhs a, abval_rhs null_IdEnv)
349 > udBinding (StgRec ve) cvs p
350 > = (StgRec ve', [], abval_rhs, abval_rhs)
352 > (vs, ve', abvals) = unzip3 (map udBind ve)
353 > fv = (map lookup . filter (`notCaseBound` cvs) . concat . map collectfv) ve
357 > p' = grow_IdEnv (mk_IdEnv (vs `zip` (repeat closure))) p
358 > closure = (null_IdEnv, fv', dont_know fv')
359 > fv' = getrefs p fv vs'
360 > (cs, ps) = unzip (doRec vs abvals)
363 > doRec (v:vs) (abval:as)
364 > = abval p' =: \(c,b,abfun) ->
365 > (c, (v,(null_IdEnv, b, abfun))) : doRec vs as
368 > (foldr (combine_IdEnvs (+)) null_IdEnv cs, mk_IdEnv ps)
371 > = udRhs rhs cvs p =: \(rhs', abval) ->
372 > (v,(v,rhs'), abval)
374 > collectfv (_, StgRhsClosure _ _ fv _ _ _) = fv
375 > collectfv (_, StgRhsCon _ con args) = [ v | (StgVarArg v) <- args ]
377 %-----------------------------------------------------------------------------
378 \subsection{Analysing Right-Hand Sides}
380 > udRhs e@(StgRhsCon _ _ vs) cvs p = (e, udData vs cvs)
382 > udRhs (StgRhsClosure cc bi fv u [] body) cvs p
383 > = ud body cvs p =: \(body', abval_body) ->
384 > (StgRhsClosure cc bi fv u [] body', abval_body)
386 Here is the code for closures with arguments. A closure has a number
387 of arguments, which correspond to a set of nested lambda expressions.
388 We build up the analysis using foldr with the function doLam to
389 analyse each lambda expression.
391 > udRhs (StgRhsClosure cc bi fv u args body) cvs p
392 > = ud body cvs p =: \(body', abval_body) ->
394 > fv' = map lookup (filter (`notCaseBound` cvs) fv)
396 > foldr doLam (\b -> abval_body) args (getrefs p fv' noRefs) p
398 > (StgRhsClosure cc bi fv u args body', abval_rhs)
401 > doLam :: Id -> (Refs -> AbVal) -> Refs -> AbVal
404 > Fun (\x@(c',b',_) ->
405 > let b'' = dom_IdEnv c' `merge2` b' `merge2` b in
406 > f b'' (addOneTo_IdEnv p i x)))
408 %-----------------------------------------------------------------------------
409 \subsection{Adjusting Update flags}
411 The closure is tagged single entry iff it is used at most once, it is
412 not referenced from inside a data structure or function, and it has no
413 arguments (closures with arguments are re-entrant).
415 > tag :: Refs -> IdEnvInt -> StgBinding -> StgBinding
417 > tag b c r@(StgNonRec v (StgRhsClosure cc bi fv Updatable [] body))
418 > = if (v `notInRefs` b) && (lookupc c v <= 1)
419 > then -- trace "One!" (
420 > StgNonRec v (StgRhsClosure cc bi fv SingleEntry [] body)
423 > tag b c other = other
425 > lookupc c v = case lookup_IdEnv c v of
429 %-----------------------------------------------------------------------------
430 \subsection{Top Level analysis}
432 Should we tag top level closures? This could have good implications
433 for CAFs (i.e. they could be made non-updateable if only used once,
434 thus preventing a space leak).
436 > updateAnalyse :: [StgBinding] -> [StgBinding] {- Exported -}
438 > = udProgram bs null_IdEnv
440 > udProgram :: [StgBinding] -> IdEnvClosure -> [StgBinding]
441 > udProgram [] p = []
443 > = udBinding d noCaseBound p =: \(d', vs, _, abval_bind) ->
444 > abval_bind p =: \(_, p') ->
445 > grow_IdEnv p p' =: \p'' ->
446 > attachUpdateInfoToBinds d' p'' =: \d'' ->
447 > d'' : udProgram ds p''
449 %-----------------------------------------------------------------------------
450 \subsection{Exporting Update Information}
452 Convert the exported representation of a function's update function
453 into a real Closure value.
455 > convertUpdateSpec :: UpdateSpec -> Closure
456 > convertUpdateSpec = mkClosure null_IdEnv noRefs noRefs
458 > mkClosure :: IdEnvInt -> Refs -> Refs -> UpdateSpec -> Closure
460 > mkClosure c b b' [] = (c, b', dont_know b')
461 > mkClosure c b b' (0 : ns) = (null_IdEnv, b, Fun (\ _ -> mkClosure c b b' ns))
462 > mkClosure c b b' (1 : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
464 > (combine_IdEnvs (+) c c')
465 > (dom_IdEnv c' `merge2` b'' `merge2` b)
468 > mkClosure c b b' (n : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
470 > (dom_IdEnv c' `merge2` b'' `merge2` b)
471 > (dom_IdEnv c' `merge2` b'' `merge2` b')
474 Convert a Closure into a representation that can be placed in a .hi file.
476 > mkUpdateSpec :: Id -> Closure -> UpdateSpec
477 > mkUpdateSpec v f = {- removeSuperfluous2s -} (map countUses ids)
479 > (c,b,_) = foldl doApp f ids
480 > ids = map mkid (getBuiltinUniques arity)
481 > mkid u = mkSysLocal SLIT("upd") u noType noSrcLoc
482 > countUses u = if u `elemRefs` b then 2 else min (lookupc c u) 2
483 > noType = panic "UpdAnal: no type!"
485 > doApp (c,b,Fun f) i
486 > = f (unit_IdEnv i 1, noRefs, dont_know noRefs) =: \(c',b',f') ->
487 > (combine_IdEnvs (+) c' c, b', f')
489 > (_,dict_tys,tau_ty) = (splitSigmaTy . idType) v
490 > (reg_arg_tys, _) = splitFunTy tau_ty
491 > arity = length dict_tys + length reg_arg_tys
493 removeSuperfluous2s = reverse . dropWhile (> 1) . reverse
495 %-----------------------------------------------------------------------------
496 \subsection{Attaching the update information to top-level bindings}
498 This is so that the information can later be retrieved for printing
499 out in the .hi file. This is not an ideal solution, however it will
502 > attachUpdateInfoToBinds b p
504 > StgNonRec v rhs -> StgNonRec (attachOne v) rhs
505 > StgRec bs -> StgRec [ (attachOne v, rhs) | (v, rhs) <- bs ]
508 > | externallyVisibleId v
509 > = let c = lookup v p in
511 > (mkUpdateInfo (mkUpdateSpec v c))
514 %-----------------------------------------------------------------------------