2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
8 InId, InBind, InExpr, InAlt, InArg, InType, InBndr,
9 OutId, OutTyVar, OutBind, OutExpr, OutAlt, OutArg, OutType, OutBndr,
10 InCoercion, OutCoercion,
12 -- The simplifier mode
16 SwitchChecker, SwitchResult(..), getSwitchChecker, getSimplIntSwitch,
17 isAmongSimpl, intSwitchSet, switchIsOn,
19 setEnclosingCC, getEnclosingCC,
22 SimplEnv(..), pprSimplEnv, -- Temp not abstract
23 mkSimplEnv, extendIdSubst, SimplEnv.extendTvSubst,
24 zapSubstEnv, setSubstEnv,
25 getInScope, setInScope, setInScopeSet, modifyInScope, addNewInScopeIds,
28 SimplSR(..), mkContEx, substId, lookupRecBndr,
30 simplNonRecBndr, simplRecBndrs, simplLamBndr, simplLamBndrs,
31 simplBinder, simplBinders, addBndrRules,
32 substExpr, substWorker, substTy,
35 Floats, emptyFloats, isEmptyFloats, addNonRec, addFloats, extendFloats,
36 wrapFloats, floatBinds, setFloats, zapFloats, addRecFloats,
37 doFloatFromRhs, getFloats
40 #include "HsVersions.h"
52 import qualified CoreSubst ( Subst, mkSubst, substExpr, substSpec, substWorker )
53 import qualified Type ( substTy, substTyVarBndr )
54 import Type hiding ( substTy, substTyVarBndr )
65 %************************************************************************
67 \subsection[Simplify-types]{Type declarations}
69 %************************************************************************
72 type InBndr = CoreBndr
73 type InId = Id -- Not yet cloned
74 type InType = Type -- Ditto
75 type InBind = CoreBind
76 type InExpr = CoreExpr
79 type InCoercion = Coercion
81 type OutBndr = CoreBndr
82 type OutId = Id -- Cloned
83 type OutTyVar = TyVar -- Cloned
84 type OutType = Type -- Cloned
85 type OutCoercion = Coercion
86 type OutBind = CoreBind
87 type OutExpr = CoreExpr
92 %************************************************************************
94 \subsubsection{The @SimplEnv@ type}
96 %************************************************************************
102 seMode :: SimplifierMode,
103 seChkr :: SwitchChecker,
104 seCC :: CostCentreStack, -- The enclosing CCS (when profiling)
106 -- The current set of in-scope variables
107 -- They are all OutVars, and all bound in this module
108 seInScope :: InScopeSet, -- OutVars only
109 -- Includes all variables bound by seFloats
111 -- See Note [Simplifier floats]
113 -- The current substitution
114 seTvSubst :: TvSubstEnv, -- InTyVar |--> OutType
115 seIdSubst :: SimplIdSubst -- InId |--> OutExpr
119 pprSimplEnv :: SimplEnv -> SDoc
120 -- Used for debugging; selective
122 = vcat [ptext (sLit "TvSubst:") <+> ppr (seTvSubst env),
123 ptext (sLit "IdSubst:") <+> ppr (seIdSubst env) ]
125 type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
126 -- See Note [Extending the Subst] in CoreSubst
129 = DoneEx OutExpr -- Completed term
130 | DoneId OutId -- Completed term variable
131 | ContEx TvSubstEnv -- A suspended substitution
135 instance Outputable SimplSR where
136 ppr (DoneEx e) = ptext (sLit "DoneEx") <+> ppr e
137 ppr (DoneId v) = ptext (sLit "DoneId") <+> ppr v
138 ppr (ContEx _tv _id e) = vcat [ptext (sLit "ContEx") <+> ppr e {-,
139 ppr (filter_env tv), ppr (filter_env id) -}]
141 -- fvs = exprFreeVars e
142 -- filter_env env = filterVarEnv_Directly keep env
143 -- keep uniq _ = uniq `elemUFM_Directly` fvs
148 The in-scope part of Subst includes *all* in-scope TyVars and Ids
149 The elements of the set may have better IdInfo than the
150 occurrences of in-scope Ids, and (more important) they will
151 have a correctly-substituted type. So we use a lookup in this
152 set to replace occurrences
154 The Ids in the InScopeSet are replete with their Rules,
155 and as we gather info about the unfolding of an Id, we replace
156 it in the in-scope set.
158 The in-scope set is actually a mapping OutVar -> OutVar, and
159 in case expressions we sometimes bind
162 The substitution is *apply-once* only, because InIds and OutIds can overlap.
163 For example, we generally omit mappings
165 from the substitution, when we decide not to clone a77, but it's quite
166 legitimate to put the mapping in the substitution anyway.
168 Furthermore, consider
169 let x = case k of I# x77 -> ... in
170 let y = case k of I# x77 -> ... in ...
171 and suppose the body is strict in both x and y. Then the simplifier
172 will pull the first (case k) to the top; so the second (case k) will
173 cancel out, mapping x77 to, well, x77! But one is an in-Id and the
176 Of course, the substitution *must* applied! Things in its domain
177 simply aren't necessarily bound in the result.
179 * substId adds a binding (DoneId new_id) to the substitution if
180 the Id's unique has changed
183 Note, though that the substitution isn't necessarily extended
184 if the type changes. Why not? Because of the next point:
186 * We *always, always* finish by looking up in the in-scope set
187 any variable that doesn't get a DoneEx or DoneVar hit in the substitution.
188 Reason: so that we never finish up with a "old" Id in the result.
189 An old Id might point to an old unfolding and so on... which gives a space leak.
191 [The DoneEx and DoneVar hits map to "new" stuff.]
193 * It follows that substExpr must not do a no-op if the substitution is empty.
194 substType is free to do so, however.
196 * When we come to a let-binding (say) we generate new IdInfo, including an
197 unfolding, attach it to the binder, and add this newly adorned binder to
198 the in-scope set. So all subsequent occurrences of the binder will get mapped
199 to the full-adorned binder, which is also the one put in the binding site.
201 * The in-scope "set" usually maps x->x; we use it simply for its domain.
202 But sometimes we have two in-scope Ids that are synomyms, and should
203 map to the same target: x->x, y->x. Notably:
205 That's why the "set" is actually a VarEnv Var
209 mkSimplEnv :: SimplifierMode -> SwitchChecker -> SimplEnv
210 mkSimplEnv mode switches
211 = SimplEnv { seChkr = switches, seCC = subsumedCCS,
212 seMode = mode, seInScope = emptyInScopeSet,
213 seFloats = emptyFloats,
214 seTvSubst = emptyVarEnv, seIdSubst = emptyVarEnv }
215 -- The top level "enclosing CC" is "SUBSUMED".
217 ---------------------
218 getSwitchChecker :: SimplEnv -> SwitchChecker
219 getSwitchChecker env = seChkr env
221 ---------------------
222 getMode :: SimplEnv -> SimplifierMode
223 getMode env = seMode env
225 setMode :: SimplifierMode -> SimplEnv -> SimplEnv
226 setMode mode env = env { seMode = mode }
228 ---------------------
229 getEnclosingCC :: SimplEnv -> CostCentreStack
230 getEnclosingCC env = seCC env
232 setEnclosingCC :: SimplEnv -> CostCentreStack -> SimplEnv
233 setEnclosingCC env cc = env {seCC = cc}
235 ---------------------
236 extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
237 extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
238 = env {seIdSubst = extendVarEnv subst var res}
240 extendTvSubst :: SimplEnv -> TyVar -> Type -> SimplEnv
241 extendTvSubst env@(SimplEnv {seTvSubst = subst}) var res
242 = env {seTvSubst = extendVarEnv subst var res}
244 ---------------------
245 getInScope :: SimplEnv -> InScopeSet
246 getInScope env = seInScope env
248 setInScopeSet :: SimplEnv -> InScopeSet -> SimplEnv
249 setInScopeSet env in_scope = env {seInScope = in_scope}
251 setInScope :: SimplEnv -> SimplEnv -> SimplEnv
252 -- Set the in-scope set, and *zap* the floats
253 setInScope env env_with_scope
254 = env { seInScope = seInScope env_with_scope,
255 seFloats = emptyFloats }
257 setFloats :: SimplEnv -> SimplEnv -> SimplEnv
258 -- Set the in-scope set *and* the floats
259 setFloats env env_with_floats
260 = env { seInScope = seInScope env_with_floats,
261 seFloats = seFloats env_with_floats }
263 addNewInScopeIds :: SimplEnv -> [CoreBndr] -> SimplEnv
264 -- The new Ids are guaranteed to be freshly allocated
265 addNewInScopeIds env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst }) vs
266 = env { seInScope = in_scope `extendInScopeSetList` vs,
267 seIdSubst = id_subst `delVarEnvList` vs }
268 -- Why delete? Consider
269 -- let x = a*b in (x, \x -> x+3)
270 -- We add [x |-> a*b] to the substitution, but we must
271 -- _delete_ it from the substitution when going inside
274 modifyInScope :: SimplEnv -> CoreBndr -> SimplEnv
275 -- The variable should already be in scope, but
276 -- replace the existing version with this new one
277 -- which has more information
278 modifyInScope env@(SimplEnv {seInScope = in_scope}) v
279 = env {seInScope = extendInScopeSet in_scope v}
281 ---------------------
282 zapSubstEnv :: SimplEnv -> SimplEnv
283 zapSubstEnv env = env {seTvSubst = emptyVarEnv, seIdSubst = emptyVarEnv}
285 setSubstEnv :: SimplEnv -> TvSubstEnv -> SimplIdSubst -> SimplEnv
286 setSubstEnv env tvs ids = env { seTvSubst = tvs, seIdSubst = ids }
288 mkContEx :: SimplEnv -> InExpr -> SimplSR
289 mkContEx (SimplEnv { seTvSubst = tvs, seIdSubst = ids }) e = ContEx tvs ids e
294 %************************************************************************
298 %************************************************************************
300 Note [Simplifier floats]
301 ~~~~~~~~~~~~~~~~~~~~~~~~~
302 The Floats is a bunch of bindings, classified by a FloatFlag.
304 NonRec x (y:ys) FltLifted
305 Rec [(x,rhs)] FltLifted
307 NonRec x# (y +# 3) FltOkSpec -- Unboxed, but ok-for-spec'n
309 NonRec x# (a /# b) FltCareful
310 NonRec x* (f y) FltCareful -- Strict binding; might fail or diverge
311 NonRec x# (f y) FltCareful -- Unboxed binding: might fail or diverge
312 -- (where f :: Int -> Int#)
315 data Floats = Floats (OrdList OutBind) FloatFlag
316 -- See Note [Simplifier floats]
319 = FltLifted -- All bindings are lifted and lazy
320 -- Hence ok to float to top level, or recursive
322 | FltOkSpec -- All bindings are FltLifted *or*
323 -- strict (perhaps because unlifted,
324 -- perhaps because of a strict binder),
325 -- *and* ok-for-speculation
326 -- Hence ok to float out of the RHS
327 -- of a lazy non-recursive let binding
328 -- (but not to top level, or into a rec group)
330 | FltCareful -- At least one binding is strict (or unlifted)
331 -- and not guaranteed cheap
332 -- Do not float these bindings out of a lazy let
334 instance Outputable Floats where
335 ppr (Floats binds ff) = ppr ff $$ ppr (fromOL binds)
337 instance Outputable FloatFlag where
338 ppr FltLifted = ptext (sLit "FltLifted")
339 ppr FltOkSpec = ptext (sLit "FltOkSpec")
340 ppr FltCareful = ptext (sLit "FltCareful")
342 andFF :: FloatFlag -> FloatFlag -> FloatFlag
343 andFF FltCareful _ = FltCareful
344 andFF FltOkSpec FltCareful = FltCareful
345 andFF FltOkSpec _ = FltOkSpec
346 andFF FltLifted flt = flt
348 classifyFF :: CoreBind -> FloatFlag
349 classifyFF (Rec _) = FltLifted
350 classifyFF (NonRec bndr rhs)
351 | not (isStrictId bndr) = FltLifted
352 | exprOkForSpeculation rhs = FltOkSpec
353 | otherwise = FltCareful
355 doFloatFromRhs :: TopLevelFlag -> RecFlag -> Bool -> OutExpr -> SimplEnv -> Bool
356 doFloatFromRhs lvl rec str rhs (SimplEnv {seFloats = Floats fs ff})
357 = not (isNilOL fs) && want_to_float && can_float
359 want_to_float = isTopLevel lvl || exprIsExpandable rhs
360 can_float = case ff of
362 FltOkSpec -> isNotTopLevel lvl && isNonRec rec
363 FltCareful -> isNotTopLevel lvl && isNonRec rec && str
368 emptyFloats :: Floats
369 emptyFloats = Floats nilOL FltLifted
371 unitFloat :: OutBind -> Floats
372 -- A single-binding float
373 unitFloat bind = Floats (unitOL bind) (classifyFF bind)
375 addNonRec :: SimplEnv -> OutId -> OutExpr -> SimplEnv
376 -- Add a non-recursive binding and extend the in-scope set
377 -- The latter is important; the binder may already be in the
378 -- in-scope set (although it might also have been created with newId)
379 -- but it may now have more IdInfo
381 = env { seFloats = seFloats env `addFlts` unitFloat (NonRec id rhs),
382 seInScope = extendInScopeSet (seInScope env) id }
384 extendFloats :: SimplEnv -> OutBind -> SimplEnv
385 -- Add these bindings to the floats, and extend the in-scope env too
386 extendFloats env bind
387 = env { seFloats = seFloats env `addFlts` unitFloat bind,
388 seInScope = extendInScopeSetList (seInScope env) bndrs }
390 bndrs = bindersOf bind
392 addFloats :: SimplEnv -> SimplEnv -> SimplEnv
393 -- Add the floats for env2 to env1;
394 -- *plus* the in-scope set for env2, which is bigger
395 -- than that for env1
397 = env1 {seFloats = seFloats env1 `addFlts` seFloats env2,
398 seInScope = seInScope env2 }
400 addFlts :: Floats -> Floats -> Floats
401 addFlts (Floats bs1 l1) (Floats bs2 l2)
402 = Floats (bs1 `appOL` bs2) (l1 `andFF` l2)
404 zapFloats :: SimplEnv -> SimplEnv
405 zapFloats env = env { seFloats = emptyFloats }
407 addRecFloats :: SimplEnv -> SimplEnv -> SimplEnv
408 -- Flattens the floats from env2 into a single Rec group,
409 -- prepends the floats from env1, and puts the result back in env2
410 -- This is all very specific to the way recursive bindings are
411 -- handled; see Simplify.simplRecBind
412 addRecFloats env1 env2@(SimplEnv {seFloats = Floats bs ff})
413 = ASSERT2( case ff of { FltLifted -> True; _ -> False }, ppr (fromOL bs) )
414 env2 {seFloats = seFloats env1 `addFlts` unitFloat (Rec (flattenBinds (fromOL bs)))}
416 wrapFloats :: SimplEnv -> OutExpr -> OutExpr
417 wrapFloats env expr = wrapFlts (seFloats env) expr
419 wrapFlts :: Floats -> OutExpr -> OutExpr
420 -- Wrap the floats around the expression, using case-binding where necessary
421 wrapFlts (Floats bs _) body = foldrOL wrap body bs
423 wrap (Rec prs) body = Let (Rec prs) body
424 wrap (NonRec b r) body = bindNonRec b r body
426 getFloats :: SimplEnv -> [CoreBind]
427 getFloats (SimplEnv {seFloats = Floats bs _}) = fromOL bs
429 isEmptyFloats :: SimplEnv -> Bool
430 isEmptyFloats env = isEmptyFlts (seFloats env)
432 isEmptyFlts :: Floats -> Bool
433 isEmptyFlts (Floats bs _) = isNilOL bs
435 floatBinds :: Floats -> [OutBind]
436 floatBinds (Floats bs _) = fromOL bs
440 %************************************************************************
444 %************************************************************************
446 Note [Global Ids in the substitution]
447 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
448 We look up even a global (eg imported) Id in the substitution. Consider
449 case X.g_34 of b { (a,b) -> ... case X.g_34 of { (p,q) -> ...} ... }
450 The binder-swap in the occurence analyser will add a binding
451 for a LocalId version of g (with the same unique though):
452 case X.g_34 of b { (a,b) -> let g_34 = b in
453 ... case X.g_34 of { (p,q) -> ...} ... }
454 So we want to look up the inner X.g_34 in the substitution, where we'll
455 find that it has been substituted by b. (Or conceivably cloned.)
458 substId :: SimplEnv -> InId -> SimplSR
459 -- Returns DoneEx only on a non-Var expression
460 substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
461 = case lookupVarEnv ids v of -- Note [Global Ids in the substitution]
462 Nothing -> DoneId (refine in_scope v)
463 Just (DoneId v) -> DoneId (refine in_scope v)
464 Just (DoneEx (Var v)) -> DoneId (refine in_scope v)
465 Just res -> res -- DoneEx non-var, or ContEx
468 -- Get the most up-to-date thing from the in-scope set
469 -- Even though it isn't in the substitution, it may be in
470 -- the in-scope set with better IdInfo
471 refine :: InScopeSet -> Var -> Var
473 | isLocalId v = case lookupInScope in_scope v of
475 Nothing -> WARN( True, ppr v ) v -- This is an error!
478 lookupRecBndr :: SimplEnv -> InId -> OutId
479 -- Look up an Id which has been put into the envt by simplRecBndrs,
480 -- but where we have not yet done its RHS
481 lookupRecBndr (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
482 = case lookupVarEnv ids v of
484 Just _ -> pprPanic "lookupRecBndr" (ppr v)
485 Nothing -> refine in_scope v
489 %************************************************************************
491 \section{Substituting an Id binder}
493 %************************************************************************
496 These functions are in the monad only so that they can be made strict via seq.
499 simplBinders, simplLamBndrs
500 :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
501 simplBinders env bndrs = mapAccumLM simplBinder env bndrs
502 simplLamBndrs env bndrs = mapAccumLM simplLamBndr env bndrs
505 simplBinder :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
506 -- Used for lambda and case-bound variables
507 -- Clone Id if necessary, substitute type
508 -- Return with IdInfo already substituted, but (fragile) occurrence info zapped
509 -- The substitution is extended only if the variable is cloned, because
510 -- we *don't* need to use it to track occurrence info.
512 | isTyVar bndr = do { let (env', tv) = substTyVarBndr env bndr
513 ; seqTyVar tv `seq` return (env', tv) }
514 | otherwise = do { let (env', id) = substIdBndr env bndr
515 ; seqId id `seq` return (env', id) }
518 simplLamBndr :: SimplEnv -> Var -> SimplM (SimplEnv, Var)
519 -- Used for lambda binders. These sometimes have unfoldings added by
520 -- the worker/wrapper pass that must be preserved, because they can't
521 -- be reconstructed from context. For example:
522 -- f x = case x of (a,b) -> fw a b x
523 -- fw a b x{=(a,b)} = ...
524 -- The "{=(a,b)}" is an unfolding we can't reconstruct otherwise.
525 simplLamBndr env bndr
526 | isId bndr && hasSomeUnfolding old_unf = seqId id2 `seq` return (env2, id2) -- Special case
527 | otherwise = simplBinder env bndr -- Normal case
529 old_unf = idUnfolding bndr
530 (env1, id1) = substIdBndr env bndr
531 id2 = id1 `setIdUnfolding` substUnfolding env old_unf
532 env2 = modifyInScope env1 id2
535 simplNonRecBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
536 -- A non-recursive let binder
537 simplNonRecBndr env id
538 = do { let (env1, id1) = substIdBndr env id
539 ; seqId id1 `seq` return (env1, id1) }
542 simplRecBndrs :: SimplEnv -> [InBndr] -> SimplM SimplEnv
543 -- Recursive let binders
544 simplRecBndrs env@(SimplEnv {}) ids
545 = do { let (env1, ids1) = mapAccumL substIdBndr env ids
546 ; seqIds ids1 `seq` return env1 }
549 substIdBndr :: SimplEnv
550 -> InBndr -- Env and binder to transform
551 -> (SimplEnv, OutBndr)
552 -- Clone Id if necessary, substitute its type
553 -- Return an Id with its
554 -- * Type substituted
555 -- * UnfoldingInfo, Rules, WorkerInfo zapped
556 -- * Fragile OccInfo (only) zapped: Note [Robust OccInfo]
557 -- * Robust info, retained especially arity and demand info,
558 -- so that they are available to occurrences that occur in an
559 -- earlier binding of a letrec
561 -- For the robust info, see Note [Arity robustness]
563 -- Augment the substitution if the unique changed
564 -- Extend the in-scope set with the new Id
566 -- Similar to CoreSubst.substIdBndr, except that
567 -- the type of id_subst differs
568 -- all fragile info is zapped
570 substIdBndr env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst })
572 = (env { seInScope = in_scope `extendInScopeSet` new_id,
573 seIdSubst = new_subst }, new_id)
575 id1 = uniqAway in_scope old_id
576 id2 = substIdType env id1
577 new_id = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding
578 -- and fragile OccInfo
580 -- Extend the substitution if the unique has changed,
581 -- or there's some useful occurrence information
582 -- See the notes with substTyVarBndr for the delSubstEnv
583 new_subst | new_id /= old_id
584 = extendVarEnv id_subst old_id (DoneId new_id)
586 = delVarEnv id_subst old_id
590 ------------------------------------
591 seqTyVar :: TyVar -> ()
592 seqTyVar b = b `seq` ()
595 seqId id = seqType (idType id) `seq`
601 seqIds (id:ids) = seqId id `seq` seqIds ids
605 Note [Arity robustness]
606 ~~~~~~~~~~~~~~~~~~~~~~~
607 We *do* transfer the arity from from the in_id of a let binding to the
608 out_id. This is important, so that the arity of an Id is visible in
609 its own RHS. For example:
610 f = \x. ....g (\y. f y)....
611 We can eta-reduce the arg to g, becuase f is a value. But that
614 This interacts with the 'state hack' too:
619 Can we eta-expand f? Only if we see that f has arity 1, and then we
620 take advantage of the 'state hack' on the result of
621 (f y) :: State# -> (State#, Int) to expand the arity one more.
623 There is a disadvantage though. Making the arity visible in the RHS
624 allows us to eta-reduce
628 which technically is not sound. This is very much a corner case, so
629 I'm not worried about it. Another idea is to ensure that f's arity
630 never decreases; its arity started as 1, and we should never eta-reduce
634 Note [Robust OccInfo]
635 ~~~~~~~~~~~~~~~~~~~~~
636 It's important that we *do* retain the loop-breaker OccInfo, because
637 that's what stops the Id getting inlined infinitely, in the body of
641 Note [Rules in a letrec]
642 ~~~~~~~~~~~~~~~~~~~~~~~~
643 After creating fresh binders for the binders of a letrec, we
644 substitute the RULES and add them back onto the binders; this is done
645 *before* processing any of the RHSs. This is important. Manuel found
646 cases where he really, really wanted a RULE for a recursive function
647 to apply in that function's own right-hand side.
649 See Note [Loop breaking and RULES] in OccAnal.
653 addBndrRules :: SimplEnv -> InBndr -> OutBndr -> (SimplEnv, OutBndr)
654 -- Rules are added back in to to the bin
655 addBndrRules env in_id out_id
656 | isEmptySpecInfo old_rules = (env, out_id)
657 | otherwise = (modifyInScope env final_id, final_id)
659 subst = mkCoreSubst env
660 old_rules = idSpecialisation in_id
661 new_rules = CoreSubst.substSpec subst out_id old_rules
662 final_id = out_id `setIdSpecialisation` new_rules
665 substIdType :: SimplEnv -> Id -> Id
666 substIdType (SimplEnv { seInScope = in_scope, seTvSubst = tv_env}) id
667 | isEmptyVarEnv tv_env || isEmptyVarSet (tyVarsOfType old_ty) = id
668 | otherwise = Id.setIdType id (Type.substTy (TvSubst in_scope tv_env) old_ty)
669 -- The tyVarsOfType is cheaper than it looks
670 -- because we cache the free tyvars of the type
671 -- in a Note in the id's type itself
676 substUnfolding :: SimplEnv -> Unfolding -> Unfolding
677 substUnfolding _ NoUnfolding = NoUnfolding
678 substUnfolding _ (OtherCon cons) = OtherCon cons
679 substUnfolding env (CompulsoryUnfolding rhs) = CompulsoryUnfolding (substExpr env rhs)
680 substUnfolding env (CoreUnfolding rhs t u v w g) = CoreUnfolding (substExpr env rhs) t u v w g
683 substWorker :: SimplEnv -> WorkerInfo -> WorkerInfo
684 substWorker _ NoWorker = NoWorker
685 substWorker env wkr_info = CoreSubst.substWorker (mkCoreSubst env) wkr_info
689 %************************************************************************
691 Impedence matching to type substitution
693 %************************************************************************
696 substTy :: SimplEnv -> Type -> Type
697 substTy (SimplEnv { seInScope = in_scope, seTvSubst = tv_env }) ty
698 = Type.substTy (TvSubst in_scope tv_env) ty
700 substTyVarBndr :: SimplEnv -> TyVar -> (SimplEnv, TyVar)
701 substTyVarBndr env@(SimplEnv { seInScope = in_scope, seTvSubst = tv_env }) tv
702 = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
703 (TvSubst in_scope' tv_env', tv')
704 -> (env { seInScope = in_scope', seTvSubst = tv_env'}, tv')
706 -- When substituting in rules etc we can get CoreSubst to do the work
707 -- But CoreSubst uses a simpler form of IdSubstEnv, so we must impedence-match
708 -- here. I think the this will not usually result in a lot of work;
709 -- the substitutions are typically small, and laziness will avoid work in many cases.
711 mkCoreSubst :: SimplEnv -> CoreSubst.Subst
712 mkCoreSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seIdSubst = id_env })
713 = mk_subst tv_env id_env
715 mk_subst tv_env id_env = CoreSubst.mkSubst in_scope tv_env (mapVarEnv fiddle id_env)
717 fiddle (DoneEx e) = e
718 fiddle (DoneId v) = Var v
719 fiddle (ContEx tv id e) = CoreSubst.substExpr (mk_subst tv id) e
721 substExpr :: SimplEnv -> CoreExpr -> CoreExpr
722 substExpr env expr = CoreSubst.substExpr (mkCoreSubst env) expr
723 -- Do *not* short-cut in the case of an empty substitution
724 -- See CoreSubst: Note [Extending the Subst]