2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 ***************************
8 ***************************
10 * We attach binding levels to Core bindings, in preparation for floating
11 outwards (@FloatOut@).
13 * We also let-ify many expressions (notably case scrutinees), so they
14 will have a fighting chance of being floated sensible.
16 * We clone the binders of any floatable let-binding, so that when it is
17 floated out it will be unique. (This used to be done by the simplifier
18 but the latter now only ensures that there's no shadowing.)
19 NOTE: Very tiresomely, we must apply this substitution to
20 the rules stored inside a variable too.
30 incMinorLvl, ltMajLvl, ltLvl, isTopLvl
33 #include "HsVersions.h"
37 import CoreUtils ( coreExprType, exprIsTrivial, exprIsBottom )
38 import CoreFVs -- all of it
39 import Id ( Id, idType, mkSysLocal, isOneShotLambda, modifyIdInfo )
40 import IdInfo ( specInfo, setSpecInfo )
41 import Var ( IdOrTyVar, Var, setVarUnique )
45 import Type ( isUnLiftedType, mkTyVarTys, mkForAllTys, Type )
49 import Maybes ( maybeToBool )
50 import Util ( zipWithEqual, zipEqual )
53 isLeakFreeType x y = False -- safe option; ToDo
56 %************************************************************************
58 \subsection{Level numbers}
60 %************************************************************************
64 = Top -- Means *really* the top level; short for (Level 0 0).
65 | Level Int -- Level number of enclosing lambdas
66 Int -- Number of big-lambda and/or case expressions between
67 -- here and the nearest enclosing lambda
70 The {\em level number} on a (type-)lambda-bound variable is the
71 nesting depth of the (type-)lambda which binds it. The outermost lambda
72 has level 1, so (Level 0 0) means that the variable is bound outside any lambda.
74 On an expression, it's the maximum level number of its free
75 (type-)variables. On a let(rec)-bound variable, it's the level of its
76 RHS. On a case-bound variable, it's the number of enclosing lambdas.
78 Top-level variables: level~0. Those bound on the RHS of a top-level
79 definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown
82 a_0 = let b_? = ... in
83 x_1 = ... b ... in ...
86 Level 0 0 will make something get floated to a top-level "equals",
87 @Top@ makes it go right to the top.
89 The main function @lvlExpr@ carries a ``context level'' (@ctxt_lvl@).
90 That's meant to be the level number of the enclosing binder in the
91 final (floated) program. If the level number of a sub-expression is
92 less than that of the context, then it might be worth let-binding the
93 sub-expression so that it will indeed float. This context level starts
94 at @Level 0 0@; it is never @Top@.
97 type LevelledExpr = TaggedExpr Level
98 type LevelledArg = TaggedArg Level
99 type LevelledBind = TaggedBind Level
103 incMajorLvl :: Level -> Level
104 incMajorLvl Top = Level 1 0
105 incMajorLvl (Level major minor) = Level (major+1) 0
107 incMinorLvl :: Level -> Level
108 incMinorLvl Top = Level 0 1
109 incMinorLvl (Level major minor) = Level major (minor+1)
111 unTopify :: Type -> Level -> Level
113 | isUnLiftedType ty = case lvl of
114 Top -> Level 0 0 -- Unboxed floats can't go right
115 other -> lvl -- to the top
118 maxLvl :: Level -> Level -> Level
121 maxLvl l1@(Level maj1 min1) l2@(Level maj2 min2)
122 | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1
125 ltLvl :: Level -> Level -> Bool
127 ltLvl Top (Level _ _) = True
128 ltLvl (Level maj1 min1) (Level maj2 min2)
129 = (maj1 < maj2) || (maj1 == maj2 && min1 < min2)
131 ltMajLvl :: Level -> Level -> Bool
132 -- Tells if one level belongs to a difft *lambda* level to another
133 ltMajLvl l1 Top = False
134 ltMajLvl Top (Level 0 _) = False
135 ltMajLvl Top (Level _ _) = True
136 ltMajLvl (Level maj1 _) (Level maj2 _) = maj1 < maj2
138 isTopLvl :: Level -> Bool
140 isTopLvl other = False
142 isTopMajLvl :: Level -> Bool -- Tells if it's the top *lambda* level
143 isTopMajLvl Top = True
144 isTopMajLvl (Level maj _) = maj == 0
146 instance Outputable Level where
147 ppr Top = ptext SLIT("<Top>")
148 ppr (Level maj min) = hcat [ char '<', int maj, char ',', int min, char '>' ]
151 %************************************************************************
153 \subsection{Main level-setting code}
155 %************************************************************************
158 setLevels :: [CoreBind]
163 = initLvl us (do_them binds)
165 -- "do_them"'s main business is to thread the monad along
166 -- It gives each top binding the same empty envt, because
167 -- things unbound in the envt have level number zero implicitly
168 do_them :: [CoreBind] -> LvlM [LevelledBind]
170 do_them [] = returnLvl []
172 = lvlTopBind b `thenLvl` \ (lvld_bind, _) ->
173 do_them bs `thenLvl` \ lvld_binds ->
174 returnLvl (lvld_bind ++ lvld_binds)
176 lvlTopBind (NonRec binder rhs)
177 = lvlBind Top initialEnv (AnnNonRec binder (freeVars rhs))
178 -- Rhs can have no free vars!
180 lvlTopBind (Rec pairs)
181 = lvlBind Top initialEnv (AnnRec [(b,freeVars rhs) | (b,rhs) <- pairs])
184 %************************************************************************
186 \subsection{Bindings}
188 %************************************************************************
190 The binding stuff works for top level too.
196 -> LvlM ([LevelledBind], LevelEnv)
198 lvlBind ctxt_lvl env (AnnNonRec bndr rhs)
199 = setFloatLevel (Just bndr) ctxt_lvl env rhs ty `thenLvl` \ (final_lvl, rhs') ->
200 cloneVar ctxt_lvl env bndr final_lvl `thenLvl` \ (new_env, new_bndr) ->
201 returnLvl ([NonRec (new_bndr, final_lvl) rhs'], new_env)
206 lvlBind ctxt_lvl env (AnnRec pairs) = lvlRecBind ctxt_lvl env pairs
209 %************************************************************************
211 \subsection{Setting expression levels}
213 %************************************************************************
216 lvlExpr :: Level -- ctxt_lvl: Level of enclosing expression
217 -> LevelEnv -- Level of in-scope names/tyvars
218 -> CoreExprWithFVs -- input expression
219 -> LvlM LevelledExpr -- Result expression
222 The @ctxt_lvl@ is, roughly, the level of the innermost enclosing
227 v = \x -> ...\y -> let r = case (..x..) of
231 When looking at the rhs of @r@, @ctxt_lvl@ will be 1 because that's
232 the level of @r@, even though it's inside a level-2 @\y@. It's
233 important that @ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we
234 don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE
235 --- because it isn't a *maximal* free expression.
237 If there were another lambda in @r@'s rhs, it would get level-2 as well.
240 lvlExpr _ _ (_, AnnType ty) = returnLvl (Type ty)
241 lvlExpr _ env (_, AnnVar v) = returnLvl (lookupVar env v)
243 lvlExpr ctxt_lvl env (_, AnnCon con args)
244 = mapLvl (lvlExpr ctxt_lvl env) args `thenLvl` \ args' ->
245 returnLvl (Con con args')
247 lvlExpr ctxt_lvl env (_, AnnApp fun arg)
248 = lvlExpr ctxt_lvl env fun `thenLvl` \ fun' ->
249 lvlMFE ctxt_lvl env arg `thenLvl` \ arg' ->
250 returnLvl (App fun' arg')
252 lvlExpr ctxt_lvl env (_, AnnNote note expr)
253 = lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
254 returnLvl (Note note expr')
256 -- We don't split adjacent lambdas. That is, given
258 -- we don't float to give
259 -- \x -> let v = x+y in \y -> (v,y)
260 -- Why not? Because partial applications are fairly rare, and splitting
261 -- lambdas makes them more expensive.
263 lvlExpr ctxt_lvl env (_, AnnLam bndr rhs)
264 = lvlMFE incd_lvl new_env body `thenLvl` \ body' ->
265 returnLvl (mkLams lvld_bndrs body')
267 bndr_is_id = isId bndr
268 bndr_is_tyvar = isTyVar bndr
269 (more_bndrs, body) = go rhs
270 bndrs = bndr : more_bndrs
272 incd_lvl | bndr_is_id && not (all isOneShotLambda bndrs) = incMajorLvl ctxt_lvl
273 | otherwise = incMinorLvl ctxt_lvl
274 -- Only bump the major level number if the binders include
275 -- at least one more-than-one-shot lambda
277 lvld_bndrs = [(b,incd_lvl) | b <- bndrs]
278 new_env = extendLvlEnv env lvld_bndrs
280 go (_, AnnLam bndr rhs) | bndr_is_id && isId bndr
281 || bndr_is_tyvar && isTyVar bndr
282 = case go rhs of { (bndrs, body) -> (bndr:bndrs, body) }
285 lvlExpr ctxt_lvl env (_, AnnLet bind body)
286 = lvlBind ctxt_lvl env bind `thenLvl` \ (binds', new_env) ->
287 lvlExpr ctxt_lvl new_env body `thenLvl` \ body' ->
288 returnLvl (mkLets binds' body')
290 lvlExpr ctxt_lvl env (_, AnnCase expr case_bndr alts)
291 = lvlMFE ctxt_lvl env expr `thenLvl` \ expr' ->
292 mapLvl lvl_alt alts `thenLvl` \ alts' ->
293 returnLvl (Case expr' (case_bndr, incd_lvl) alts')
295 expr_type = coreExprType (deAnnotate expr)
296 incd_lvl = incMinorLvl ctxt_lvl
297 alts_env = extendLvlEnv env [(case_bndr,incd_lvl)]
299 lvl_alt (con, bs, rhs)
301 bs' = [ (b, incd_lvl) | b <- bs ]
302 new_env = extendLvlEnv alts_env bs'
304 lvlMFE incd_lvl new_env rhs `thenLvl` \ rhs' ->
305 returnLvl (con, bs', rhs')
308 @lvlMFE@ is just like @lvlExpr@, except that it might let-bind
309 the expression, so that it can itself be floated.
312 lvlMFE :: Level -- Level of innermost enclosing lambda/tylam
313 -> LevelEnv -- Level of in-scope names/tyvars
314 -> CoreExprWithFVs -- input expression
315 -> LvlM LevelledExpr -- Result expression
317 lvlMFE ctxt_lvl env (_, AnnType ty)
318 = returnLvl (Type ty)
320 lvlMFE ctxt_lvl env ann_expr
321 | isUnLiftedType ty -- Can't let-bind it
322 = lvlExpr ctxt_lvl env ann_expr
324 | otherwise -- Not primitive type so could be let-bound
325 = setFloatLevel Nothing {- Not already let-bound -}
326 ctxt_lvl env ann_expr ty `thenLvl` \ (final_lvl, expr') ->
329 ty = coreExprType (deAnnotate ann_expr)
333 %************************************************************************
335 \subsection{Deciding floatability}
337 %************************************************************************
339 @setFloatLevel@ is used for let-bound right-hand-sides, or for MFEs which
340 are being created as let-bindings
344 YES. -> (a) try abstracting type variables.
345 If we abstract type variables it will go further, that is, past more
346 lambdas. same as asking if the level number given by the free
347 variables is less than the level number given by free variables
348 and type variables together.
349 Abstract offending type variables, e.g.
351 to let v = /\ty' -> f ty' a b
353 so that v' is not stopped by the level number of ty
354 tag the original let with its level number
355 (from its variables and type variables)
357 YES. -> No point in let binding to float a WHNF.
358 Pin (leave) expression here.
359 NO. -> Will float past a lambda?
360 (check using free variables only, not type variables)
361 YES. -> do the same as (a) above.
362 NO. -> No point in let binding if it is not going anywhere
363 Pin (leave) expression here.
366 setFloatLevel :: Maybe Id -- Just id <=> the expression is already let-bound to id
367 -- Nothing <=> it's a possible MFE
368 -> Level -- of context
371 -> CoreExprWithFVs -- Original rhs
372 -> Type -- Type of rhs
374 -> LvlM (Level, -- Level to attribute to this let-binding
375 LevelledExpr) -- Final rhs
377 setFloatLevel maybe_let_bound ctxt_lvl env expr@(expr_fvs, _) ty
379 -- Now deal with (by not floating) trivial non-let-bound expressions
380 -- which just aren't worth let-binding in order to float. We always
381 -- choose to float even trivial let-bound things because it doesn't do
382 -- any harm, and not floating it may pin something important. For
389 -- Here, if we don't float v we won't float w, which is Bad News.
390 -- If this gives any problems we could restrict the idea to things destined
393 | not alreadyLetBound
394 && (expr_is_trivial || expr_is_bottom || not will_float_past_lambda)
396 = -- Pin trivial non-let-bound expressions,
397 -- or ones which aren't going anywhere useful
398 lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
399 returnLvl (safe_ctxt_lvl, expr')
402 The above case used to read (whnf_or_bottom || not will_float_past_lambda).
403 It was changed because we really do want to float out constructors if possible:
404 this can save a great deal of needless allocation inside a loop. On the other
405 hand, there's no point floating out nullary constructors and literals, hence
406 the expr_is_trivial condition.
409 | alreadyLetBound && not worth_type_abstraction
410 = -- Process the expression with a new ctxt_lvl, obtained from
411 -- the free vars of the expression itself
412 lvlExpr expr_lvl env expr `thenLvl` \ expr' ->
413 returnLvl (safe_expr_lvl, expr')
415 | otherwise -- This will create a let anyway, even if there is no
416 -- type variable to abstract, so we try to abstract anyway
417 = abstractWrtTyVars offending_tyvars ty env lvl_after_ty_abstr expr
418 `thenLvl` \ final_expr ->
419 returnLvl (safe_expr_lvl, final_expr)
420 -- OLD LIE: The body of the let, just a type application, isn't worth floating
421 -- so pin it with ctxt_lvl
422 -- The truth: better to give it expr_lvl in case it is pinning
423 -- something non-trivial which depends on it.
425 alreadyLetBound = maybeToBool maybe_let_bound
427 safe_ctxt_lvl = unTopify ty ctxt_lvl
428 safe_expr_lvl = unTopify ty expr_lvl
430 fvs = case maybe_let_bound of
432 Just id -> expr_fvs `unionVarSet` idFreeVars id
434 ids_only_lvl = foldVarSet (maxIdLvl env) tOP_LEVEL fvs
435 tyvars_only_lvl = foldVarSet (maxTyVarLvl env) tOP_LEVEL fvs
436 expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
437 lvl_after_ty_abstr = ids_only_lvl --`maxLvl` non_offending_tyvars_lvl
439 -- Will escape lambda if let-bound
440 will_float_past_lambda = ids_only_lvl `ltMajLvl` ctxt_lvl
442 -- Will escape (more) lambda(s)/type lambda(s) if type abstracted
443 worth_type_abstraction = (ids_only_lvl `ltLvl` tyvars_only_lvl)
444 && not expr_is_trivial -- Avoids abstracting trivial type applications
446 offending_tyvars = filter offending_tv (varSetElems fvs)
447 offending_tv var | isId var = False
448 | otherwise = ids_only_lvl `ltLvl` varLevel env var
450 expr_is_trivial = exprIsTrivial de_ann_expr
451 expr_is_bottom = exprIsBottom de_ann_expr
452 de_ann_expr = deAnnotate expr
455 Abstract wrt tyvars, by making it just as if we had seen
460 instead of simply E. The idea is that v can be freely floated, since it
461 has no free type variables. Of course, if E has no free type
462 variables, then we just return E.
465 abstractWrtTyVars offending_tyvars ty env lvl expr
466 = lvlExpr incd_lvl new_env expr `thenLvl` \ expr' ->
467 newLvlVar poly_ty `thenLvl` \ poly_var ->
469 poly_var_rhs = mkLams tyvar_lvls expr'
470 poly_var_binding = NonRec (poly_var, lvl) poly_var_rhs
471 poly_var_app = mkTyApps (Var poly_var) (mkTyVarTys offending_tyvars)
472 final_expr = Let poly_var_binding poly_var_app -- mkCoLet* requires Core
476 poly_ty = mkForAllTys offending_tyvars ty
478 -- These defns are just like those in the TyLam case of lvlExpr
479 incd_lvl = incMinorLvl lvl
480 tyvar_lvls = [(tv,incd_lvl) | tv <- offending_tyvars]
481 new_env = extendLvlEnv env tyvar_lvls
484 Recursive definitions. We want to transform
496 x1' = /\ ab -> let D' in e1
498 xn' = /\ ab -> let D' in en
502 where ab are the tyvars pinning the defn further in than it
503 need be, and D is a bunch of simple type applications:
509 The "_cl" indicates that in D, the level numbers on the xi are the context level
510 number; type applications aren't worth floating. The D' decls are
517 but differ in their level numbers; here the ab are the newly-introduced
521 lvlRecBind ctxt_lvl env pairs
522 | ids_only_lvl `ltLvl` tyvars_only_lvl
523 = -- Abstract wrt tyvars;
524 -- offending_tyvars is definitely non-empty
525 -- (I love the ASSERT to check this... WDP 95/02)
527 incd_lvl = incMinorLvl ids_only_lvl
528 tyvars_w_rhs_lvl = [(var,incd_lvl) | var <- offending_tyvars]
529 bndrs_w_rhs_lvl = [(var,incd_lvl) | var <- bndrs]
530 rhs_env = extendLvlEnv env (tyvars_w_rhs_lvl ++ bndrs_w_rhs_lvl)
532 mapLvl (lvlExpr incd_lvl rhs_env) rhss `thenLvl` \ rhss' ->
533 mapLvl newLvlVar poly_tys `thenLvl` \ poly_vars ->
534 cloneVars ctxt_lvl env bndrs ctxt_lvl `thenLvl` \ (new_env, new_bndrs) ->
536 -- The "d_rhss" are the right-hand sides of "D" and "D'"
537 -- in the documentation above
538 d_rhss = [ mkTyApps (Var poly_var) offending_tyvar_tys | poly_var <- poly_vars]
540 -- "local_binds" are "D'" in the documentation above
541 local_binds = zipWithEqual "SetLevels" NonRec bndrs_w_rhs_lvl d_rhss
543 poly_var_rhss = [ mkLams tyvars_w_rhs_lvl (mkLets local_binds rhs')
547 poly_binds = zipEqual "poly_binds" [(poly_var, ids_only_lvl) | poly_var <- poly_vars]
550 -- The new right-hand sides, just a type application,
551 -- aren't worth floating so pin it with ctxt_lvl
552 bndrs_w_lvl = new_bndrs `zip` repeat ctxt_lvl
554 -- "d_binds" are the "D" in the documentation above
555 d_binds = zipWithEqual "SetLevels" NonRec bndrs_w_lvl d_rhss
557 returnLvl (Rec poly_binds : d_binds, new_env)
560 = -- Let it float freely
561 cloneVars ctxt_lvl env bndrs expr_lvl `thenLvl` \ (new_env, new_bndrs) ->
563 bndrs_w_lvls = new_bndrs `zip` repeat expr_lvl
565 mapLvl (lvlExpr expr_lvl new_env) rhss `thenLvl` \ rhss' ->
566 returnLvl ([Rec (bndrs_w_lvls `zip` rhss')], new_env)
569 (bndrs,rhss) = unzip pairs
571 -- Finding the free vars of the binding group is annoying
572 bind_fvs = (unionVarSets (map fst rhss) `unionVarSet` unionVarSets (map idFreeVars bndrs))
576 ids_only_lvl = foldVarSet (maxIdLvl env) tOP_LEVEL bind_fvs
577 tyvars_only_lvl = foldVarSet (maxTyVarLvl env) tOP_LEVEL bind_fvs
578 expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
580 offending_tyvars = filter offending_tv (varSetElems bind_fvs)
581 offending_tv var | isId var = False
582 | otherwise = ids_only_lvl `ltLvl` varLevel env var
583 offending_tyvar_tys = mkTyVarTys offending_tyvars
585 tys = map idType bndrs
586 poly_tys = map (mkForAllTys offending_tyvars) tys
589 %************************************************************************
591 \subsection{Free-To-Level Monad}
593 %************************************************************************
596 type LevelEnv = (VarEnv Level, SubstEnv)
597 -- We clone let-bound variables so that they are still
598 -- distinct when floated out; hence the SubstEnv
599 -- The domain of the VarEnv is *pre-cloned* Ids, though
601 initialEnv :: LevelEnv
602 initialEnv = (emptyVarEnv, emptySubstEnv)
604 extendLvlEnv :: LevelEnv -> [(Var,Level)] -> LevelEnv
605 -- Used when *not* cloning
606 extendLvlEnv (lvl_env, subst_env) prs
607 = (foldl add lvl_env prs, subst_env)
609 add env (v,l) = extendVarEnv env v l
611 varLevel :: LevelEnv -> IdOrTyVar -> Level
612 varLevel (lvl_env, _) v
613 = case lookupVarEnv lvl_env v of
617 lookupVar :: LevelEnv -> Id -> LevelledExpr
618 lookupVar (_, subst) v = case lookupSubstEnv subst v of
619 Just (DoneEx (Var v')) -> Var v' -- Urgh! Types don't match
622 maxIdLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
623 maxIdLvl (lvl_env,_) var lvl | isTyVar var = lvl
624 | otherwise = case lookupVarEnv lvl_env var of
625 Just lvl' -> maxLvl lvl' lvl
628 maxTyVarLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
629 maxTyVarLvl (lvl_env,_) var lvl | isId var = lvl
630 | otherwise = case lookupVarEnv lvl_env var of
631 Just lvl' -> maxLvl lvl' lvl
636 type LvlM result = UniqSM result
645 newLvlVar :: Type -> LvlM Id
646 newLvlVar ty = getUniqueUs `thenLvl` \ uniq ->
647 returnUs (mkSysLocal SLIT("lvl") uniq ty)
649 -- The deeply tiresome thing is that we have to apply the substitution
650 -- to the rules inside each Id. Grr. But it matters.
652 cloneVar :: Level -> LevelEnv -> Id -> Level -> LvlM (LevelEnv, Id)
653 cloneVar Top env v lvl
654 = returnUs (env, v) -- Don't clone top level things
655 cloneVar _ (lvl_env, subst_env) v lvl
656 = getUniqueUs `thenLvl` \ uniq ->
658 subst = mkSubst emptyVarSet subst_env
659 v' = setVarUnique v uniq
660 v'' = apply_to_rules subst v'
661 subst_env' = extendSubstEnv subst_env v (DoneEx (Var v''))
662 lvl_env' = extendVarEnv lvl_env v lvl
664 returnUs ((lvl_env', subst_env'), v'')
666 cloneVars :: Level -> LevelEnv -> [Id] -> Level -> LvlM (LevelEnv, [Id])
667 cloneVars Top env vs lvl
668 = returnUs (env, vs) -- Don't clone top level things
669 cloneVars _ (lvl_env, subst_env) vs lvl
670 = getUniquesUs (length vs) `thenLvl` \ uniqs ->
672 subst = mkSubst emptyVarSet subst_env'
673 vs' = zipWith setVarUnique vs uniqs
674 vs'' = map (apply_to_rules subst) vs'
675 subst_env' = extendSubstEnvList subst_env vs [DoneEx (Var v'') | v'' <- vs'']
676 lvl_env' = extendVarEnvList lvl_env (vs `zip` repeat lvl)
678 returnUs ((lvl_env', subst_env'), vs'')
680 -- Apply the substitution to the rules
681 apply_to_rules subst id
682 = modifyIdInfo go_spec id
684 go_spec info = info `setSpecInfo` substRules subst (specInfo info)