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,
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,
34 -- * Core syntax tree annotation with free variables
35 CoreExprWithFVs, -- = AnnExpr Id VarSet
36 CoreBindWithFVs, -- = AnnBind Id VarSet
37 freeVars, -- CoreExpr -> CoreExprWithFVs
38 freeVarsOf -- CoreExprWithFVs -> IdSet
41 #include "HsVersions.h"
53 import BasicTypes( Activation )
58 %************************************************************************
60 \section{Finding the free variables of an expression}
62 %************************************************************************
64 This function simply finds the free variables of an expression.
65 So far as type variables are concerned, it only finds tyvars that are
67 * free in type arguments,
68 * free in the type of a binder,
70 but not those that are free in the type of variable occurrence.
73 -- | Find all locally-defined free Ids or type variables in an expression
74 exprFreeVars :: CoreExpr -> VarSet
75 exprFreeVars = exprSomeFreeVars isLocalVar
77 -- | Find all locally-defined free Ids in an expression
78 exprFreeIds :: CoreExpr -> IdSet -- Find all locally-defined free Ids
79 exprFreeIds = exprSomeFreeVars isLocalId
81 -- | Find all locally-defined free Ids or type variables in several expressions
82 exprsFreeVars :: [CoreExpr] -> VarSet
83 exprsFreeVars = foldr (unionVarSet . exprFreeVars) emptyVarSet
85 -- | Find all locally defined free Ids in a binding group
86 bindFreeVars :: CoreBind -> VarSet
87 bindFreeVars (NonRec _ r) = exprFreeVars r
88 bindFreeVars (Rec prs) = addBndrs (map fst prs)
89 (foldr (union . rhs_fvs) noVars prs)
90 isLocalVar emptyVarSet
92 -- | Finds free variables in an expression selected by a predicate
93 exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting
96 exprSomeFreeVars fv_cand e = expr_fvs e fv_cand emptyVarSet
98 -- | Finds free variables in several expressions selected by a predicate
99 exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting
102 exprsSomeFreeVars fv_cand = foldr (unionVarSet . exprSomeFreeVars fv_cand) emptyVarSet
104 -- | Predicate on possible free variables: returns @True@ iff the variable is interesting
105 type InterestingVarFun = Var -> Bool
110 type FV = InterestingVarFun
111 -> VarSet -- In scope
112 -> VarSet -- Free vars
114 union :: FV -> FV -> FV
115 union fv1 fv2 fv_cand in_scope = fv1 fv_cand in_scope `unionVarSet` fv2 fv_cand in_scope
118 noVars _ _ = emptyVarSet
120 -- Comment about obselete code
121 -- We used to gather the free variables the RULES at a variable occurrence
122 -- with the following cryptic comment:
123 -- "At a variable occurrence, add in any free variables of its rule rhss
124 -- Curiously, we gather the Id's free *type* variables from its binding
125 -- site, but its free *rule-rhs* variables from its usage sites. This
126 -- is a little weird. The reason is that the former is more efficient,
127 -- but the latter is more fine grained, and a makes a difference when
128 -- a variable mentions itself one of its own rule RHSs"
129 -- Not only is this "weird", but it's also pretty bad because it can make
130 -- a function seem more recursive than it is. Suppose
133 -- RULE g x = ...f...
134 -- Then f is not mentioned in its own RHS, and needn't be a loop breaker
135 -- (though g may be). But if we collect the rule fvs from g's occurrence,
136 -- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB
137 -- code in GHC.Enum.)
139 -- Anyway, it seems plain wrong. The RULE is like an extra RHS for the
140 -- function, so its free variables belong at the definition site.
142 -- Deleted code looked like
143 -- foldVarSet add_rule_var var_itself_set (idRuleVars var)
144 -- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
149 oneVar var fv_cand in_scope
151 if keep_it fv_cand in_scope var
155 someVars :: VarSet -> FV
156 someVars vars fv_cand in_scope
157 = filterVarSet (keep_it fv_cand in_scope) vars
159 keep_it :: InterestingVarFun -> VarSet -> Var -> Bool
160 keep_it fv_cand in_scope var
161 | var `elemVarSet` in_scope = False
166 addBndr :: CoreBndr -> FV -> FV
167 addBndr bndr fv fv_cand in_scope
168 = someVars (varTypeTyVars bndr) fv_cand in_scope
169 -- Include type varibles in the binder's type
170 -- (not just Ids; coercion variables too!)
171 `unionVarSet` fv fv_cand (in_scope `extendVarSet` bndr)
173 addBndrs :: [CoreBndr] -> FV -> FV
174 addBndrs bndrs fv = foldr addBndr fv bndrs
179 expr_fvs :: CoreExpr -> FV
181 expr_fvs (Type ty) = someVars (tyVarsOfType ty)
182 expr_fvs (Var var) = oneVar var
183 expr_fvs (Lit _) = noVars
184 expr_fvs (Note _ expr) = expr_fvs expr
185 expr_fvs (App fun arg) = expr_fvs fun `union` expr_fvs arg
186 expr_fvs (Lam bndr body) = addBndr bndr (expr_fvs body)
187 expr_fvs (Cast expr co) = expr_fvs expr `union` someVars (tyVarsOfType co)
189 expr_fvs (Case scrut bndr ty alts)
190 = expr_fvs scrut `union` someVars (tyVarsOfType ty) `union` addBndr bndr
191 (foldr (union . alt_fvs) noVars alts)
193 alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
195 expr_fvs (Let (NonRec bndr rhs) body)
196 = rhs_fvs (bndr, rhs) `union` addBndr bndr (expr_fvs body)
198 expr_fvs (Let (Rec pairs) body)
199 = addBndrs (map fst pairs)
200 (foldr (union . rhs_fvs) (expr_fvs body) pairs)
203 rhs_fvs :: (Id,CoreExpr) -> FV
204 rhs_fvs (bndr, rhs) = expr_fvs rhs `union`
205 someVars (bndrRuleAndUnfoldingVars bndr)
206 -- Treat any RULES as extra RHSs of the binding
209 exprs_fvs :: [CoreExpr] -> FV
210 exprs_fvs exprs = foldr (union . expr_fvs) noVars exprs
214 %************************************************************************
218 %************************************************************************
221 -- | ruleLhsOrphNames is used when deciding whether
222 -- a rule is an orphan. In particular, suppose that T is defined in this
223 -- module; we want to avoid declaring that a rule like:
225 -- > fromIntegral T = fromIntegral_T
227 -- is an orphan. Of course it isn't, and declaring it an orphan would
228 -- make the whole module an orphan module, which is bad.
229 ruleLhsOrphNames :: CoreRule -> NameSet
230 ruleLhsOrphNames (BuiltinRule { ru_fn = fn }) = unitNameSet fn
231 ruleLhsOrphNames (Rule { ru_fn = fn, ru_args = tpl_args })
232 = addOneToNameSet (exprsOrphNames tpl_args) fn
233 -- No need to delete bndrs, because
234 -- exprsOrphNames finds only External names
236 -- | Finds the free /external/ names of an expression, notably
237 -- including the names of type constructors (which of course do not show
238 -- up in 'exprFreeVars').
239 exprOrphNames :: CoreExpr -> NameSet
240 -- There's no need to delete local binders, because they will all
241 -- be /internal/ names.
246 | isExternalName n = unitNameSet n
247 | otherwise = emptyNameSet
249 go (Lit _) = emptyNameSet
250 go (Type ty) = orphNamesOfType ty -- Don't need free tyvars
251 go (App e1 e2) = go e1 `unionNameSets` go e2
252 go (Lam v e) = go e `delFromNameSet` idName v
254 go (Cast e co) = go e `unionNameSets` orphNamesOfType co
255 go (Let (NonRec _ r) e) = go e `unionNameSets` go r
256 go (Let (Rec prs) e) = exprsOrphNames (map snd prs) `unionNameSets` go e
257 go (Case e _ ty as) = go e `unionNameSets` orphNamesOfType ty
258 `unionNameSets` unionManyNameSets (map go_alt as)
260 go_alt (_,_,r) = go r
262 -- | Finds the free /external/ names of several expressions: see 'exprOrphNames' for details
263 exprsOrphNames :: [CoreExpr] -> NameSet
264 exprsOrphNames es = foldr (unionNameSets . exprOrphNames) emptyNameSet es
267 %************************************************************************
269 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
271 %************************************************************************
274 -- | Those variables free in the right hand side of a rule
275 ruleRhsFreeVars :: CoreRule -> VarSet
276 ruleRhsFreeVars (BuiltinRule {}) = noFVs
277 ruleRhsFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs })
278 = delFromUFM fvs fn -- Note [Rule free var hack]
280 fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
282 -- | Those variables free in the both the left right hand sides of a rule
283 ruleFreeVars :: CoreRule -> VarSet
284 ruleFreeVars (BuiltinRule {}) = noFVs
285 ruleFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs, ru_args = args })
286 = delFromUFM fvs fn -- Note [Rule free var hack]
288 fvs = addBndrs bndrs (exprs_fvs (rhs:args)) isLocalVar emptyVarSet
290 idRuleRhsVars :: (Activation -> Bool) -> Id -> VarSet
291 -- Just the variables free on the *rhs* of a rule
292 idRuleRhsVars is_active id
293 = foldr (unionVarSet . get_fvs) emptyVarSet (idCoreRules id)
295 get_fvs (Rule { ru_fn = fn, ru_bndrs = bndrs
296 , ru_rhs = rhs, ru_act = act })
298 -- See Note [Finding rule RHS free vars] in OccAnal.lhs
299 = delFromUFM fvs fn -- Note [Rule free var hack]
301 fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
304 -- | Those variables free in the right hand side of several rules
305 rulesFreeVars :: [CoreRule] -> VarSet
306 rulesFreeVars rules = foldr (unionVarSet . ruleFreeVars) emptyVarSet rules
308 ruleLhsFreeIds :: CoreRule -> VarSet
309 -- ^ This finds all locally-defined free Ids on the left hand side of a rule
310 ruleLhsFreeIds (BuiltinRule {}) = noFVs
311 ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args })
312 = addBndrs bndrs (exprs_fvs args) isLocalId emptyVarSet
315 Note [Rule free var hack]
316 ~~~~~~~~~~~~~~~~~~~~~~~~~
317 Don't include the Id in its own rhs free-var set.
318 Otherwise the occurrence analyser makes bindings recursive
319 that shoudn't be. E.g.
320 RULE: f (f x y) z ==> f x (f y z)
322 Also since rule_fn is a Name, not a Var, we have to use the grungy delUFM.
324 %************************************************************************
326 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
328 %************************************************************************
330 The free variable pass annotates every node in the expression with its
331 NON-GLOBAL free variables and type variables.
334 -- | Every node in a binding group annotated with its
335 -- (non-global) free variables, both Ids and TyVars
336 type CoreBindWithFVs = AnnBind Id VarSet
337 -- | Every node in an expression annotated with its
338 -- (non-global) free variables, both Ids and TyVars
339 type CoreExprWithFVs = AnnExpr Id VarSet
341 freeVarsOf :: CoreExprWithFVs -> IdSet
342 -- ^ Inverse function to 'freeVars'
343 freeVarsOf (free_vars, _) = free_vars
348 aFreeVar :: Var -> VarSet
349 aFreeVar = unitVarSet
351 unionFVs :: VarSet -> VarSet -> VarSet
352 unionFVs = unionVarSet
354 delBindersFV :: [Var] -> VarSet -> VarSet
355 delBindersFV bs fvs = foldr delBinderFV fvs bs
357 delBinderFV :: Var -> VarSet -> VarSet
358 -- This way round, so we can do it multiple times using foldr
360 -- (b `delBinderFV` s) removes the binder b from the free variable set s,
363 -- the free variables of b's type
365 -- This is really important for some lambdas:
366 -- In (\x::a -> x) the only mention of "a" is in the binder.
369 -- let x::a = b in ...
370 -- we should really note that "a" is free in this expression.
371 -- It'll be pinned inside the /\a by the binding for b, but
372 -- it seems cleaner to make sure that a is in the free-var set
373 -- when it is mentioned.
375 -- This also shows up in recursive bindings. Consider:
376 -- /\a -> letrec x::a = x in E
377 -- Now, there are no explicit free type variables in the RHS of x,
378 -- but nevertheless "a" is free in its definition. So we add in
379 -- the free tyvars of the types of the binders, and include these in the
380 -- free vars of the group, attached to the top level of each RHS.
382 -- This actually happened in the defn of errorIO in IOBase.lhs:
383 -- errorIO (ST io) = case (errorIO# io) of
386 -- bottom = bottom -- Never evaluated
388 delBinderFV b s = (s `delVarSet` b) `unionFVs` varTypeTyVars b
389 -- Include coercion variables too!
391 varTypeTyVars :: Var -> TyVarSet
392 -- Find the type variables free in the type of the variable
393 -- Remember, coercion variables can mention type variables...
395 | isLocalId var || isCoVar var = tyVarsOfType (idType var)
396 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
398 varTypeTcTyVars :: Var -> TyVarSet
399 -- Find the type variables free in the type of the variable
400 -- Remember, coercion variables can mention type variables...
402 | isLocalId var || isCoVar var = tcTyVarsOfType (idType var)
403 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
405 idFreeVars :: Id -> VarSet
406 -- Type variables, rule variables, and inline variables
407 idFreeVars id = ASSERT( isId id)
408 varTypeTyVars id `unionVarSet`
409 idRuleAndUnfoldingVars id
411 bndrRuleAndUnfoldingVars ::Var -> VarSet
412 -- A 'let' can bind a type variable, and idRuleVars assumes
413 -- it's seeing an Id. This function tests first.
414 bndrRuleAndUnfoldingVars v | isTyCoVar v = emptyVarSet
415 | otherwise = idRuleAndUnfoldingVars v
417 idRuleAndUnfoldingVars :: Id -> VarSet
418 idRuleAndUnfoldingVars id = ASSERT( isId id)
419 idRuleVars id `unionVarSet`
422 idRuleVars ::Id -> VarSet -- Does *not* include CoreUnfolding vars
423 idRuleVars id = ASSERT( isId id) specInfoFreeVars (idSpecialisation id)
425 idUnfoldingVars :: Id -> VarSet
426 -- Produce free vars for an unfolding, but NOT for an ordinary
427 -- (non-inline) unfolding, since it is a dup of the rhs
428 -- and we'll get exponential behaviour if we look at both unf and rhs!
429 -- But do look at the *real* unfolding, even for loop breakers, else
430 -- we might get out-of-scope variables
431 idUnfoldingVars id = stableUnfoldingVars (realIdUnfolding id)
433 stableUnfoldingVars :: Unfolding -> VarSet
434 stableUnfoldingVars (CoreUnfolding { uf_tmpl = rhs, uf_src = src })
435 | isStableSource src = exprFreeVars rhs
436 stableUnfoldingVars (DFunUnfolding _ _ args) = exprsFreeVars (dfunArgExprs args)
437 stableUnfoldingVars _ = emptyVarSet
441 %************************************************************************
443 \subsection{Free variables (and types)}
445 %************************************************************************
448 freeVars :: CoreExpr -> CoreExprWithFVs
449 -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node
453 -- ToDo: insert motivating example for why we *need*
454 -- to include the idSpecVars in the FV list.
455 -- Actually [June 98] I don't think it's necessary
456 -- fvs = fvs_v `unionVarSet` idSpecVars v
458 fvs | isLocalVar v = aFreeVar v
461 freeVars (Lit lit) = (noFVs, AnnLit lit)
462 freeVars (Lam b body)
463 = (b `delBinderFV` freeVarsOf body', AnnLam b body')
465 body' = freeVars body
467 freeVars (App fun arg)
468 = (freeVarsOf fun2 `unionFVs` freeVarsOf arg2, AnnApp fun2 arg2)
473 freeVars (Case scrut bndr ty alts)
474 = ((bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyVarsOfType ty,
475 AnnCase scrut2 bndr ty alts2)
477 scrut2 = freeVars scrut
479 (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
480 alts_fvs = foldr1 unionFVs alts_fvs_s
482 fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
487 freeVars (Let (NonRec binder rhs) body)
490 `unionFVs` bndrRuleAndUnfoldingVars binder,
491 -- Remember any rules; cf rhs_fvs above
492 AnnLet (AnnNonRec binder rhs2) body2)
495 body2 = freeVars body
496 body_fvs = binder `delBinderFV` freeVarsOf body2
498 freeVars (Let (Rec binds) body)
499 = (delBindersFV binders all_fvs,
500 AnnLet (AnnRec (binders `zip` rhss2)) body2)
502 (binders, rhss) = unzip binds
504 rhss2 = map freeVars rhss
505 rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
506 all_fvs = foldr (unionFVs . idRuleAndUnfoldingVars) rhs_body_fvs binders
507 -- The "delBinderFV" happens after adding the idSpecVars,
508 -- since the latter may add some of the binders as fvs
510 body2 = freeVars body
511 body_fvs = freeVarsOf body2
514 freeVars (Cast expr co)
515 = (freeVarsOf expr2 `unionFVs` cfvs, AnnCast expr2 co)
517 expr2 = freeVars expr
518 cfvs = tyVarsOfType co
520 freeVars (Note other_note expr)
521 = (freeVarsOf expr2, AnnNote other_note expr2)
523 expr2 = freeVars expr
525 freeVars (Type ty) = (tyVarsOfType ty, AnnType ty)