Comments only
[ghc-hetmet.git] / compiler / coreSyn / CoreSubst.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Utility functions on @Core@ syntax
7
8 \begin{code}
9 module CoreSubst (
10         -- Substitution stuff
11         Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
12
13         deShadowBinds,
14         substTy, substExpr, substSpec, substWorker,
15         lookupIdSubst, lookupTvSubst, 
16
17         emptySubst, mkEmptySubst, mkSubst, substInScope, isEmptySubst, 
18         extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
19         extendSubstList, zapSubstEnv,
20         extendInScope, extendInScopeList, extendInScopeIds, 
21         isInScope,
22
23         -- Binders
24         substBndr, substBndrs, substRecBndrs,
25         cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs
26     ) where
27
28 #include "HsVersions.h"
29
30 import CoreSyn
31 import CoreFVs
32 import CoreUtils
33
34 import qualified Type
35 import Type     ( Type, TvSubst(..), TvSubstEnv )
36 import VarSet
37 import VarEnv
38 import Id
39 import Var      ( Var, TyVar, setVarUnique )
40 import IdInfo
41 import Unique
42 import UniqSupply
43 import Maybes
44 import Outputable
45 import PprCore          ()              -- Instances
46 import Util
47 import FastTypes
48 \end{code}
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection{Substitutions}
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 data Subst 
59   = Subst InScopeSet    -- Variables in in scope (both Ids and TyVars)
60                         -- *after* applying the substitution
61           IdSubstEnv    -- Substitution for Ids
62           TvSubstEnv    -- Substitution for TyVars
63
64         -- INVARIANT 1: The (domain of the) in-scope set is a superset
65         --              of the free vars of the range of the substitution
66         --              that might possibly clash with locally-bound variables
67         --              in the thing being substituted in.
68         -- This is what lets us deal with name capture properly
69         -- It's a hard invariant to check...
70         -- There are various ways of causing it to happen:
71         --      - arrange that the in-scope set really is all the things in scope
72         --      - arrange that it's the free vars of the range of the substitution
73         --      - make it empty because all the free vars of the subst are fresh,
74         --              and hence can't possibly clash.a
75         --
76         -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
77         --              Types.TvSubstEnv
78         --
79         -- INVARIANT 3: See Note [Extending the Subst]
80
81 {-
82 Note [Extending the Subst]
83 ~~~~~~~~~~~~~~~~~~~~~~~~~~
84 For a core Subst, which binds Ids as well, we make a different choice for Ids
85 than we do for TyVars.  
86
87 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
88
89 For Ids, we have a different invariant
90         The IdSubstEnv is extended *only* when the Unique on an Id changes
91         Otherwise, we just extend the InScopeSet
92
93 In consequence:
94
95 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
96
97 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr does nothing
98   (Note that the above rule for substIdBndr maintains this property.  If
99    the incoming envts are both empty, then substituting the type and
100    IdInfo can't change anything.)
101
102 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
103   it may contain non-trivial changes.  Example:
104         (/\a. \x:a. ...x...) Int
105   We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
106   so we only extend the in-scope set.  Then we must look up in the in-scope
107   set when we find the occurrence of x.
108
109 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
110
111 * For Ids, we change the IdInfo all the time (e.g. deleting the
112   unfolding), and adding it back later, so using the TyVar convention
113   would entail extending the substitution almost all the time
114
115 * The simplifier wants to look up in the in-scope set anyway, in case it 
116   can see a better unfolding from an enclosing case expression
117
118 * For TyVars, only coercion variables can possibly change, and they are 
119   easy to spot
120 -}
121
122 type IdSubstEnv = IdEnv CoreExpr
123
124 ----------------------------
125 isEmptySubst :: Subst -> Bool
126 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
127
128 emptySubst :: Subst
129 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
130
131 mkEmptySubst :: InScopeSet -> Subst
132 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
133
134 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
135 mkSubst in_scope tvs ids = Subst in_scope ids tvs
136
137 -- getTvSubst :: Subst -> TvSubst
138 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
139
140 -- getTvSubstEnv :: Subst -> TvSubstEnv
141 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
142 -- 
143 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
144 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
145
146 substInScope :: Subst -> InScopeSet
147 substInScope (Subst in_scope _ _) = in_scope
148
149 zapSubstEnv :: Subst -> Subst
150 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
151
152 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
153 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
154 extendIdSubst (Subst in_scope ids tvs) v r = Subst in_scope (extendVarEnv ids v r) tvs
155
156 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
157 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
158
159 extendTvSubst :: Subst -> TyVar -> Type -> Subst
160 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r) 
161
162 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
163 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
164
165 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
166 extendSubstList subst [] 
167   = subst
168 extendSubstList (Subst in_scope ids tvs) ((tv,Type ty):prs)
169   = ASSERT( isTyVar tv ) extendSubstList (Subst in_scope ids (extendVarEnv tvs tv ty)) prs
170 extendSubstList (Subst in_scope ids tvs) ((id,expr):prs)
171   = ASSERT( isId id ) extendSubstList (Subst in_scope (extendVarEnv ids id expr) tvs) prs
172
173 lookupIdSubst :: Subst -> Id -> CoreExpr
174 lookupIdSubst (Subst in_scope ids tvs) v 
175   | not (isLocalId v) = Var v
176   | Just e  <- lookupVarEnv ids       v = e
177   | Just v' <- lookupInScope in_scope v = Var v'
178         -- Vital! See Note [Extending the Subst]
179   | otherwise = WARN( True, ptext SLIT("CoreSubst.lookupIdSubst") <+> ppr v ) 
180                 Var v
181
182 lookupTvSubst :: Subst -> TyVar -> Type
183 lookupTvSubst (Subst _ ids tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
184
185 ------------------------------
186 isInScope :: Var -> Subst -> Bool
187 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
188
189 extendInScope :: Subst -> Var -> Subst
190 extendInScope (Subst in_scope ids tvs) v
191   = Subst (in_scope `extendInScopeSet` v) 
192           (ids `delVarEnv` v) (tvs `delVarEnv` v)
193
194 extendInScopeList :: Subst -> [Var] -> Subst
195 extendInScopeList (Subst in_scope ids tvs) vs
196   = Subst (in_scope `extendInScopeSetList` vs) 
197           (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
198
199 extendInScopeIds :: Subst -> [Id] -> Subst
200 extendInScopeIds (Subst in_scope ids tvs) vs 
201   = Subst (in_scope `extendInScopeSetList` vs) 
202           (ids `delVarEnvList` vs) tvs
203 \end{code}
204
205 Pretty printing, for debugging only
206
207 \begin{code}
208 instance Outputable Subst where
209   ppr (Subst in_scope ids tvs) 
210         =  ptext SLIT("<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
211         $$ ptext SLIT(" IdSubst   =") <+> ppr ids
212         $$ ptext SLIT(" TvSubst   =") <+> ppr tvs
213          <> char '>'
214 \end{code}
215
216
217 %************************************************************************
218 %*                                                                      *
219         Substituting expressions
220 %*                                                                      *
221 %************************************************************************
222
223 \begin{code}
224 substExpr :: Subst -> CoreExpr -> CoreExpr
225 substExpr subst expr
226   = go expr
227   where
228     go (Var v)         = lookupIdSubst subst v 
229     go (Type ty)       = Type (substTy subst ty)
230     go (Lit lit)       = Lit lit
231     go (App fun arg)   = App (go fun) (go arg)
232     go (Note note e)   = Note (go_note note) (go e)
233     go (Cast e co)     = Cast (go e) (substTy subst co)
234     go (Lam bndr body) = Lam bndr' (substExpr subst' body)
235                        where
236                          (subst', bndr') = substBndr subst bndr
237
238     go (Let bind body) = Let bind' (substExpr subst' body)
239                        where
240                          (subst', bind') = substBind subst bind
241
242     go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
243                                  where
244                                  (subst', bndr') = substBndr subst bndr
245
246     go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
247                                  where
248                                    (subst', bndrs') = substBndrs subst bndrs
249
250     go_note note             = note
251
252 substBind :: Subst -> CoreBind -> (Subst, CoreBind)
253 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (substExpr subst rhs))
254                                   where
255                                     (subst', bndr') = substBndr subst bndr
256
257 substBind subst (Rec pairs) = (subst', Rec pairs')
258                             where
259                                 (subst', bndrs') = substRecBndrs subst (map fst pairs)
260                                 pairs'  = bndrs' `zip` rhss'
261                                 rhss'   = map (substExpr subst' . snd) pairs
262 \end{code}
263
264 De-shadowing the program is sometimes a useful pre-pass.  It can be done simply
265 by running over the bindings with an empty substitution, becuase substitution
266 returns a result that has no-shadowing guaranteed.
267
268 (Actually, within a single *type* there might still be shadowing, because 
269 substType is a no-op for the empty substitution, but that's OK.)
270
271 \begin{code}
272 deShadowBinds :: [CoreBind] -> [CoreBind]
273 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
274 \end{code}
275
276
277 %************************************************************************
278 %*                                                                      *
279         Substituting binders
280 %*                                                                      *
281 %************************************************************************
282
283 Remember that substBndr and friends are used when doing expression
284 substitution only.  Their only business is substitution, so they
285 preserve all IdInfo (suitably substituted).  For example, we *want* to
286 preserve occ info in rules.
287
288 \begin{code}
289 substBndr :: Subst -> Var -> (Subst, Var)
290 substBndr subst bndr
291   | isTyVar bndr  = substTyVarBndr subst bndr
292   | otherwise     = substIdBndr subst subst bndr
293
294 substBndrs :: Subst -> [Var] -> (Subst, [Var])
295 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
296
297 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
298 -- Substitute a mutually recursive group
299 substRecBndrs subst bndrs 
300   = (new_subst, new_bndrs)
301   where         -- Here's the reason we need to pass rec_subst to subst_id
302     (new_subst, new_bndrs) = mapAccumL (substIdBndr new_subst) subst bndrs
303 \end{code}
304
305
306 \begin{code}
307 substIdBndr :: Subst            -- Substitution to use for the IdInfo
308             -> Subst -> Id      -- Substitition and Id to transform
309             -> (Subst, Id)      -- Transformed pair
310                                 -- NB: unfolding may be zapped
311
312 substIdBndr rec_subst subst@(Subst in_scope env tvs) old_id
313   = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
314   where
315     id1 = uniqAway in_scope old_id      -- id1 is cloned if necessary
316     id2 | no_type_change = id1
317         | otherwise      = setIdType id1 (substTy subst old_ty)
318
319     old_ty = idType old_id
320     no_type_change = isEmptyVarEnv tvs || 
321                      isEmptyVarSet (Type.tyVarsOfType old_ty)
322
323         -- new_id has the right IdInfo
324         -- The lazy-set is because we're in a loop here, with 
325         -- rec_subst, when dealing with a mutually-recursive group
326     new_id = maybeModifyIdInfo mb_new_info id2
327     mb_new_info = substIdInfo rec_subst (idInfo id2)
328         -- NB: unfolding info may be zapped
329
330         -- Extend the substitution if the unique has changed
331         -- See the notes with substTyVarBndr for the delVarEnv
332     new_env | no_change = delVarEnv env old_id
333             | otherwise = extendVarEnv env old_id (Var new_id)
334
335     no_change = id1 == old_id
336         -- See Note [Extending the Subst]
337         -- *not* necessary to check mb_new_info and no_type_change
338 \end{code}
339
340 Now a variant that unconditionally allocates a new unique.
341 It also unconditionally zaps the OccInfo.
342
343 \begin{code}
344 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
345 cloneIdBndr subst us old_id
346   = clone_id subst subst (old_id, uniqFromSupply us)
347
348 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
349 cloneIdBndrs subst us ids
350   = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
351
352 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
353 cloneRecIdBndrs subst us ids
354   = (subst', ids')
355   where
356     (subst', ids') = mapAccumL (clone_id subst') subst
357                                (ids `zip` uniqsFromSupply us)
358
359 -- Just like substIdBndr, except that it always makes a new unique
360 -- It is given the unique to use
361 clone_id    :: Subst                    -- Substitution for the IdInfo
362             -> Subst -> (Id, Unique)    -- Substitition and Id to transform
363             -> (Subst, Id)              -- Transformed pair
364
365 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
366   = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
367   where
368     id1     = setVarUnique old_id uniq
369     id2     = substIdType subst id1
370     new_id  = maybeModifyIdInfo (substIdInfo rec_subst (idInfo old_id)) id2
371     new_env = extendVarEnv env old_id (Var new_id)
372 \end{code}
373
374
375 %************************************************************************
376 %*                                                                      *
377                 Types
378 %*                                                                      *
379 %************************************************************************
380
381 For types we just call the corresponding function in Type, but we have
382 to repackage the substitution, from a Subst to a TvSubst
383
384 \begin{code}
385 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
386 substTyVarBndr (Subst in_scope id_env tv_env) tv
387   = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
388         (TvSubst in_scope' tv_env', tv') 
389            -> (Subst in_scope' id_env tv_env', tv')
390
391 substTy :: Subst -> Type -> Type 
392 substTy (Subst in_scope id_env tv_env) ty 
393   = Type.substTy (TvSubst in_scope tv_env) ty
394 \end{code}
395
396
397 %************************************************************************
398 %*                                                                      *
399 \section{IdInfo substitution}
400 %*                                                                      *
401 %************************************************************************
402
403 \begin{code}
404 substIdType :: Subst -> Id -> Id
405 substIdType subst@(Subst in_scope id_env tv_env) id
406   | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
407   | otherwise   = setIdType id (substTy subst old_ty)
408                 -- The tyVarsOfType is cheaper than it looks
409                 -- because we cache the free tyvars of the type
410                 -- in a Note in the id's type itself
411   where
412     old_ty = idType id
413
414 ------------------
415 substIdInfo :: Subst -> IdInfo -> Maybe IdInfo
416 -- Always zaps the unfolding, to save substitution work
417 substIdInfo  subst info
418   | nothing_to_do = Nothing
419   | otherwise     = Just (info `setSpecInfo`      substSpec  subst old_rules
420                                `setWorkerInfo`    substWorker subst old_wrkr
421                                `setUnfoldingInfo` noUnfolding)
422   where
423     old_rules     = specInfo info
424     old_wrkr      = workerInfo info
425     nothing_to_do = isEmptySpecInfo old_rules &&
426                     not (workerExists old_wrkr) &&
427                     not (hasUnfolding (unfoldingInfo info))
428     
429
430 ------------------
431 substWorker :: Subst -> WorkerInfo -> WorkerInfo
432         -- Seq'ing on the returned WorkerInfo is enough to cause all the 
433         -- substitutions to happen completely
434
435 substWorker subst NoWorker
436   = NoWorker
437 substWorker subst (HasWorker w a)
438   = case lookupIdSubst subst w of
439         Var w1 -> HasWorker w1 a
440         other  -> WARN( not (exprIsTrivial other), text "CoreSubst.substWorker:" <+> ppr w )
441                   NoWorker      -- Worker has got substituted away altogether
442                                 -- (This can happen if it's trivial, 
443                                 --  via postInlineUnconditionally, hence warning)
444
445 ------------------
446 substSpec :: Subst -> SpecInfo -> SpecInfo
447
448 substSpec subst spec@(SpecInfo rules rhs_fvs)
449   | isEmptySubst subst
450   = spec
451   | otherwise
452   = seqSpecInfo new_rules `seq` new_rules
453   where
454     new_rules = SpecInfo (map do_subst rules) (substVarSet subst rhs_fvs)
455
456     do_subst rule@(BuiltinRule {}) = rule
457     do_subst rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
458         = rule { ru_bndrs = bndrs',
459                  ru_args  = map (substExpr subst') args,
460                  ru_rhs   = substExpr subst' rhs }
461         where
462           (subst', bndrs') = substBndrs subst bndrs
463
464 ------------------
465 substVarSet subst fvs 
466   = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
467   where
468     subst_fv subst fv 
469         | isId fv   = exprFreeVars (lookupIdSubst subst fv)
470         | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)
471 \end{code}