2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 Taken quite directly from the Peyton Jones/Lester paper.
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
15 -- | A module concerned with finding the free variables of an expression.
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
23 -- * Selective free variables of expressions
25 exprSomeFreeVars, exprsSomeFreeVars,
26 exprFreeNames, exprsFreeNames,
28 -- * Free variables of Rules, Vars and Ids
29 varTypeTyVars, varTypeTcTyVars,
30 idUnfoldingVars, idFreeVars, idRuleAndUnfoldingVars,
31 idRuleVars, idRuleRhsVars, stableUnfoldingVars,
32 ruleRhsFreeVars, rulesFreeVars,
33 ruleLhsFreeNames, ruleLhsFreeIds,
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
42 #include "HsVersions.h"
54 import BasicTypes( Activation )
59 %************************************************************************
61 \section{Finding the free variables of an expression}
63 %************************************************************************
65 This function simply finds the free variables of an expression.
66 So far as type variables are concerned, it only finds tyvars that are
68 * free in type arguments,
69 * free in the type of a binder,
71 but not those that are free in the type of variable occurrence.
74 -- | Find all locally-defined free Ids or type variables in an expression
75 exprFreeVars :: CoreExpr -> VarSet
76 exprFreeVars = exprSomeFreeVars isLocalVar
78 -- | Find all locally-defined free Ids in an expression
79 exprFreeIds :: CoreExpr -> IdSet -- Find all locally-defined free Ids
80 exprFreeIds = exprSomeFreeVars isLocalId
82 -- | Find all locally-defined free Ids or type variables in several expressions
83 exprsFreeVars :: [CoreExpr] -> VarSet
84 exprsFreeVars = foldr (unionVarSet . exprFreeVars) emptyVarSet
86 -- | Find all locally defined free Ids in a binding group
87 bindFreeVars :: CoreBind -> VarSet
88 bindFreeVars (NonRec _ r) = exprFreeVars r
89 bindFreeVars (Rec prs) = addBndrs (map fst prs)
90 (foldr (union . rhs_fvs) noVars prs)
91 isLocalVar emptyVarSet
93 -- | Finds free variables in an expression selected by a predicate
94 exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting
97 exprSomeFreeVars fv_cand e = expr_fvs e fv_cand emptyVarSet
99 -- | Finds free variables in several expressions selected by a predicate
100 exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting
103 exprsSomeFreeVars fv_cand = foldr (unionVarSet . exprSomeFreeVars fv_cand) emptyVarSet
105 -- | Predicate on possible free variables: returns @True@ iff the variable is interesting
106 type InterestingVarFun = Var -> Bool
111 type FV = InterestingVarFun
112 -> VarSet -- In scope
113 -> VarSet -- Free vars
115 union :: FV -> FV -> FV
116 union fv1 fv2 fv_cand in_scope = fv1 fv_cand in_scope `unionVarSet` fv2 fv_cand in_scope
119 noVars _ _ = emptyVarSet
121 -- Comment about obselete code
122 -- We used to gather the free variables the RULES at a variable occurrence
123 -- with the following cryptic comment:
124 -- "At a variable occurrence, add in any free variables of its rule rhss
125 -- Curiously, we gather the Id's free *type* variables from its binding
126 -- site, but its free *rule-rhs* variables from its usage sites. This
127 -- is a little weird. The reason is that the former is more efficient,
128 -- but the latter is more fine grained, and a makes a difference when
129 -- a variable mentions itself one of its own rule RHSs"
130 -- Not only is this "weird", but it's also pretty bad because it can make
131 -- a function seem more recursive than it is. Suppose
134 -- RULE g x = ...f...
135 -- Then f is not mentioned in its own RHS, and needn't be a loop breaker
136 -- (though g may be). But if we collect the rule fvs from g's occurrence,
137 -- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB
138 -- code in GHC.Enum.)
140 -- Anyway, it seems plain wrong. The RULE is like an extra RHS for the
141 -- function, so its free variables belong at the definition site.
143 -- Deleted code looked like
144 -- foldVarSet add_rule_var var_itself_set (idRuleVars var)
145 -- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
150 oneVar var fv_cand in_scope
152 if keep_it fv_cand in_scope var
156 someVars :: VarSet -> FV
157 someVars vars fv_cand in_scope
158 = filterVarSet (keep_it fv_cand in_scope) vars
160 keep_it :: InterestingVarFun -> VarSet -> Var -> Bool
161 keep_it fv_cand in_scope var
162 | var `elemVarSet` in_scope = False
167 addBndr :: CoreBndr -> FV -> FV
168 addBndr bndr fv fv_cand in_scope
169 = someVars (varTypeTyVars bndr) fv_cand in_scope
170 -- Include type varibles in the binder's type
171 -- (not just Ids; coercion variables too!)
172 `unionVarSet` fv fv_cand (in_scope `extendVarSet` bndr)
174 addBndrs :: [CoreBndr] -> FV -> FV
175 addBndrs bndrs fv = foldr addBndr fv bndrs
180 expr_fvs :: CoreExpr -> FV
182 expr_fvs (Type ty) = someVars (tyVarsOfType ty)
183 expr_fvs (Var var) = oneVar var
184 expr_fvs (Lit _) = noVars
185 expr_fvs (Note _ expr) = expr_fvs expr
186 expr_fvs (App fun arg) = expr_fvs fun `union` expr_fvs arg
187 expr_fvs (Lam bndr body) = addBndr bndr (expr_fvs body)
188 expr_fvs (Cast expr co) = expr_fvs expr `union` someVars (tyVarsOfType co)
190 expr_fvs (Case scrut bndr ty alts)
191 = expr_fvs scrut `union` someVars (tyVarsOfType ty) `union` addBndr bndr
192 (foldr (union . alt_fvs) noVars alts)
194 alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
196 expr_fvs (Let (NonRec bndr rhs) body)
197 = rhs_fvs (bndr, rhs) `union` addBndr bndr (expr_fvs body)
199 expr_fvs (Let (Rec pairs) body)
200 = addBndrs (map fst pairs)
201 (foldr (union . rhs_fvs) (expr_fvs body) pairs)
204 rhs_fvs :: (Id,CoreExpr) -> FV
205 rhs_fvs (bndr, rhs) = expr_fvs rhs `union`
206 someVars (bndrRuleAndUnfoldingVars bndr)
207 -- Treat any RULES as extra RHSs of the binding
210 exprs_fvs :: [CoreExpr] -> FV
211 exprs_fvs exprs = foldr (union . expr_fvs) noVars exprs
215 %************************************************************************
219 %************************************************************************
222 -- | Similar to 'exprFreeNames'. However, this is used when deciding whether
223 -- a rule is an orphan. In particular, suppose that T is defined in this
224 -- module; we want to avoid declaring that a rule like:
226 -- > fromIntegral T = fromIntegral_T
228 -- is an orphan. Of course it isn't, and declaring it an orphan would
229 -- make the whole module an orphan module, which is bad.
230 ruleLhsFreeNames :: CoreRule -> NameSet
231 ruleLhsFreeNames (BuiltinRule { ru_fn = fn }) = unitNameSet fn
232 ruleLhsFreeNames (Rule { ru_fn = fn, ru_args = tpl_args })
233 = addOneToNameSet (exprsFreeNames tpl_args) fn
235 -- | Finds the free /external/ names of an expression, notably
236 -- including the names of type constructors (which of course do not show
237 -- up in 'exprFreeVars').
238 exprFreeNames :: CoreExpr -> NameSet
239 -- There's no need to delete local binders, because they will all
240 -- be /internal/ names.
245 | isExternalName n = unitNameSet n
246 | otherwise = emptyNameSet
248 go (Lit _) = emptyNameSet
249 go (Type ty) = tyClsNamesOfType ty -- Don't need free tyvars
250 go (App e1 e2) = go e1 `unionNameSets` go e2
251 go (Lam v e) = go e `delFromNameSet` idName v
253 go (Cast e co) = go e `unionNameSets` tyClsNamesOfType co
254 go (Let (NonRec _ r) e) = go e `unionNameSets` go r
255 go (Let (Rec prs) e) = exprsFreeNames (map snd prs) `unionNameSets` go e
256 go (Case e _ ty as) = go e `unionNameSets` tyClsNamesOfType ty
257 `unionNameSets` unionManyNameSets (map go_alt as)
259 go_alt (_,_,r) = go r
261 -- | Finds the free /external/ names of several expressions: see 'exprFreeNames' for details
262 exprsFreeNames :: [CoreExpr] -> NameSet
263 exprsFreeNames es = foldr (unionNameSets . exprFreeNames) emptyNameSet es
266 %************************************************************************
268 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
270 %************************************************************************
273 -- | Those variables free in the right hand side of a rule
274 ruleRhsFreeVars :: CoreRule -> VarSet
275 ruleRhsFreeVars (BuiltinRule {}) = noFVs
276 ruleRhsFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs })
277 = delFromUFM fvs fn -- Note [Rule free var hack]
279 fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
281 -- | Those variables free in the both the left right hand sides of a rule
282 ruleFreeVars :: CoreRule -> VarSet
283 ruleFreeVars (BuiltinRule {}) = noFVs
284 ruleFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs, ru_args = args })
285 = delFromUFM fvs fn -- Note [Rule free var hack]
287 fvs = addBndrs bndrs (exprs_fvs (rhs:args)) isLocalVar emptyVarSet
289 idRuleRhsVars :: (Activation -> Bool) -> Id -> VarSet
290 -- Just the variables free on the *rhs* of a rule
291 idRuleRhsVars is_active id
292 = foldr (unionVarSet . get_fvs) emptyVarSet (idCoreRules id)
294 get_fvs (Rule { ru_fn = fn, ru_bndrs = bndrs
295 , ru_rhs = rhs, ru_act = act })
297 -- See Note [Finding rule RHS free vars] in OccAnal.lhs
298 = delFromUFM fvs fn -- Note [Rule free var hack]
300 fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
303 -- | Those variables free in the right hand side of several rules
304 rulesFreeVars :: [CoreRule] -> VarSet
305 rulesFreeVars rules = foldr (unionVarSet . ruleFreeVars) emptyVarSet rules
307 ruleLhsFreeIds :: CoreRule -> VarSet
308 -- ^ This finds all locally-defined free Ids on the left hand side of a rule
309 ruleLhsFreeIds (BuiltinRule {}) = noFVs
310 ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args })
311 = addBndrs bndrs (exprs_fvs args) isLocalId emptyVarSet
314 Note [Rule free var hack]
315 ~~~~~~~~~~~~~~~~~~~~~~~~~
316 Don't include the Id in its own rhs free-var set.
317 Otherwise the occurrence analyser makes bindings recursive
318 that shoudn't be. E.g.
319 RULE: f (f x y) z ==> f x (f y z)
321 Also since rule_fn is a Name, not a Var, we have to use the grungy delUFM.
323 %************************************************************************
325 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
327 %************************************************************************
329 The free variable pass annotates every node in the expression with its
330 NON-GLOBAL free variables and type variables.
333 -- | Every node in a binding group annotated with its
334 -- (non-global) free variables, both Ids and TyVars
335 type CoreBindWithFVs = AnnBind Id VarSet
336 -- | Every node in an expression annotated with its
337 -- (non-global) free variables, both Ids and TyVars
338 type CoreExprWithFVs = AnnExpr Id VarSet
340 freeVarsOf :: CoreExprWithFVs -> IdSet
341 -- ^ Inverse function to 'freeVars'
342 freeVarsOf (free_vars, _) = free_vars
347 aFreeVar :: Var -> VarSet
348 aFreeVar = unitVarSet
350 unionFVs :: VarSet -> VarSet -> VarSet
351 unionFVs = unionVarSet
353 delBindersFV :: [Var] -> VarSet -> VarSet
354 delBindersFV bs fvs = foldr delBinderFV fvs bs
356 delBinderFV :: Var -> VarSet -> VarSet
357 -- This way round, so we can do it multiple times using foldr
359 -- (b `delBinderFV` s) removes the binder b from the free variable set s,
362 -- the free variables of b's type
364 -- This is really important for some lambdas:
365 -- In (\x::a -> x) the only mention of "a" is in the binder.
368 -- let x::a = b in ...
369 -- we should really note that "a" is free in this expression.
370 -- It'll be pinned inside the /\a by the binding for b, but
371 -- it seems cleaner to make sure that a is in the free-var set
372 -- when it is mentioned.
374 -- This also shows up in recursive bindings. Consider:
375 -- /\a -> letrec x::a = x in E
376 -- Now, there are no explicit free type variables in the RHS of x,
377 -- but nevertheless "a" is free in its definition. So we add in
378 -- the free tyvars of the types of the binders, and include these in the
379 -- free vars of the group, attached to the top level of each RHS.
381 -- This actually happened in the defn of errorIO in IOBase.lhs:
382 -- errorIO (ST io) = case (errorIO# io) of
385 -- bottom = bottom -- Never evaluated
387 delBinderFV b s = (s `delVarSet` b) `unionFVs` varTypeTyVars b
388 -- Include coercion variables too!
390 varTypeTyVars :: Var -> TyVarSet
391 -- Find the type variables free in the type of the variable
392 -- Remember, coercion variables can mention type variables...
394 | isLocalId var || isCoVar var = tyVarsOfType (idType var)
395 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
397 varTypeTcTyVars :: Var -> TyVarSet
398 -- Find the type variables free in the type of the variable
399 -- Remember, coercion variables can mention type variables...
401 | isLocalId var || isCoVar var = tcTyVarsOfType (idType var)
402 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
404 idFreeVars :: Id -> VarSet
405 -- Type variables, rule variables, and inline variables
406 idFreeVars id = ASSERT( isId id)
407 varTypeTyVars id `unionVarSet`
408 idRuleAndUnfoldingVars id
410 bndrRuleAndUnfoldingVars ::Var -> VarSet
411 -- A 'let' can bind a type variable, and idRuleVars assumes
412 -- it's seeing an Id. This function tests first.
413 bndrRuleAndUnfoldingVars v | isTyCoVar v = emptyVarSet
414 | otherwise = idRuleAndUnfoldingVars v
416 idRuleAndUnfoldingVars :: Id -> VarSet
417 idRuleAndUnfoldingVars id = ASSERT( isId id)
418 idRuleVars id `unionVarSet`
421 idRuleVars ::Id -> VarSet -- Does *not* include CoreUnfolding vars
422 idRuleVars id = ASSERT( isId id) specInfoFreeVars (idSpecialisation id)
424 idUnfoldingVars :: Id -> VarSet
425 -- Produce free vars for an unfolding, but NOT for an ordinary
426 -- (non-inline) unfolding, since it is a dup of the rhs
427 -- and we'll get exponential behaviour if we look at both unf and rhs!
428 -- But do look at the *real* unfolding, even for loop breakers, else
429 -- we might get out-of-scope variables
430 idUnfoldingVars id = stableUnfoldingVars (realIdUnfolding id)
432 stableUnfoldingVars :: Unfolding -> VarSet
433 stableUnfoldingVars (CoreUnfolding { uf_tmpl = rhs, uf_src = src })
434 | isStableSource src = exprFreeVars rhs
435 stableUnfoldingVars (DFunUnfolding _ _ args) = exprsFreeVars (dfunArgExprs args)
436 stableUnfoldingVars _ = emptyVarSet
440 %************************************************************************
442 \subsection{Free variables (and types)}
444 %************************************************************************
447 freeVars :: CoreExpr -> CoreExprWithFVs
448 -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node
452 -- ToDo: insert motivating example for why we *need*
453 -- to include the idSpecVars in the FV list.
454 -- Actually [June 98] I don't think it's necessary
455 -- fvs = fvs_v `unionVarSet` idSpecVars v
457 fvs | isLocalVar v = aFreeVar v
460 freeVars (Lit lit) = (noFVs, AnnLit lit)
461 freeVars (Lam b body)
462 = (b `delBinderFV` freeVarsOf body', AnnLam b body')
464 body' = freeVars body
466 freeVars (App fun arg)
467 = (freeVarsOf fun2 `unionFVs` freeVarsOf arg2, AnnApp fun2 arg2)
472 freeVars (Case scrut bndr ty alts)
473 = ((bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyVarsOfType ty,
474 AnnCase scrut2 bndr ty alts2)
476 scrut2 = freeVars scrut
478 (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
479 alts_fvs = foldr1 unionFVs alts_fvs_s
481 fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
486 freeVars (Let (NonRec binder rhs) body)
489 `unionFVs` bndrRuleAndUnfoldingVars binder,
490 -- Remember any rules; cf rhs_fvs above
491 AnnLet (AnnNonRec binder rhs2) body2)
494 body2 = freeVars body
495 body_fvs = binder `delBinderFV` freeVarsOf body2
497 freeVars (Let (Rec binds) body)
498 = (delBindersFV binders all_fvs,
499 AnnLet (AnnRec (binders `zip` rhss2)) body2)
501 (binders, rhss) = unzip binds
503 rhss2 = map freeVars rhss
504 rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
505 all_fvs = foldr (unionFVs . idRuleAndUnfoldingVars) rhs_body_fvs binders
506 -- The "delBinderFV" happens after adding the idSpecVars,
507 -- since the latter may add some of the binders as fvs
509 body2 = freeVars body
510 body_fvs = freeVarsOf body2
513 freeVars (Cast expr co)
514 = (freeVarsOf expr2 `unionFVs` cfvs, AnnCast expr2 co)
516 expr2 = freeVars expr
517 cfvs = tyVarsOfType co
519 freeVars (Note other_note expr)
520 = (freeVarsOf expr2, AnnNote other_note expr2)
522 expr2 = freeVars expr
524 freeVars (Type ty) = (tyVarsOfType ty, AnnType ty)