Occurrence analyser takes account of the phase when handing RULES
[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         -- * Main data types
11         Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
12
13         -- ** Substituting into expressions and related types
14         deShadowBinds, substSpec, substRulesForImportedIds,
15         substTy, substExpr, substExprSC, substBind, substBindSC,
16         substUnfolding, substUnfoldingSC,
17         substUnfoldingSource, lookupIdSubst, lookupTvSubst, substIdOcc,
18
19         -- ** Operations on substitutions
20         emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst, 
21         extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
22         extendSubst, extendSubstList, zapSubstEnv,
23         extendInScope, extendInScopeList, extendInScopeIds, 
24         isInScope,
25
26         -- ** Substituting and cloning binders
27         substBndr, substBndrs, substRecBndrs,
28         cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs,
29
30         -- ** Simple expression optimiser
31         simpleOptPgm, simpleOptExpr
32     ) where
33
34 #include "HsVersions.h"
35
36 import CoreSyn
37 import CoreFVs
38 import CoreUtils
39 import PprCore
40 import OccurAnal( occurAnalyseExpr, occurAnalysePgm )
41
42 import qualified Type
43 import Type     ( Type, TvSubst(..), TvSubstEnv )
44 import Coercion    ( isIdentityCoercion )
45 import OptCoercion ( optCoercion )
46 import VarSet
47 import VarEnv
48 import Id
49 import Name     ( Name )
50 import Var      ( Var, TyVar, setVarUnique )
51 import IdInfo
52 import Unique
53 import UniqSupply
54 import Maybes
55 import ErrUtils
56 import DynFlags   ( DynFlags, DynFlag(..) )
57 import BasicTypes ( isAlwaysActive )
58 import Outputable
59 import PprCore          ()              -- Instances
60 import FastString
61
62 import Data.List
63 \end{code}
64
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection{Substitutions}
69 %*                                                                      *
70 %************************************************************************
71
72 \begin{code}
73 -- | A substitution environment, containing both 'Id' and 'TyVar' substitutions.
74 --
75 -- Some invariants apply to how you use the substitution:
76 --
77 -- 1. #in_scope_invariant# The in-scope set contains at least those 'Id's and 'TyVar's that will be in scope /after/
78 -- applying the substitution to a term. Precisely, the in-scope set must be a superset of the free vars of the
79 -- substitution range that might possibly clash with locally-bound variables in the thing being substituted in.
80 --
81 -- 2. #apply_once# You may apply the substitution only /once/
82 --
83 -- There are various ways of setting up the in-scope set such that the first of these invariants hold:
84 --
85 -- * Arrange that the in-scope set really is all the things in scope
86 --
87 -- * Arrange that it's the free vars of the range of the substitution
88 --
89 -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash
90 data Subst 
91   = Subst InScopeSet  -- Variables in in scope (both Ids and TyVars) /after/
92                       -- applying the substitution
93           IdSubstEnv  -- Substitution for Ids
94           TvSubstEnv  -- Substitution for TyVars
95
96         -- INVARIANT 1: See #in_scope_invariant#
97         -- This is what lets us deal with name capture properly
98         -- It's a hard invariant to check...
99         --
100         -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
101         --              Types.TvSubstEnv
102         --
103         -- INVARIANT 3: See Note [Extending the Subst]
104 \end{code}
105
106 Note [Extending the Subst]
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~
108 For a core Subst, which binds Ids as well, we make a different choice for Ids
109 than we do for TyVars.  
110
111 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
112
113 For Ids, we have a different invariant
114         The IdSubstEnv is extended *only* when the Unique on an Id changes
115         Otherwise, we just extend the InScopeSet
116
117 In consequence:
118
119 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr would be a
120   no-op, so substExprSC ("short cut") does nothing.
121
122   However, substExpr still goes ahead and substitutes.  Reason: we may
123   want to replace existing Ids with new ones from the in-scope set, to
124   avoid space leaks.
125
126 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
127
128 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
129   it may contain non-trivial changes.  Example:
130         (/\a. \x:a. ...x...) Int
131   We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
132   so we only extend the in-scope set.  Then we must look up in the in-scope
133   set when we find the occurrence of x.
134
135 * The requirement to look up the Id in the in-scope set means that we
136   must NOT take no-op short cut when the IdSubst is empty.
137   We must still look up every Id in the in-scope set.
138
139 * (However, we don't need to do so for expressions found in the IdSubst
140   itself, whose range is assumed to be correct wrt the in-scope set.)
141
142 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
143
144 * For Ids, we change the IdInfo all the time (e.g. deleting the
145   unfolding), and adding it back later, so using the TyVar convention
146   would entail extending the substitution almost all the time
147
148 * The simplifier wants to look up in the in-scope set anyway, in case it 
149   can see a better unfolding from an enclosing case expression
150
151 * For TyVars, only coercion variables can possibly change, and they are 
152   easy to spot
153
154 \begin{code}
155 -- | An environment for substituting for 'Id's
156 type IdSubstEnv = IdEnv CoreExpr
157
158 ----------------------------
159 isEmptySubst :: Subst -> Bool
160 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
161
162 emptySubst :: Subst
163 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
164
165 mkEmptySubst :: InScopeSet -> Subst
166 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
167
168 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
169 mkSubst in_scope tvs ids = Subst in_scope ids tvs
170
171 -- getTvSubst :: Subst -> TvSubst
172 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
173
174 -- getTvSubstEnv :: Subst -> TvSubstEnv
175 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
176 -- 
177 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
178 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
179
180 -- | Find the in-scope set: see "CoreSubst#in_scope_invariant"
181 substInScope :: Subst -> InScopeSet
182 substInScope (Subst in_scope _ _) = in_scope
183
184 -- | Remove all substitutions for 'Id's and 'Var's that might have been built up
185 -- while preserving the in-scope set
186 zapSubstEnv :: Subst -> Subst
187 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
188
189 -- | Add a substitution for an 'Id' to the 'Subst': you must ensure that the in-scope set is
190 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
191 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
192 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
193 extendIdSubst (Subst in_scope ids tvs) v r = Subst in_scope (extendVarEnv ids v r) tvs
194
195 -- | Adds multiple 'Id' substitutions to the 'Subst': see also 'extendIdSubst'
196 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
197 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
198
199 -- | Add a substitution for a 'TyVar' to the 'Subst': you must ensure that the in-scope set is
200 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
201 extendTvSubst :: Subst -> TyVar -> Type -> Subst
202 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r) 
203
204 -- | Adds multiple 'TyVar' substitutions to the 'Subst': see also 'extendTvSubst'
205 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
206 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
207
208 -- | Add a substitution for a 'TyVar' or 'Id' as appropriate to the 'Var' being added. See also
209 -- 'extendIdSubst' and 'extendTvSubst'
210 extendSubst :: Subst -> Var -> CoreArg -> Subst
211 extendSubst (Subst in_scope ids tvs) tv (Type ty)
212   = ASSERT( isTyCoVar tv ) Subst in_scope ids (extendVarEnv tvs tv ty)
213 extendSubst (Subst in_scope ids tvs) id expr
214   = ASSERT( isId id ) Subst in_scope (extendVarEnv ids id expr) tvs
215
216 -- | Add a substitution for a 'TyVar' or 'Id' as appropriate to all the 'Var's being added. See also 'extendSubst'
217 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
218 extendSubstList subst []              = subst
219 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
220
221 -- | Find the substitution for an 'Id' in the 'Subst'
222 lookupIdSubst :: SDoc -> Subst -> Id -> CoreExpr
223 lookupIdSubst doc (Subst in_scope ids _) v
224   | not (isLocalId v) = Var v
225   | Just e  <- lookupVarEnv ids       v = e
226   | Just v' <- lookupInScope in_scope v = Var v'
227         -- Vital! See Note [Extending the Subst]
228   | otherwise = WARN( True, ptext (sLit "CoreSubst.lookupIdSubst") <+> ppr v $$ ppr in_scope $$ doc) 
229                 Var v
230
231 -- | Find the substitution for a 'TyVar' in the 'Subst'
232 lookupTvSubst :: Subst -> TyVar -> Type
233 lookupTvSubst (Subst _ _ tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
234
235 -- | Simultaneously substitute for a bunch of variables
236 --   No left-right shadowing
237 --   ie the substitution for   (\x \y. e) a1 a2
238 --      so neither x nor y scope over a1 a2
239 mkOpenSubst :: InScopeSet -> [(Var,CoreArg)] -> Subst
240 mkOpenSubst in_scope pairs = Subst in_scope
241                                    (mkVarEnv [(id,e)  | (id, e) <- pairs, isId id])
242                                    (mkVarEnv [(tv,ty) | (tv, Type ty) <- pairs])
243
244 ------------------------------
245 isInScope :: Var -> Subst -> Bool
246 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
247
248 -- | Add the 'Var' to the in-scope set: as a side effect, removes any existing substitutions for it
249 extendInScope :: Subst -> Var -> Subst
250 extendInScope (Subst in_scope ids tvs) v
251   = Subst (in_scope `extendInScopeSet` v) 
252           (ids `delVarEnv` v) (tvs `delVarEnv` v)
253
254 -- | Add the 'Var's to the in-scope set: see also 'extendInScope'
255 extendInScopeList :: Subst -> [Var] -> Subst
256 extendInScopeList (Subst in_scope ids tvs) vs
257   = Subst (in_scope `extendInScopeSetList` vs) 
258           (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
259
260 -- | Optimized version of 'extendInScopeList' that can be used if you are certain 
261 -- all the things being added are 'Id's and hence none are 'TyVar's
262 extendInScopeIds :: Subst -> [Id] -> Subst
263 extendInScopeIds (Subst in_scope ids tvs) vs 
264   = Subst (in_scope `extendInScopeSetList` vs) 
265           (ids `delVarEnvList` vs) tvs
266 \end{code}
267
268 Pretty printing, for debugging only
269
270 \begin{code}
271 instance Outputable Subst where
272   ppr (Subst in_scope ids tvs) 
273         =  ptext (sLit "<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
274         $$ ptext (sLit " IdSubst   =") <+> ppr ids
275         $$ ptext (sLit " TvSubst   =") <+> ppr tvs
276          <> char '>'
277 \end{code}
278
279
280 %************************************************************************
281 %*                                                                      *
282         Substituting expressions
283 %*                                                                      *
284 %************************************************************************
285
286 \begin{code}
287 -- | Apply a substititon to an entire 'CoreExpr'. Rememeber, you may only 
288 -- apply the substitution /once/: see "CoreSubst#apply_once"
289 --
290 -- Do *not* attempt to short-cut in the case of an empty substitution!
291 -- See Note [Extending the Subst]
292 substExprSC :: SDoc -> Subst -> CoreExpr -> CoreExpr
293 substExprSC _doc subst orig_expr
294   | isEmptySubst subst = orig_expr
295   | otherwise          = -- pprTrace "enter subst-expr" (doc $$ ppr orig_expr) $
296                          subst_expr subst orig_expr
297
298 substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr
299 substExpr _doc subst orig_expr = subst_expr subst orig_expr
300
301 subst_expr :: Subst -> CoreExpr -> CoreExpr
302 subst_expr subst expr
303   = go expr
304   where
305     go (Var v)         = lookupIdSubst (text "subst_expr") subst v 
306     go (Type ty)       = Type (substTy subst ty)
307     go (Lit lit)       = Lit lit
308     go (App fun arg)   = App (go fun) (go arg)
309     go (Note note e)   = Note (go_note note) (go e)
310     go (Cast e co) 
311       | isIdentityCoercion co' = go e
312       | otherwise              = Cast (go e) co'
313       where
314         co' = optCoercion (getTvSubst subst) co
315         -- Optimise coercions as we go; this is good, for example
316         -- in the RHS of rules, which are only substituted in
317
318     go (Lam bndr body) = Lam bndr' (subst_expr subst' body)
319                        where
320                          (subst', bndr') = substBndr subst bndr
321
322     go (Let bind body) = Let bind' (subst_expr subst' body)
323                        where
324                          (subst', bind') = substBind subst bind
325
326     go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
327                                  where
328                                  (subst', bndr') = substBndr subst bndr
329
330     go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr subst' rhs)
331                                  where
332                                    (subst', bndrs') = substBndrs subst bndrs
333
334     go_note note             = note
335
336 -- | Apply a substititon to an entire 'CoreBind', additionally returning an updated 'Subst'
337 -- that should be used by subsequent substitutons.
338 substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind)
339
340 substBindSC subst bind    -- Short-cut if the substitution is empty
341   | not (isEmptySubst subst)
342   = substBind subst bind
343   | otherwise
344   = case bind of
345        NonRec bndr rhs -> (subst', NonRec bndr' rhs)
346           where
347             (subst', bndr') = substBndr subst bndr
348        Rec pairs -> (subst', Rec (bndrs' `zip` rhss'))
349           where
350             (bndrs, rhss)    = unzip pairs
351             (subst', bndrs') = substRecBndrs subst bndrs
352             rhss' | isEmptySubst subst' = rhss
353                   | otherwise           = map (subst_expr subst') rhss
354
355 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (subst_expr subst rhs))
356                                   where
357                                     (subst', bndr') = substBndr subst bndr
358
359 substBind subst (Rec pairs) = (subst', Rec (bndrs' `zip` rhss'))
360                             where
361                                 (bndrs, rhss)    = unzip pairs
362                                 (subst', bndrs') = substRecBndrs subst bndrs
363                                 rhss' = map (subst_expr subst') rhss
364 \end{code}
365
366 \begin{code}
367 -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply
368 -- by running over the bindings with an empty substitution, becuase substitution
369 -- returns a result that has no-shadowing guaranteed.
370 --
371 -- (Actually, within a single /type/ there might still be shadowing, because 
372 -- 'substTy' is a no-op for the empty substitution, but that's probably OK.)
373 --
374 -- [Aug 09] This function is not used in GHC at the moment, but seems so 
375 --          short and simple that I'm going to leave it here
376 deShadowBinds :: [CoreBind] -> [CoreBind]
377 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
378 \end{code}
379
380
381 %************************************************************************
382 %*                                                                      *
383         Substituting binders
384 %*                                                                      *
385 %************************************************************************
386
387 Remember that substBndr and friends are used when doing expression
388 substitution only.  Their only business is substitution, so they
389 preserve all IdInfo (suitably substituted).  For example, we *want* to
390 preserve occ info in rules.
391
392 \begin{code}
393 -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning
394 -- the result and an updated 'Subst' that should be used by subsequent substitutons.
395 -- 'IdInfo' is preserved by this process, although it is substituted into appropriately.
396 substBndr :: Subst -> Var -> (Subst, Var)
397 substBndr subst bndr
398   | isTyCoVar bndr  = substTyVarBndr subst bndr
399   | otherwise       = substIdBndr (text "var-bndr") subst subst bndr
400
401 -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right
402 substBndrs :: Subst -> [Var] -> (Subst, [Var])
403 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
404
405 -- | Substitute in a mutually recursive group of 'Id's
406 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
407 substRecBndrs subst bndrs 
408   = (new_subst, new_bndrs)
409   where         -- Here's the reason we need to pass rec_subst to subst_id
410     (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs
411 \end{code}
412
413
414 \begin{code}
415 substIdBndr :: SDoc 
416             -> Subst            -- ^ Substitution to use for the IdInfo
417             -> Subst -> Id      -- ^ Substitition and Id to transform
418             -> (Subst, Id)      -- ^ Transformed pair
419                                 -- NB: unfolding may be zapped
420
421 substIdBndr _doc rec_subst subst@(Subst in_scope env tvs) old_id
422   = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $
423     (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
424   where
425     id1 = uniqAway in_scope old_id      -- id1 is cloned if necessary
426     id2 | no_type_change = id1
427         | otherwise      = setIdType id1 (substTy subst old_ty)
428
429     old_ty = idType old_id
430     no_type_change = isEmptyVarEnv tvs || 
431                      isEmptyVarSet (Type.tyVarsOfType old_ty)
432
433         -- new_id has the right IdInfo
434         -- The lazy-set is because we're in a loop here, with 
435         -- rec_subst, when dealing with a mutually-recursive group
436     new_id = maybeModifyIdInfo mb_new_info id2
437     mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
438         -- NB: unfolding info may be zapped
439
440         -- Extend the substitution if the unique has changed
441         -- See the notes with substTyVarBndr for the delVarEnv
442     new_env | no_change = delVarEnv env old_id
443             | otherwise = extendVarEnv env old_id (Var new_id)
444
445     no_change = id1 == old_id
446         -- See Note [Extending the Subst]
447         -- it's /not/ necessary to check mb_new_info and no_type_change
448 \end{code}
449
450 Now a variant that unconditionally allocates a new unique.
451 It also unconditionally zaps the OccInfo.
452
453 \begin{code}
454 -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for
455 -- each variable in its output.  It substitutes the IdInfo though.
456 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
457 cloneIdBndr subst us old_id
458   = clone_id subst subst (old_id, uniqFromSupply us)
459
460 -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final
461 -- substitution from left to right
462 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
463 cloneIdBndrs subst us ids
464   = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
465
466 -- | Clone a mutually recursive group of 'Id's
467 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
468 cloneRecIdBndrs subst us ids
469   = (subst', ids')
470   where
471     (subst', ids') = mapAccumL (clone_id subst') subst
472                                (ids `zip` uniqsFromSupply us)
473
474 -- Just like substIdBndr, except that it always makes a new unique
475 -- It is given the unique to use
476 clone_id    :: Subst                    -- Substitution for the IdInfo
477             -> Subst -> (Id, Unique)    -- Substitition and Id to transform
478             -> (Subst, Id)              -- Transformed pair
479
480 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
481   = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
482   where
483     id1     = setVarUnique old_id uniq
484     id2     = substIdType subst id1
485     new_id  = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
486     new_env = extendVarEnv env old_id (Var new_id)
487 \end{code}
488
489
490 %************************************************************************
491 %*                                                                      *
492                 Types
493 %*                                                                      *
494 %************************************************************************
495
496 For types we just call the corresponding function in Type, but we have
497 to repackage the substitution, from a Subst to a TvSubst
498
499 \begin{code}
500 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
501 substTyVarBndr (Subst in_scope id_env tv_env) tv
502   = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
503         (TvSubst in_scope' tv_env', tv') 
504            -> (Subst in_scope' id_env tv_env', tv')
505
506 -- | See 'Type.substTy'
507 substTy :: Subst -> Type -> Type 
508 substTy subst ty = Type.substTy (getTvSubst subst) ty
509
510 getTvSubst :: Subst -> TvSubst
511 getTvSubst (Subst in_scope _id_env tv_env) = TvSubst in_scope tv_env
512 \end{code}
513
514
515 %************************************************************************
516 %*                                                                      *
517 \section{IdInfo substitution}
518 %*                                                                      *
519 %************************************************************************
520
521 \begin{code}
522 substIdType :: Subst -> Id -> Id
523 substIdType subst@(Subst _ _ tv_env) id
524   | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
525   | otherwise   = setIdType id (substTy subst old_ty)
526                 -- The tyVarsOfType is cheaper than it looks
527                 -- because we cache the free tyvars of the type
528                 -- in a Note in the id's type itself
529   where
530     old_ty = idType id
531
532 ------------------
533 -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'.
534 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
535 substIdInfo subst new_id info
536   | nothing_to_do = Nothing
537   | otherwise     = Just (info `setSpecInfo`      substSpec subst new_id old_rules
538                                `setUnfoldingInfo` substUnfolding subst old_unf)
539   where
540     old_rules     = specInfo info
541     old_unf       = unfoldingInfo info
542     nothing_to_do = isEmptySpecInfo old_rules && isClosedUnfolding old_unf
543     
544
545 ------------------
546 -- | Substitutes for the 'Id's within an unfolding
547 substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding
548         -- Seq'ing on the returned Unfolding is enough to cause
549         -- all the substitutions to happen completely
550
551 substUnfoldingSC subst unf       -- Short-cut version
552   | isEmptySubst subst = unf
553   | otherwise          = substUnfolding subst unf
554
555 substUnfolding subst (DFunUnfolding ar con args)
556   = DFunUnfolding ar con (map (substExpr (text "dfun-unf") subst) args)
557
558 substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src })
559         -- Retain an InlineRule!
560   | not (isStableSource src)  -- Zap an unstable unfolding, to save substitution work
561   = NoUnfolding
562   | otherwise                 -- But keep a stable one!
563   = seqExpr new_tmpl `seq` 
564     new_src `seq`
565     unf { uf_tmpl = new_tmpl, uf_src = new_src }
566   where
567     new_tmpl = substExpr (text "subst-unf") subst tmpl
568     new_src  = substUnfoldingSource subst src
569
570 substUnfolding _ unf = unf      -- NoUnfolding, OtherCon
571
572 -------------------
573 substUnfoldingSource :: Subst -> UnfoldingSource -> UnfoldingSource
574 substUnfoldingSource (Subst in_scope ids _) (InlineWrapper wkr)
575   | Just wkr_expr <- lookupVarEnv ids wkr 
576   = case wkr_expr of
577       Var w1 -> InlineWrapper w1
578       _other -> -- WARN( True, text "Interesting! CoreSubst.substWorker1:" <+> ppr wkr 
579                 --             <+> ifPprDebug (equals <+> ppr wkr_expr) )   
580                               -- Note [Worker inlining]
581                 InlineStable  -- It's not a wrapper any more, but still inline it!
582
583   | Just w1  <- lookupInScope in_scope wkr = InlineWrapper w1
584   | otherwise = -- WARN( True, text "Interesting! CoreSubst.substWorker2:" <+> ppr wkr )
585                 -- This can legitimately happen.  The worker has been inlined and
586                 -- dropped as dead code, because we don't treat the UnfoldingSource
587                 -- as an "occurrence".
588                 -- Note [Worker inlining]
589                 InlineStable
590
591 substUnfoldingSource _ src = src
592
593 ------------------
594 substIdOcc :: Subst -> Id -> Id
595 -- These Ids should not be substituted to non-Ids
596 substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of
597                         Var v' -> v'
598                         other  -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst])
599
600 ------------------
601 -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id'
602 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
603 substSpec subst new_id (SpecInfo rules rhs_fvs)
604   = seqSpecInfo new_spec `seq` new_spec
605   where
606     subst_ru_fn = const (idName new_id)
607     new_spec = SpecInfo (map (substRule subst subst_ru_fn) rules)
608                          (substVarSet subst rhs_fvs)
609
610 ------------------
611 substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule]
612 substRulesForImportedIds subst rules 
613   = map (substRule subst not_needed) rules
614   where
615     not_needed name = pprPanic "substRulesForImportedIds" (ppr name)
616
617 ------------------
618 substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule
619
620 -- The subst_ru_fn argument is applied to substitute the ru_fn field
621 -- of the rule:
622 --    - Rules for *imported* Ids never change ru_fn
623 --    - Rules for *local* Ids are in the IdInfo for that Id,
624 --      and the ru_fn field is simply replaced by the new name 
625 --      of the Id
626
627 substRule _ _ rule@(BuiltinRule {}) = rule
628 substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args
629                                        , ru_fn = fn_name, ru_rhs = rhs
630                                        , ru_local = is_local })
631   = rule { ru_bndrs = bndrs', 
632            ru_fn    = if is_local 
633                         then subst_ru_fn fn_name 
634                         else fn_name,
635            ru_args  = map (substExpr (text "subst-rule" <+> ppr fn_name) subst') args,
636            ru_rhs   = substExpr (text "subst-rule" <+> ppr fn_name) subst' rhs }
637   where
638     (subst', bndrs') = substBndrs subst bndrs
639
640 ------------------
641 substVarSet :: Subst -> VarSet -> VarSet
642 substVarSet subst fvs 
643   = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
644   where
645     subst_fv subst fv 
646         | isId fv   = exprFreeVars (lookupIdSubst (text "substVarSet") subst fv)
647         | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)
648 \end{code}
649
650 Note [Worker inlining]
651 ~~~~~~~~~~~~~~~~~~~~~~
652 A worker can get sustituted away entirely.
653         - it might be trivial
654         - it might simply be very small
655 We do not treat an InlWrapper as an 'occurrence' in the occurence 
656 analyser, so it's possible that the worker is not even in scope any more.
657
658 In all all these cases we simply drop the special case, returning to
659 InlVanilla.  The WARN is just so I can see if it happens a lot.
660
661
662 %************************************************************************
663 %*                                                                      *
664         The Very Simple Optimiser
665 %*                                                                      *
666 %************************************************************************
667
668 \begin{code}
669 simpleOptExpr :: CoreExpr -> CoreExpr
670 -- Do simple optimisation on an expression
671 -- The optimisation is very straightforward: just
672 -- inline non-recursive bindings that are used only once, 
673 -- or where the RHS is trivial
674 --
675 -- The result is NOT guaranteed occurence-analysed, becuase
676 -- in  (let x = y in ....) we substitute for x; so y's occ-info
677 -- may change radically
678
679 simpleOptExpr expr
680   = -- pprTrace "simpleOptExpr" (ppr init_subst $$ ppr expr)
681     simple_opt_expr init_subst (occurAnalyseExpr expr)
682   where
683     init_subst = mkEmptySubst (mkInScopeSet (exprFreeVars expr))
684         -- It's potentially important to make a proper in-scope set
685         -- Consider  let x = ..y.. in \y. ...x...
686         -- Then we should remember to clone y before substituting
687         -- for x.  It's very unlikely to occur, because we probably
688         -- won't *be* substituting for x if it occurs inside a
689         -- lambda.  
690         --
691         -- It's a bit painful to call exprFreeVars, because it makes
692         -- three passes instead of two (occ-anal, and go)
693
694 ----------------------
695 simpleOptPgm :: DynFlags -> [CoreBind] -> [CoreRule] -> IO ([CoreBind], [CoreRule])
696 simpleOptPgm dflags binds rules
697   = do { dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis"
698                        (pprCoreBindings occ_anald_binds);
699
700        ; return (reverse binds', substRulesForImportedIds subst' rules) }
701   where
702     occ_anald_binds  = occurAnalysePgm Nothing {- No rules active -}
703                                        rules binds
704     (subst', binds') = foldl do_one (emptySubst, []) occ_anald_binds
705                        
706     do_one (subst, binds') bind 
707       = case simple_opt_bind subst bind of
708           (subst', Nothing)    -> (subst', binds')
709           (subst', Just bind') -> (subst', bind':binds')
710
711 ----------------------
712 type InVar   = Var
713 type OutVar  = Var
714 type InId    = Id
715 type OutId   = Id
716 type InExpr  = CoreExpr
717 type OutExpr = CoreExpr
718
719 -- In these functions the substitution maps InVar -> OutExpr
720
721 ----------------------
722 simple_opt_expr :: Subst -> InExpr -> OutExpr
723 simple_opt_expr subst expr
724   = go expr
725   where
726     go (Var v)          = lookupIdSubst (text "simpleOptExpr") subst v
727     go (App e1 e2)      = simple_app subst e1 [go e2]
728     go (Type ty)        = Type (substTy subst ty)
729     go (Lit lit)        = Lit lit
730     go (Note note e)    = Note note (go e)
731     go (Cast e co)      | isIdentityCoercion co' = go e
732                         | otherwise              = Cast (go e) co' 
733                         where
734                           co' = substTy subst co
735
736     go (Let bind body) = case simple_opt_bind subst bind of
737                            (subst', Nothing)   -> simple_opt_expr subst' body
738                            (subst', Just bind) -> Let bind (simple_opt_expr subst' body)
739
740     go lam@(Lam {})     = go_lam [] subst lam
741     go (Case e b ty as) = Case (go e) b' (substTy subst ty)
742                                (map (go_alt subst') as)
743                         where
744                           (subst', b') = subst_opt_bndr subst b
745
746     ----------------------
747     go_alt subst (con, bndrs, rhs) 
748       = (con, bndrs', simple_opt_expr subst' rhs)
749       where
750         (subst', bndrs') = subst_opt_bndrs subst bndrs
751
752     ----------------------
753     -- go_lam tries eta reduction
754     go_lam bs' subst (Lam b e) 
755        = go_lam (b':bs') subst' e
756        where
757          (subst', b') = subst_opt_bndr subst b
758     go_lam bs' subst e 
759        | Just etad_e <- tryEtaReduce bs e' = etad_e
760        | otherwise                         = mkLams bs e'
761        where
762          bs = reverse bs'
763          e' = simple_opt_expr subst e
764
765 ----------------------
766 -- simple_app collects arguments for beta reduction
767 simple_app :: Subst -> InExpr -> [OutExpr] -> CoreExpr
768 simple_app subst (App e1 e2) as   
769   = simple_app subst e1 (simple_opt_expr subst e2 : as)
770 simple_app subst (Lam b e) (a:as) 
771   = case maybe_substitute subst b a of
772       Just ext_subst -> simple_app ext_subst e as
773       Nothing        -> Let (NonRec b2 a) (simple_app subst' e as)
774   where
775     (subst', b') = subst_opt_bndr subst b
776     b2 = add_info subst' b b'
777 simple_app subst e as
778   = foldl App (simple_opt_expr subst e) as
779
780 ----------------------
781 simple_opt_bind :: Subst -> CoreBind -> (Subst, Maybe CoreBind)
782 simple_opt_bind subst (Rec prs)
783   = (subst'', Just (Rec (reverse rev_prs')))
784   where
785     (subst', bndrs')    = subst_opt_bndrs subst (map fst prs)
786     (subst'', rev_prs') = foldl do_pr (subst', []) (prs `zip` bndrs')
787     do_pr (subst, prs) ((b,r), b') 
788        = case maybe_substitute subst b r2 of
789            Just subst' -> (subst', prs)
790            Nothing     -> (subst,  (b2,r2):prs)
791        where
792          b2 = add_info subst b b'
793          r2 = simple_opt_expr subst r
794
795 simple_opt_bind subst (NonRec b r)
796   = case maybe_substitute subst b r' of
797       Just ext_subst -> (ext_subst, Nothing)
798       Nothing        -> (subst', Just (NonRec b2 r'))
799   where
800     r' = simple_opt_expr subst r
801     (subst', b') = subst_opt_bndr subst b
802     b2 = add_info subst' b b'
803
804 ----------------------
805 maybe_substitute :: Subst -> InVar -> OutExpr -> Maybe Subst
806     -- (maybe_substitute subst in_var out_rhs)  
807     --   either extends subst with (in_var -> out_rhs)
808     --   or     returns Nothing
809 maybe_substitute subst b r
810   | Type ty <- r        -- let a::* = TYPE ty in <body>
811   = ASSERT( isTyCoVar b )
812     Just (extendTvSubst subst b ty)
813
814   | isId b              -- let x = e in <body>
815   , safe_to_inline (idOccInfo b) 
816   , isAlwaysActive (idInlineActivation b)       -- Note [Inline prag in simplOpt]
817   , not (isStableUnfolding (idUnfolding b))
818   , not (isExportedId b)
819   = Just (extendIdSubst subst b r)
820   
821   | otherwise
822   = Nothing
823   where
824         -- Unconditionally safe to inline
825     safe_to_inline :: OccInfo -> Bool
826     safe_to_inline (IAmALoopBreaker {})     = False
827     safe_to_inline IAmDead                  = True
828     safe_to_inline (OneOcc in_lam one_br _) = (not in_lam && one_br) || exprIsTrivial r
829     safe_to_inline NoOccInfo                = exprIsTrivial r
830
831 ----------------------
832 subst_opt_bndr :: Subst -> InVar -> (Subst, OutVar)
833 subst_opt_bndr subst bndr
834   | isTyCoVar bndr  = substTyVarBndr subst bndr
835   | otherwise       = subst_opt_id_bndr subst bndr
836
837 subst_opt_id_bndr :: Subst -> InId -> (Subst, OutId)
838 -- Nuke all fragile IdInfo, unfolding, and RULES; 
839 --    it gets added back later by add_info
840 -- Rather like SimplEnv.substIdBndr
841 --
842 -- It's important to zap fragile OccInfo (which CoreSubst.SubstIdBndr 
843 -- carefully does not do) because simplOptExpr invalidates it
844
845 subst_opt_id_bndr subst@(Subst in_scope id_subst tv_subst) old_id
846   = (Subst new_in_scope new_id_subst tv_subst, new_id)
847   where
848     id1    = uniqAway in_scope old_id
849     id2    = setIdType id1 (substTy subst (idType old_id))
850     new_id = zapFragileIdInfo id2       -- Zaps rules, worker-info, unfolding
851                                         -- and fragile OccInfo
852     new_in_scope = in_scope `extendInScopeSet` new_id
853
854         -- Extend the substitution if the unique has changed,
855         -- or there's some useful occurrence information
856         -- See the notes with substTyVarBndr for the delSubstEnv
857     new_id_subst | new_id /= old_id
858                  = extendVarEnv id_subst old_id (Var new_id)
859                  | otherwise 
860                  = delVarEnv id_subst old_id
861
862 ----------------------
863 subst_opt_bndrs :: Subst -> [InVar] -> (Subst, [OutVar])
864 subst_opt_bndrs subst bndrs
865   = mapAccumL subst_opt_bndr subst bndrs
866
867 ----------------------
868 add_info :: Subst -> InVar -> OutVar -> OutVar
869 add_info subst old_bndr new_bndr 
870  | isTyCoVar old_bndr = new_bndr
871  | otherwise          = maybeModifyIdInfo mb_new_info new_bndr
872  where
873    mb_new_info = substIdInfo subst new_bndr (idInfo old_bndr)
874 \end{code}
875
876 Note [Inline prag in simplOpt]
877 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
878 If there's an INLINE/NOINLINE pragma that restricts the phase in 
879 which the binder can be inlined, we don't inline here; after all,
880 we don't know what phase we're in.  Here's an example
881
882   foo :: Int -> Int -> Int
883   {-# INLINE foo #-}
884   foo m n = inner m
885      where
886        {-# INLINE [1] inner #-}
887        inner m = m+n
888
889   bar :: Int -> Int
890   bar n = foo n 1
891
892 When inlining 'foo' in 'bar' we want the let-binding for 'inner' 
893 to remain visible until Phase 1
894