2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Utility functions on @Core@ syntax
11 Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
14 substTy, substExpr, substSpec, substWorker,
15 lookupIdSubst, lookupTvSubst,
17 emptySubst, mkEmptySubst, mkSubst, substInScope, isEmptySubst,
18 extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
19 extendSubstList, zapSubstEnv,
20 extendInScope, extendInScopeList, extendInScopeIds,
24 substBndr, substBndrs, substRecBndrs,
25 cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs
28 #include "HsVersions.h"
35 import Type ( Type, TvSubst(..), TvSubstEnv )
39 import Var ( Var, TyVar, setVarUnique )
45 import PprCore () -- Instances
53 %************************************************************************
55 \subsection{Substitutions}
57 %************************************************************************
61 = Subst InScopeSet -- Variables in in scope (both Ids and TyVars)
62 -- *after* applying the substitution
63 IdSubstEnv -- Substitution for Ids
64 TvSubstEnv -- Substitution for TyVars
66 -- INVARIANT 1: The (domain of the) in-scope set is a superset
67 -- of the free vars of the range of the substitution
68 -- that might possibly clash with locally-bound variables
69 -- in the thing being substituted in.
70 -- This is what lets us deal with name capture properly
71 -- It's a hard invariant to check...
72 -- There are various ways of causing it to happen:
73 -- - arrange that the in-scope set really is all the things in scope
74 -- - arrange that it's the free vars of the range of the substitution
75 -- - make it empty because all the free vars of the subst are fresh,
76 -- and hence can't possibly clash.a
78 -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
81 -- INVARIANT 3: See Note [Extending the Subst]
84 Note [Extending the Subst]
85 ~~~~~~~~~~~~~~~~~~~~~~~~~~
86 For a core Subst, which binds Ids as well, we make a different choice for Ids
87 than we do for TyVars.
89 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
91 For Ids, we have a different invariant
92 The IdSubstEnv is extended *only* when the Unique on an Id changes
93 Otherwise, we just extend the InScopeSet
97 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
99 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr does nothing
100 (Note that the above rule for substIdBndr maintains this property. If
101 the incoming envts are both empty, then substituting the type and
102 IdInfo can't change anything.)
104 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
105 it may contain non-trivial changes. Example:
106 (/\a. \x:a. ...x...) Int
107 We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
108 so we only extend the in-scope set. Then we must look up in the in-scope
109 set when we find the occurrence of x.
111 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
113 * For Ids, we change the IdInfo all the time (e.g. deleting the
114 unfolding), and adding it back later, so using the TyVar convention
115 would entail extending the substitution almost all the time
117 * The simplifier wants to look up in the in-scope set anyway, in case it
118 can see a better unfolding from an enclosing case expression
120 * For TyVars, only coercion variables can possibly change, and they are
124 type IdSubstEnv = IdEnv CoreExpr
126 ----------------------------
127 isEmptySubst :: Subst -> Bool
128 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
131 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
133 mkEmptySubst :: InScopeSet -> Subst
134 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
136 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
137 mkSubst in_scope tvs ids = Subst in_scope ids tvs
139 -- getTvSubst :: Subst -> TvSubst
140 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
142 -- getTvSubstEnv :: Subst -> TvSubstEnv
143 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
145 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
146 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
148 substInScope :: Subst -> InScopeSet
149 substInScope (Subst in_scope _ _) = in_scope
151 zapSubstEnv :: Subst -> Subst
152 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
154 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
155 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
156 extendIdSubst (Subst in_scope ids tvs) v r = Subst in_scope (extendVarEnv ids v r) tvs
158 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
159 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
161 extendTvSubst :: Subst -> TyVar -> Type -> Subst
162 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r)
164 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
165 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
167 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
168 extendSubstList subst []
170 extendSubstList (Subst in_scope ids tvs) ((tv,Type ty):prs)
171 = ASSERT( isTyVar tv ) extendSubstList (Subst in_scope ids (extendVarEnv tvs tv ty)) prs
172 extendSubstList (Subst in_scope ids tvs) ((id,expr):prs)
173 = ASSERT( isId id ) extendSubstList (Subst in_scope (extendVarEnv ids id expr) tvs) prs
175 lookupIdSubst :: Subst -> Id -> CoreExpr
176 lookupIdSubst (Subst in_scope ids tvs) v
177 | not (isLocalId v) = Var v
178 | Just e <- lookupVarEnv ids v = e
179 | Just v' <- lookupInScope in_scope v = Var v'
180 -- Vital! See Note [Extending the Subst]
181 | otherwise = WARN( True, ptext SLIT("CoreSubst.lookupIdSubst") <+> ppr v )
184 lookupTvSubst :: Subst -> TyVar -> Type
185 lookupTvSubst (Subst _ ids tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
187 ------------------------------
188 isInScope :: Var -> Subst -> Bool
189 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
191 extendInScope :: Subst -> Var -> Subst
192 extendInScope (Subst in_scope ids tvs) v
193 = Subst (in_scope `extendInScopeSet` v)
194 (ids `delVarEnv` v) (tvs `delVarEnv` v)
196 extendInScopeList :: Subst -> [Var] -> Subst
197 extendInScopeList (Subst in_scope ids tvs) vs
198 = Subst (in_scope `extendInScopeSetList` vs)
199 (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
201 extendInScopeIds :: Subst -> [Id] -> Subst
202 extendInScopeIds (Subst in_scope ids tvs) vs
203 = Subst (in_scope `extendInScopeSetList` vs)
204 (ids `delVarEnvList` vs) tvs
207 Pretty printing, for debugging only
210 instance Outputable Subst where
211 ppr (Subst in_scope ids tvs)
212 = ptext SLIT("<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
213 $$ ptext SLIT(" IdSubst =") <+> ppr ids
214 $$ ptext SLIT(" TvSubst =") <+> ppr tvs
219 %************************************************************************
221 Substituting expressions
223 %************************************************************************
226 substExpr :: Subst -> CoreExpr -> CoreExpr
230 go (Var v) = lookupIdSubst subst v
231 go (Type ty) = Type (substTy subst ty)
232 go (Lit lit) = Lit lit
233 go (App fun arg) = App (go fun) (go arg)
234 go (Note note e) = Note (go_note note) (go e)
235 go (Cast e co) = Cast (go e) (substTy subst co)
236 go (Lam bndr body) = Lam bndr' (substExpr subst' body)
238 (subst', bndr') = substBndr subst bndr
240 go (Let bind body) = Let bind' (substExpr subst' body)
242 (subst', bind') = substBind subst bind
244 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
246 (subst', bndr') = substBndr subst bndr
248 go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
250 (subst', bndrs') = substBndrs subst bndrs
254 substBind :: Subst -> CoreBind -> (Subst, CoreBind)
255 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (substExpr subst rhs))
257 (subst', bndr') = substBndr subst bndr
259 substBind subst (Rec pairs) = (subst', Rec pairs')
261 (subst', bndrs') = substRecBndrs subst (map fst pairs)
262 pairs' = bndrs' `zip` rhss'
263 rhss' = map (substExpr subst' . snd) pairs
266 De-shadowing the program is sometimes a useful pre-pass. It can be done simply
267 by running over the bindings with an empty substitution, becuase substitution
268 returns a result that has no-shadowing guaranteed.
270 (Actually, within a single *type* there might still be shadowing, because
271 substType is a no-op for the empty substitution, but that's OK.)
274 deShadowBinds :: [CoreBind] -> [CoreBind]
275 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
279 %************************************************************************
283 %************************************************************************
285 Remember that substBndr and friends are used when doing expression
286 substitution only. Their only business is substitution, so they
287 preserve all IdInfo (suitably substituted). For example, we *want* to
288 preserve occ info in rules.
291 substBndr :: Subst -> Var -> (Subst, Var)
293 | isTyVar bndr = substTyVarBndr subst bndr
294 | otherwise = substIdBndr subst subst bndr
296 substBndrs :: Subst -> [Var] -> (Subst, [Var])
297 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
299 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
300 -- Substitute a mutually recursive group
301 substRecBndrs subst bndrs
302 = (new_subst, new_bndrs)
303 where -- Here's the reason we need to pass rec_subst to subst_id
304 (new_subst, new_bndrs) = mapAccumL (substIdBndr new_subst) subst bndrs
309 substIdBndr :: Subst -- Substitution to use for the IdInfo
310 -> Subst -> Id -- Substitition and Id to transform
311 -> (Subst, Id) -- Transformed pair
312 -- NB: unfolding may be zapped
314 substIdBndr rec_subst subst@(Subst in_scope env tvs) old_id
315 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
317 id1 = uniqAway in_scope old_id -- id1 is cloned if necessary
318 id2 | no_type_change = id1
319 | otherwise = setIdType id1 (substTy subst old_ty)
321 old_ty = idType old_id
322 no_type_change = isEmptyVarEnv tvs ||
323 isEmptyVarSet (Type.tyVarsOfType old_ty)
325 -- new_id has the right IdInfo
326 -- The lazy-set is because we're in a loop here, with
327 -- rec_subst, when dealing with a mutually-recursive group
328 new_id = maybeModifyIdInfo mb_new_info id2
329 mb_new_info = substIdInfo rec_subst (idInfo id2)
330 -- NB: unfolding info may be zapped
332 -- Extend the substitution if the unique has changed
333 -- See the notes with substTyVarBndr for the delVarEnv
334 new_env | no_change = delVarEnv env old_id
335 | otherwise = extendVarEnv env old_id (Var new_id)
337 no_change = id1 == old_id
338 -- See Note [Extending the Subst]
339 -- *not* necessary to check mb_new_info and no_type_change
342 Now a variant that unconditionally allocates a new unique.
343 It also unconditionally zaps the OccInfo.
346 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
347 cloneIdBndr subst us old_id
348 = clone_id subst subst (old_id, uniqFromSupply us)
350 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
351 cloneIdBndrs subst us ids
352 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
354 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
355 cloneRecIdBndrs subst us ids
358 (subst', ids') = mapAccumL (clone_id subst') subst
359 (ids `zip` uniqsFromSupply us)
361 -- Just like substIdBndr, except that it always makes a new unique
362 -- It is given the unique to use
363 clone_id :: Subst -- Substitution for the IdInfo
364 -> Subst -> (Id, Unique) -- Substitition and Id to transform
365 -> (Subst, Id) -- Transformed pair
367 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
368 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
370 id1 = setVarUnique old_id uniq
371 id2 = substIdType subst id1
372 new_id = maybeModifyIdInfo (substIdInfo rec_subst (idInfo old_id)) id2
373 new_env = extendVarEnv env old_id (Var new_id)
377 %************************************************************************
381 %************************************************************************
383 For types we just call the corresponding function in Type, but we have
384 to repackage the substitution, from a Subst to a TvSubst
387 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
388 substTyVarBndr (Subst in_scope id_env tv_env) tv
389 = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
390 (TvSubst in_scope' tv_env', tv')
391 -> (Subst in_scope' id_env tv_env', tv')
393 substTy :: Subst -> Type -> Type
394 substTy (Subst in_scope id_env tv_env) ty
395 = Type.substTy (TvSubst in_scope tv_env) ty
399 %************************************************************************
401 \section{IdInfo substitution}
403 %************************************************************************
406 substIdType :: Subst -> Id -> Id
407 substIdType subst@(Subst in_scope id_env tv_env) id
408 | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
409 | otherwise = setIdType id (substTy subst old_ty)
410 -- The tyVarsOfType is cheaper than it looks
411 -- because we cache the free tyvars of the type
412 -- in a Note in the id's type itself
417 substIdInfo :: Subst -> IdInfo -> Maybe IdInfo
418 -- Always zaps the unfolding, to save substitution work
419 substIdInfo subst info
420 | nothing_to_do = Nothing
421 | otherwise = Just (info `setSpecInfo` substSpec subst old_rules
422 `setWorkerInfo` substWorker subst old_wrkr
423 `setUnfoldingInfo` noUnfolding)
425 old_rules = specInfo info
426 old_wrkr = workerInfo info
427 nothing_to_do = isEmptySpecInfo old_rules &&
428 not (workerExists old_wrkr) &&
429 not (hasUnfolding (unfoldingInfo info))
433 substWorker :: Subst -> WorkerInfo -> WorkerInfo
434 -- Seq'ing on the returned WorkerInfo is enough to cause all the
435 -- substitutions to happen completely
437 substWorker subst NoWorker
439 substWorker subst (HasWorker w a)
440 = case lookupIdSubst subst w of
441 Var w1 -> HasWorker w1 a
442 other -> WARN( not (exprIsTrivial other), text "CoreSubst.substWorker:" <+> ppr w )
443 NoWorker -- Worker has got substituted away altogether
444 -- (This can happen if it's trivial,
445 -- via postInlineUnconditionally, hence warning)
448 substSpec :: Subst -> SpecInfo -> SpecInfo
450 substSpec subst spec@(SpecInfo rules rhs_fvs)
454 = seqSpecInfo new_rules `seq` new_rules
456 new_rules = SpecInfo (map do_subst rules) (substVarSet subst rhs_fvs)
458 do_subst rule@(BuiltinRule {}) = rule
459 do_subst rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
460 = rule { ru_bndrs = bndrs',
461 ru_args = map (substExpr subst') args,
462 ru_rhs = substExpr subst' rhs }
464 (subst', bndrs') = substBndrs subst bndrs
467 substVarSet subst fvs
468 = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
471 | isId fv = exprFreeVars (lookupIdSubst subst fv)
472 | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)