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