fix haddock submodule pointer
[ghc-hetmet.git] / compiler / coreSyn / CoreFVs.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 Taken quite directly from the Peyton Jones/Lester paper.
6
7 \begin{code}
8 {-# OPTIONS -fno-warn-incomplete-patterns #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 -- | A module concerned with finding the free variables of an expression.
16 module CoreFVs (
17         -- * Free variables of expressions and binding groups
18         exprFreeVars,   -- CoreExpr   -> VarSet -- Find all locally-defined free Ids or tyvars
19         exprFreeIds,    -- CoreExpr   -> IdSet  -- Find all locally-defined free Ids
20         exprsFreeVars,  -- [CoreExpr] -> VarSet
21         bindFreeVars,   -- CoreBind   -> VarSet
22
23         -- * Selective free variables of expressions
24         InterestingVarFun,
25         exprSomeFreeVars, exprsSomeFreeVars,
26
27         -- * Free variables of Rules, Vars and Ids
28         varTypeTyVars, varTypeTcTyVars, 
29         idUnfoldingVars, idFreeVars, idRuleAndUnfoldingVars,
30         idRuleVars, idRuleRhsVars, stableUnfoldingVars,
31         ruleRhsFreeVars, rulesFreeVars,
32         ruleLhsOrphNames, ruleLhsFreeIds, 
33         vectsFreeVars,
34
35         -- * Core syntax tree annotation with free variables
36         CoreExprWithFVs,        -- = AnnExpr Id VarSet
37         CoreBindWithFVs,        -- = AnnBind Id VarSet
38         freeVars,               -- CoreExpr -> CoreExprWithFVs
39         freeVarsOf              -- CoreExprWithFVs -> IdSet
40     ) where
41
42 #include "HsVersions.h"
43
44 import CoreSyn
45 import Id
46 import IdInfo
47 import NameSet
48 import UniqFM
49 import Name
50 import VarSet
51 import Var
52 import TcType
53 import Coercion
54 import Util
55 import BasicTypes( Activation )
56 import Outputable
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62 \section{Finding the free variables of an expression}
63 %*                                                                      *
64 %************************************************************************
65
66 This function simply finds the free variables of an expression.
67 So far as type variables are concerned, it only finds tyvars that are
68
69         * free in type arguments, 
70         * free in the type of a binder,
71
72 but not those that are free in the type of variable occurrence.
73
74 \begin{code}
75 -- | Find all locally-defined free Ids or type variables in an expression
76 exprFreeVars :: CoreExpr -> VarSet
77 exprFreeVars = exprSomeFreeVars isLocalVar
78
79 -- | Find all locally-defined free Ids in an expression
80 exprFreeIds :: CoreExpr -> IdSet        -- Find all locally-defined free Ids
81 exprFreeIds = exprSomeFreeVars isLocalId
82
83 -- | Find all locally-defined free Ids or type variables in several expressions
84 exprsFreeVars :: [CoreExpr] -> VarSet
85 exprsFreeVars = foldr (unionVarSet . exprFreeVars) emptyVarSet
86
87 -- | Find all locally defined free Ids in a binding group
88 bindFreeVars :: CoreBind -> VarSet
89 bindFreeVars (NonRec _ r) = exprFreeVars r
90 bindFreeVars (Rec prs)    = addBndrs (map fst prs) 
91                                      (foldr (union . rhs_fvs) noVars prs)
92                                      isLocalVar emptyVarSet
93
94 -- | Finds free variables in an expression selected by a predicate
95 exprSomeFreeVars :: InterestingVarFun   -- ^ Says which 'Var's are interesting
96                  -> CoreExpr
97                  -> VarSet
98 exprSomeFreeVars fv_cand e = expr_fvs e fv_cand emptyVarSet
99
100 -- | Finds free variables in several expressions selected by a predicate
101 exprsSomeFreeVars :: InterestingVarFun  -- Says which 'Var's are interesting
102                   -> [CoreExpr]
103                   -> VarSet
104 exprsSomeFreeVars fv_cand = foldr (unionVarSet . exprSomeFreeVars fv_cand) emptyVarSet
105
106 -- | Predicate on possible free variables: returns @True@ iff the variable is interesting
107 type InterestingVarFun = Var -> Bool
108 \end{code}
109
110
111 \begin{code}
112 type FV = InterestingVarFun 
113         -> VarSet               -- In scope
114         -> VarSet               -- Free vars
115
116 union :: FV -> FV -> FV
117 union fv1 fv2 fv_cand in_scope = fv1 fv_cand in_scope `unionVarSet` fv2 fv_cand in_scope
118
119 noVars :: FV
120 noVars _ _ = emptyVarSet
121
122 --      Comment about obselete code
123 -- We used to gather the free variables the RULES at a variable occurrence
124 -- with the following cryptic comment:
125 --     "At a variable occurrence, add in any free variables of its rule rhss
126 --     Curiously, we gather the Id's free *type* variables from its binding
127 --     site, but its free *rule-rhs* variables from its usage sites.  This
128 --     is a little weird.  The reason is that the former is more efficient,
129 --     but the latter is more fine grained, and a makes a difference when
130 --     a variable mentions itself one of its own rule RHSs"
131 -- Not only is this "weird", but it's also pretty bad because it can make
132 -- a function seem more recursive than it is.  Suppose
133 --      f  = ...g...
134 --      g  = ...
135 --         RULE g x = ...f...
136 -- Then f is not mentioned in its own RHS, and needn't be a loop breaker
137 -- (though g may be).  But if we collect the rule fvs from g's occurrence,
138 -- it looks as if f mentions itself.  (This bites in the eftInt/eftIntFB
139 -- code in GHC.Enum.)
140 -- 
141 -- Anyway, it seems plain wrong.  The RULE is like an extra RHS for the
142 -- function, so its free variables belong at the definition site.
143 --
144 -- Deleted code looked like
145 --     foldVarSet add_rule_var var_itself_set (idRuleVars var)
146 --     add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
147 --                          | otherwise                    = set
148 --      SLPJ Feb06
149
150 oneVar :: Id -> FV
151 oneVar var fv_cand in_scope
152   = ASSERT( isId var ) 
153     if keep_it fv_cand in_scope var 
154     then unitVarSet var
155     else emptyVarSet
156
157 someVars :: VarSet -> FV
158 someVars vars fv_cand in_scope
159   = filterVarSet (keep_it fv_cand in_scope) vars
160
161 keep_it :: InterestingVarFun -> VarSet -> Var -> Bool
162 keep_it fv_cand in_scope var
163   | var `elemVarSet` in_scope = False
164   | fv_cand var               = True
165   | otherwise                 = False
166
167
168 addBndr :: CoreBndr -> FV -> FV
169 addBndr bndr fv fv_cand in_scope
170   = someVars (varTypeTyVars bndr) fv_cand in_scope
171         -- Include type varibles in the binder's type
172         --      (not just Ids; coercion variables too!)
173     `unionVarSet`  fv fv_cand (in_scope `extendVarSet` bndr) 
174
175 addBndrs :: [CoreBndr] -> FV -> FV
176 addBndrs bndrs fv = foldr addBndr fv bndrs
177 \end{code}
178
179
180 \begin{code}
181 expr_fvs :: CoreExpr -> FV
182
183 expr_fvs (Type ty)       = someVars (tyVarsOfType ty)
184 expr_fvs (Coercion co)   = someVars (tyCoVarsOfCo co)
185 expr_fvs (Var var)       = oneVar var
186 expr_fvs (Lit _)         = noVars
187 expr_fvs (Note _ expr)   = expr_fvs expr
188 expr_fvs (App fun arg)   = expr_fvs fun `union` expr_fvs arg
189 expr_fvs (Lam bndr body) = addBndr bndr (expr_fvs body)
190 expr_fvs (Cast expr co)  = expr_fvs expr `union` someVars (tyCoVarsOfCo co)
191
192 expr_fvs (Case scrut bndr ty alts)
193   = expr_fvs scrut `union` someVars (tyVarsOfType ty) `union` addBndr bndr  
194       (foldr (union . alt_fvs) noVars alts)
195   where
196     alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
197
198 expr_fvs (Let (NonRec bndr rhs) body)
199   = rhs_fvs (bndr, rhs) `union` addBndr bndr (expr_fvs body)
200
201 expr_fvs (Let (Rec pairs) body)
202   = addBndrs (map fst pairs) 
203              (foldr (union . rhs_fvs) (expr_fvs body) pairs)
204
205 ---------
206 rhs_fvs :: (Id,CoreExpr) -> FV
207 rhs_fvs (bndr, rhs) = expr_fvs rhs `union` 
208                       someVars (bndrRuleAndUnfoldingVars bndr)
209         -- Treat any RULES as extra RHSs of the binding
210
211 ---------
212 exprs_fvs :: [CoreExpr] -> FV
213 exprs_fvs exprs = foldr (union . expr_fvs) noVars exprs
214 \end{code}
215
216
217 %************************************************************************
218 %*                                                                      *
219 \section{Free names}
220 %*                                                                      *
221 %************************************************************************
222
223 \begin{code}
224 -- | ruleLhsOrphNames is used when deciding whether 
225 -- a rule is an orphan.  In particular, suppose that T is defined in this 
226 -- module; we want to avoid declaring that a rule like:
227 -- 
228 -- > fromIntegral T = fromIntegral_T
229 --
230 -- is an orphan. Of course it isn't, and declaring it an orphan would
231 -- make the whole module an orphan module, which is bad.
232 ruleLhsOrphNames :: CoreRule -> NameSet
233 ruleLhsOrphNames (BuiltinRule { ru_fn = fn }) = unitNameSet fn
234 ruleLhsOrphNames (Rule { ru_fn = fn, ru_args = tpl_args })
235   = addOneToNameSet (exprsOrphNames tpl_args) fn
236                 -- No need to delete bndrs, because
237                 -- exprsOrphNames finds only External names
238
239 -- | Finds the free /external/ names of an expression, notably
240 -- including the names of type constructors (which of course do not show
241 -- up in 'exprFreeVars').
242 exprOrphNames :: CoreExpr -> NameSet
243 -- There's no need to delete local binders, because they will all
244 -- be /internal/ names.
245 exprOrphNames e
246   = go e
247   where
248     go (Var v) 
249       | isExternalName n    = unitNameSet n
250       | otherwise           = emptyNameSet
251       where n = idName v
252     go (Lit _)              = emptyNameSet
253     go (Type ty)            = orphNamesOfType ty        -- Don't need free tyvars
254     go (Coercion co)        = orphNamesOfCo co
255     go (App e1 e2)          = go e1 `unionNameSets` go e2
256     go (Lam v e)            = go e `delFromNameSet` idName v
257     go (Note _ e)           = go e
258     go (Cast e co)          = go e `unionNameSets` orphNamesOfCo co
259     go (Let (NonRec _ r) e) = go e `unionNameSets` go r
260     go (Let (Rec prs) e)    = exprsOrphNames (map snd prs) `unionNameSets` go e
261     go (Case e _ ty as)     = go e `unionNameSets` orphNamesOfType ty
262                               `unionNameSets` unionManyNameSets (map go_alt as)
263
264     go_alt (_,_,r) = go r
265
266 -- | Finds the free /external/ names of several expressions: see 'exprOrphNames' for details
267 exprsOrphNames :: [CoreExpr] -> NameSet
268 exprsOrphNames es = foldr (unionNameSets . exprOrphNames) emptyNameSet es
269 \end{code}
270
271 %************************************************************************
272 %*                                                                      *
273 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278 -- | Those variables free in the right hand side of a rule
279 ruleRhsFreeVars :: CoreRule -> VarSet
280 ruleRhsFreeVars (BuiltinRule {}) = noFVs
281 ruleRhsFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs })
282   = delFromUFM fvs fn    -- Note [Rule free var hack]
283   where
284     fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
285
286 -- | Those variables free in the both the left right hand sides of a rule
287 ruleFreeVars :: CoreRule -> VarSet
288 ruleFreeVars (BuiltinRule {}) = noFVs
289 ruleFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs, ru_args = args })
290   = delFromUFM fvs fn   -- Note [Rule free var hack]
291   where
292     fvs = addBndrs bndrs (exprs_fvs (rhs:args)) isLocalVar emptyVarSet
293
294 idRuleRhsVars :: (Activation -> Bool) -> Id -> VarSet
295 -- Just the variables free on the *rhs* of a rule
296 idRuleRhsVars is_active id 
297   = foldr (unionVarSet . get_fvs) emptyVarSet (idCoreRules id)
298   where
299     get_fvs (Rule { ru_fn = fn, ru_bndrs = bndrs
300                   , ru_rhs = rhs, ru_act = act })
301       | is_active act
302             -- See Note [Finding rule RHS free vars] in OccAnal.lhs
303       = delFromUFM fvs fn        -- Note [Rule free var hack]
304       where
305         fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
306     get_fvs _ = noFVs
307
308 -- | Those variables free in the right hand side of several rules
309 rulesFreeVars :: [CoreRule] -> VarSet
310 rulesFreeVars rules = foldr (unionVarSet . ruleFreeVars) emptyVarSet rules
311
312 ruleLhsFreeIds :: CoreRule -> VarSet
313 -- ^ This finds all locally-defined free Ids on the left hand side of a rule
314 ruleLhsFreeIds (BuiltinRule {}) = noFVs
315 ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args })
316   = addBndrs bndrs (exprs_fvs args) isLocalId emptyVarSet
317 \end{code}
318
319
320 Note [Rule free var hack]
321 ~~~~~~~~~~~~~~~~~~~~~~~~~
322 Don't include the Id in its own rhs free-var set.
323 Otherwise the occurrence analyser makes bindings recursive
324 that shoudn't be.  E.g.
325         RULE:  f (f x y) z  ==>  f x (f y z)
326
327 Also since rule_fn is a Name, not a Var, we have to use the grungy delUFM.
328
329
330 \begin{code}
331 -- |Free variables of a vectorisation declaration
332 vectsFreeVars :: [CoreVect] -> VarSet
333 vectsFreeVars = foldr (unionVarSet . vectFreeVars) emptyVarSet
334   where
335     vectFreeVars (Vect   _ Nothing)    = noFVs
336     vectFreeVars (Vect   _ (Just rhs)) = expr_fvs rhs isLocalId emptyVarSet
337     vectFreeVars (NoVect _)            = noFVs
338 \end{code}
339
340
341 %************************************************************************
342 %*                                                                      *
343 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
344 %*                                                                      *
345 %************************************************************************
346
347 The free variable pass annotates every node in the expression with its
348 NON-GLOBAL free variables and type variables.
349
350 \begin{code}
351 -- | Every node in a binding group annotated with its 
352 -- (non-global) free variables, both Ids and TyVars
353 type CoreBindWithFVs = AnnBind Id VarSet
354 -- | Every node in an expression annotated with its 
355 -- (non-global) free variables, both Ids and TyVars
356 type CoreExprWithFVs = AnnExpr Id VarSet
357
358 freeVarsOf :: CoreExprWithFVs -> IdSet
359 -- ^ Inverse function to 'freeVars'
360 freeVarsOf (free_vars, _) = free_vars
361
362 noFVs :: VarSet
363 noFVs    = emptyVarSet
364
365 aFreeVar :: Var -> VarSet
366 aFreeVar = unitVarSet
367
368 unionFVs :: VarSet -> VarSet -> VarSet
369 unionFVs = unionVarSet
370
371 delBindersFV :: [Var] -> VarSet -> VarSet
372 delBindersFV bs fvs = foldr delBinderFV fvs bs
373
374 delBinderFV :: Var -> VarSet -> VarSet
375 -- This way round, so we can do it multiple times using foldr
376
377 -- (b `delBinderFV` s) removes the binder b from the free variable set s,
378 -- but *adds* to s
379 --
380 --      the free variables of b's type
381 --
382 -- This is really important for some lambdas:
383 --      In (\x::a -> x) the only mention of "a" is in the binder.
384 --
385 -- Also in
386 --      let x::a = b in ...
387 -- we should really note that "a" is free in this expression.
388 -- It'll be pinned inside the /\a by the binding for b, but
389 -- it seems cleaner to make sure that a is in the free-var set 
390 -- when it is mentioned.
391 --
392 -- This also shows up in recursive bindings.  Consider:
393 --      /\a -> letrec x::a = x in E
394 -- Now, there are no explicit free type variables in the RHS of x,
395 -- but nevertheless "a" is free in its definition.  So we add in
396 -- the free tyvars of the types of the binders, and include these in the
397 -- free vars of the group, attached to the top level of each RHS.
398 --
399 -- This actually happened in the defn of errorIO in IOBase.lhs:
400 --      errorIO (ST io) = case (errorIO# io) of
401 --                          _ -> bottom
402 --                        where
403 --                          bottom = bottom -- Never evaluated
404
405 delBinderFV b s = (s `delVarSet` b) `unionFVs` varTypeTyVars b
406         -- Include coercion variables too!
407
408 varTypeTyVars :: Var -> TyVarSet
409 -- Find the type variables free in the type of the variable
410 -- Remember, coercion variables can mention type variables...
411 varTypeTyVars var
412   | isLocalId var = tyVarsOfType (idType var)
413   | otherwise     = emptyVarSet -- Global Ids and non-coercion TyVars
414
415 varTypeTcTyVars :: Var -> TyVarSet
416 -- Find the type variables free in the type of the variable
417 -- Remember, coercion variables can mention type variables...
418 varTypeTcTyVars var
419   | isLocalId var = tcTyVarsOfType (idType var)
420   | otherwise     = emptyVarSet -- Global Ids and non-coercion TyVars
421
422 idFreeVars :: Id -> VarSet
423 -- Type variables, rule variables, and inline variables
424 idFreeVars id = ASSERT( isId id) 
425                 varTypeTyVars id `unionVarSet`
426                 idRuleAndUnfoldingVars id
427
428 bndrRuleAndUnfoldingVars ::Var -> VarSet
429 -- A 'let' can bind a type variable, and idRuleVars assumes 
430 -- it's seeing an Id. This function tests first.
431 bndrRuleAndUnfoldingVars v | isTyVar v = emptyVarSet
432                            | otherwise = idRuleAndUnfoldingVars v
433
434 idRuleAndUnfoldingVars :: Id -> VarSet
435 idRuleAndUnfoldingVars id = ASSERT( isId id) 
436                             idRuleVars id    `unionVarSet` 
437                             idUnfoldingVars id
438
439 idRuleVars ::Id -> VarSet  -- Does *not* include CoreUnfolding vars
440 idRuleVars id = ASSERT( isId id) specInfoFreeVars (idSpecialisation id)
441
442 idUnfoldingVars :: Id -> VarSet
443 -- Produce free vars for an unfolding, but NOT for an ordinary
444 -- (non-inline) unfolding, since it is a dup of the rhs
445 -- and we'll get exponential behaviour if we look at both unf and rhs!
446 -- But do look at the *real* unfolding, even for loop breakers, else
447 -- we might get out-of-scope variables
448 idUnfoldingVars id = stableUnfoldingVars (realIdUnfolding id)
449
450 stableUnfoldingVars :: Unfolding -> VarSet
451 stableUnfoldingVars (CoreUnfolding { uf_tmpl = rhs, uf_src = src })
452   | isStableSource src                       = exprFreeVars rhs
453 stableUnfoldingVars (DFunUnfolding _ _ args) = exprsFreeVars (dfunArgExprs args)
454 stableUnfoldingVars _                        = emptyVarSet
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460 \subsection{Free variables (and types)}
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 freeVars :: CoreExpr -> CoreExprWithFVs
466 -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node
467 freeVars (Var v)
468   = (fvs, AnnVar v)
469   where
470         -- ToDo: insert motivating example for why we *need*
471         -- to include the idSpecVars in the FV list.
472         --      Actually [June 98] I don't think it's necessary
473         -- fvs = fvs_v `unionVarSet` idSpecVars v
474
475     fvs | isLocalVar v = aFreeVar v
476         | otherwise    = noFVs
477
478 freeVars (Lit lit) = (noFVs, AnnLit lit)
479 freeVars (Lam b body)
480   = (b `delBinderFV` freeVarsOf body', AnnLam b body')
481   where
482     body' = freeVars body
483
484 freeVars (App fun arg)
485   = (freeVarsOf fun2 `unionFVs` freeVarsOf arg2, AnnApp fun2 arg2)
486   where
487     fun2 = freeVars fun
488     arg2 = freeVars arg
489
490 freeVars (Case scrut bndr ty alts)
491   = ((bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyVarsOfType ty,
492      AnnCase scrut2 bndr ty alts2)
493   where
494     scrut2 = freeVars scrut
495
496     (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
497     alts_fvs            = foldr1 unionFVs alts_fvs_s
498
499     fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
500                              (con, args, rhs2))
501                           where
502                              rhs2 = freeVars rhs
503
504 freeVars (Let (NonRec binder rhs) body)
505   = (freeVarsOf rhs2 
506        `unionFVs` body_fvs 
507        `unionFVs` bndrRuleAndUnfoldingVars binder,
508                 -- Remember any rules; cf rhs_fvs above
509      AnnLet (AnnNonRec binder rhs2) body2)
510   where
511     rhs2     = freeVars rhs
512     body2    = freeVars body
513     body_fvs = binder `delBinderFV` freeVarsOf body2
514
515 freeVars (Let (Rec binds) body)
516   = (delBindersFV binders all_fvs,
517      AnnLet (AnnRec (binders `zip` rhss2)) body2)
518   where
519     (binders, rhss) = unzip binds
520
521     rhss2     = map freeVars rhss
522     rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
523     all_fvs      = foldr (unionFVs . idRuleAndUnfoldingVars) rhs_body_fvs binders
524         -- The "delBinderFV" happens after adding the idSpecVars,
525         -- since the latter may add some of the binders as fvs
526
527     body2     = freeVars body
528     body_fvs  = freeVarsOf body2
529
530 freeVars (Cast expr co)
531   = (freeVarsOf expr2 `unionFVs` cfvs, AnnCast expr2 (cfvs, co))
532   where
533     expr2 = freeVars expr
534     cfvs  = tyCoVarsOfCo co
535
536 freeVars (Note other_note expr)
537   = (freeVarsOf expr2, AnnNote other_note expr2)
538   where
539     expr2 = freeVars expr
540
541 freeVars (Type ty) = (tyVarsOfType ty, AnnType ty)
542
543 freeVars (Coercion co) = (tyCoVarsOfCo co, AnnCoercion co)
544 \end{code}
545