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