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 extendSubst, 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
52 %************************************************************************
54 \subsection{Substitutions}
56 %************************************************************************
60 = Subst InScopeSet -- Variables in in scope (both Ids and TyVars)
61 -- *after* applying the substitution
62 IdSubstEnv -- Substitution for Ids
63 TvSubstEnv -- Substitution for TyVars
65 -- INVARIANT 1: The (domain of the) in-scope set is a superset
66 -- of the free vars of the range of the substitution
67 -- that might possibly clash with locally-bound variables
68 -- in the thing being substituted in.
69 -- This is what lets us deal with name capture properly
70 -- It's a hard invariant to check...
71 -- There are various ways of causing it to happen:
72 -- - arrange that the in-scope set really is all the things in scope
73 -- - arrange that it's the free vars of the range of the substitution
74 -- - make it empty because all the free vars of the subst are fresh,
75 -- and hence can't possibly clash.a
77 -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
80 -- INVARIANT 3: See Note [Extending the Subst]
83 Note [Extending the Subst]
84 ~~~~~~~~~~~~~~~~~~~~~~~~~~
85 For a core Subst, which binds Ids as well, we make a different choice for Ids
86 than we do for TyVars.
88 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
90 For Ids, we have a different invariant
91 The IdSubstEnv is extended *only* when the Unique on an Id changes
92 Otherwise, we just extend the InScopeSet
96 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
98 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr does nothing
99 (Note that the above rule for substIdBndr maintains this property. If
100 the incoming envts are both empty, then substituting the type and
101 IdInfo can't change anything.)
103 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
104 it may contain non-trivial changes. Example:
105 (/\a. \x:a. ...x...) Int
106 We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
107 so we only extend the in-scope set. Then we must look up in the in-scope
108 set when we find the occurrence of x.
110 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
112 * For Ids, we change the IdInfo all the time (e.g. deleting the
113 unfolding), and adding it back later, so using the TyVar convention
114 would entail extending the substitution almost all the time
116 * The simplifier wants to look up in the in-scope set anyway, in case it
117 can see a better unfolding from an enclosing case expression
119 * For TyVars, only coercion variables can possibly change, and they are
123 type IdSubstEnv = IdEnv CoreExpr
125 ----------------------------
126 isEmptySubst :: Subst -> Bool
127 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
130 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
132 mkEmptySubst :: InScopeSet -> Subst
133 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
135 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
136 mkSubst in_scope tvs ids = Subst in_scope ids tvs
138 -- getTvSubst :: Subst -> TvSubst
139 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
141 -- getTvSubstEnv :: Subst -> TvSubstEnv
142 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
144 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
145 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
147 substInScope :: Subst -> InScopeSet
148 substInScope (Subst in_scope _ _) = in_scope
150 zapSubstEnv :: Subst -> Subst
151 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
153 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
154 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
155 extendIdSubst (Subst in_scope ids tvs) v r = Subst in_scope (extendVarEnv ids v r) tvs
157 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
158 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
160 extendTvSubst :: Subst -> TyVar -> Type -> Subst
161 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r)
163 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
164 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
166 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
167 extendSubstList subst [] = subst
168 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
170 extendSubst :: Subst -> Var -> CoreArg -> Subst
171 extendSubst (Subst in_scope ids tvs) tv (Type ty)
172 = ASSERT( isTyVar tv ) Subst in_scope ids (extendVarEnv tvs tv ty)
173 extendSubst (Subst in_scope ids tvs) id expr
174 = ASSERT( isId id ) Subst in_scope (extendVarEnv ids id expr) tvs
176 lookupIdSubst :: Subst -> Id -> CoreExpr
177 lookupIdSubst (Subst in_scope ids _) v
178 | not (isLocalId v) = Var v
179 | Just e <- lookupVarEnv ids v = e
180 | Just v' <- lookupInScope in_scope v = Var v'
181 -- Vital! See Note [Extending the Subst]
182 | otherwise = WARN( True, ptext (sLit "CoreSubst.lookupIdSubst") <+> ppr v )
185 lookupTvSubst :: Subst -> TyVar -> Type
186 lookupTvSubst (Subst _ _ tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
188 ------------------------------
189 isInScope :: Var -> Subst -> Bool
190 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
192 extendInScope :: Subst -> Var -> Subst
193 extendInScope (Subst in_scope ids tvs) v
194 = Subst (in_scope `extendInScopeSet` v)
195 (ids `delVarEnv` v) (tvs `delVarEnv` v)
197 extendInScopeList :: Subst -> [Var] -> Subst
198 extendInScopeList (Subst in_scope ids tvs) vs
199 = Subst (in_scope `extendInScopeSetList` vs)
200 (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
202 extendInScopeIds :: Subst -> [Id] -> Subst
203 extendInScopeIds (Subst in_scope ids tvs) vs
204 = Subst (in_scope `extendInScopeSetList` vs)
205 (ids `delVarEnvList` vs) tvs
208 Pretty printing, for debugging only
211 instance Outputable Subst where
212 ppr (Subst in_scope ids tvs)
213 = ptext (sLit "<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
214 $$ ptext (sLit " IdSubst =") <+> ppr ids
215 $$ ptext (sLit " TvSubst =") <+> ppr tvs
220 %************************************************************************
222 Substituting expressions
224 %************************************************************************
227 substExpr :: Subst -> CoreExpr -> CoreExpr
231 go (Var v) = lookupIdSubst subst v
232 go (Type ty) = Type (substTy subst ty)
233 go (Lit lit) = Lit lit
234 go (App fun arg) = App (go fun) (go arg)
235 go (Note note e) = Note (go_note note) (go e)
236 go (Cast e co) = Cast (go e) (substTy subst co)
237 go (Lam bndr body) = Lam bndr' (substExpr subst' body)
239 (subst', bndr') = substBndr subst bndr
241 go (Let bind body) = Let bind' (substExpr subst' body)
243 (subst', bind') = substBind subst bind
245 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
247 (subst', bndr') = substBndr subst bndr
249 go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
251 (subst', bndrs') = substBndrs subst bndrs
255 substBind :: Subst -> CoreBind -> (Subst, CoreBind)
256 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (substExpr subst rhs))
258 (subst', bndr') = substBndr subst bndr
260 substBind subst (Rec pairs) = (subst', Rec pairs')
262 (subst', bndrs') = substRecBndrs subst (map fst pairs)
263 pairs' = bndrs' `zip` rhss'
264 rhss' = map (substExpr subst' . snd) pairs
267 De-shadowing the program is sometimes a useful pre-pass. It can be done simply
268 by running over the bindings with an empty substitution, becuase substitution
269 returns a result that has no-shadowing guaranteed.
271 (Actually, within a single *type* there might still be shadowing, because
272 substType is a no-op for the empty substitution, but that's OK.)
275 deShadowBinds :: [CoreBind] -> [CoreBind]
276 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
280 %************************************************************************
284 %************************************************************************
286 Remember that substBndr and friends are used when doing expression
287 substitution only. Their only business is substitution, so they
288 preserve all IdInfo (suitably substituted). For example, we *want* to
289 preserve occ info in rules.
292 substBndr :: Subst -> Var -> (Subst, Var)
294 | isTyVar bndr = substTyVarBndr subst bndr
295 | otherwise = substIdBndr subst subst bndr
297 substBndrs :: Subst -> [Var] -> (Subst, [Var])
298 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
300 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
301 -- Substitute a mutually recursive group
302 substRecBndrs subst bndrs
303 = (new_subst, new_bndrs)
304 where -- Here's the reason we need to pass rec_subst to subst_id
305 (new_subst, new_bndrs) = mapAccumL (substIdBndr new_subst) subst bndrs
310 substIdBndr :: Subst -- Substitution to use for the IdInfo
311 -> Subst -> Id -- Substitition and Id to transform
312 -> (Subst, Id) -- Transformed pair
313 -- NB: unfolding may be zapped
315 substIdBndr rec_subst subst@(Subst in_scope env tvs) old_id
316 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
318 id1 = uniqAway in_scope old_id -- id1 is cloned if necessary
319 id2 | no_type_change = id1
320 | otherwise = setIdType id1 (substTy subst old_ty)
322 old_ty = idType old_id
323 no_type_change = isEmptyVarEnv tvs ||
324 isEmptyVarSet (Type.tyVarsOfType old_ty)
326 -- new_id has the right IdInfo
327 -- The lazy-set is because we're in a loop here, with
328 -- rec_subst, when dealing with a mutually-recursive group
329 new_id = maybeModifyIdInfo mb_new_info id2
330 mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
331 -- NB: unfolding info may be zapped
333 -- Extend the substitution if the unique has changed
334 -- See the notes with substTyVarBndr for the delVarEnv
335 new_env | no_change = delVarEnv env old_id
336 | otherwise = extendVarEnv env old_id (Var new_id)
338 no_change = id1 == old_id
339 -- See Note [Extending the Subst]
340 -- *not* necessary to check mb_new_info and no_type_change
343 Now a variant that unconditionally allocates a new unique.
344 It also unconditionally zaps the OccInfo.
347 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
348 cloneIdBndr subst us old_id
349 = clone_id subst subst (old_id, uniqFromSupply us)
351 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
352 cloneIdBndrs subst us ids
353 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
355 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
356 cloneRecIdBndrs subst us ids
359 (subst', ids') = mapAccumL (clone_id subst') subst
360 (ids `zip` uniqsFromSupply us)
362 -- Just like substIdBndr, except that it always makes a new unique
363 -- It is given the unique to use
364 clone_id :: Subst -- Substitution for the IdInfo
365 -> Subst -> (Id, Unique) -- Substitition and Id to transform
366 -> (Subst, Id) -- Transformed pair
368 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
369 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
371 id1 = setVarUnique old_id uniq
372 id2 = substIdType subst id1
373 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
374 new_env = extendVarEnv env old_id (Var new_id)
378 %************************************************************************
382 %************************************************************************
384 For types we just call the corresponding function in Type, but we have
385 to repackage the substitution, from a Subst to a TvSubst
388 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
389 substTyVarBndr (Subst in_scope id_env tv_env) tv
390 = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
391 (TvSubst in_scope' tv_env', tv')
392 -> (Subst in_scope' id_env tv_env', tv')
394 substTy :: Subst -> Type -> Type
395 substTy (Subst in_scope _id_env tv_env) ty
396 = Type.substTy (TvSubst in_scope tv_env) ty
400 %************************************************************************
402 \section{IdInfo substitution}
404 %************************************************************************
407 substIdType :: Subst -> Id -> Id
408 substIdType subst@(Subst _ _ tv_env) id
409 | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
410 | otherwise = setIdType id (substTy subst old_ty)
411 -- The tyVarsOfType is cheaper than it looks
412 -- because we cache the free tyvars of the type
413 -- in a Note in the id's type itself
418 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
419 -- Always zaps the unfolding, to save substitution work
420 substIdInfo subst new_id info
421 | nothing_to_do = Nothing
422 | otherwise = Just (info `setSpecInfo` substSpec subst new_id old_rules
423 `setWorkerInfo` substWorker subst old_wrkr
424 `setUnfoldingInfo` noUnfolding)
426 old_rules = specInfo info
427 old_wrkr = workerInfo info
428 nothing_to_do = isEmptySpecInfo old_rules &&
429 not (workerExists old_wrkr) &&
430 not (hasUnfolding (unfoldingInfo info))
434 substWorker :: Subst -> WorkerInfo -> WorkerInfo
435 -- Seq'ing on the returned WorkerInfo is enough to cause all the
436 -- substitutions to happen completely
438 substWorker _ NoWorker
440 substWorker subst (HasWorker w a)
441 = case lookupIdSubst subst w of
442 Var w1 -> HasWorker w1 a
443 other -> WARN( not (exprIsTrivial other), text "CoreSubst.substWorker:" <+> ppr w )
444 NoWorker -- Worker has got substituted away altogether
445 -- (This can happen if it's trivial,
446 -- via postInlineUnconditionally, hence warning)
449 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
451 substSpec subst new_fn spec@(SpecInfo rules rhs_fvs)
455 = seqSpecInfo new_rules `seq` new_rules
457 new_name = idName new_fn
458 new_rules = SpecInfo (map do_subst rules) (substVarSet subst rhs_fvs)
460 do_subst rule@(BuiltinRule {}) = rule
461 do_subst rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
462 = rule { ru_bndrs = bndrs',
463 ru_fn = new_name, -- Important: the function may have changed its name!
464 ru_args = map (substExpr subst') args,
465 ru_rhs = substExpr subst' rhs }
467 (subst', bndrs') = substBndrs subst bndrs
470 substVarSet :: Subst -> VarSet -> VarSet
471 substVarSet subst fvs
472 = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
475 | isId fv = exprFreeVars (lookupIdSubst subst fv)
476 | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)