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.)
28 incMinorLvl, ltMajLvl, ltLvl, isTopLvl
31 #include "HsVersions.h"
35 import CoreUtils ( coreExprType, exprIsTrivial, exprIsBottom )
36 import CoreFVs -- all of it
37 import Id ( Id, idType, mkSysLocal, isOneShotLambda )
38 import Var ( IdOrTyVar, Var, setVarUnique )
41 import Type ( isUnLiftedType, mkTyVarTys, mkForAllTys, Type )
45 import Maybes ( maybeToBool )
46 import Util ( zipWithEqual, zipEqual )
49 isLeakFreeType x y = False -- safe option; ToDo
52 %************************************************************************
54 \subsection{Level numbers}
56 %************************************************************************
60 = Top -- Means *really* the top level; short for (Level 0 0).
61 | Level Int -- Level number of enclosing lambdas
62 Int -- Number of big-lambda and/or case expressions between
63 -- here and the nearest enclosing lambda
66 The {\em level number} on a (type-)lambda-bound variable is the
67 nesting depth of the (type-)lambda which binds it. The outermost lambda
68 has level 1, so (Level 0 0) means that the variable is bound outside any lambda.
70 On an expression, it's the maximum level number of its free
71 (type-)variables. On a let(rec)-bound variable, it's the level of its
72 RHS. On a case-bound variable, it's the number of enclosing lambdas.
74 Top-level variables: level~0. Those bound on the RHS of a top-level
75 definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown
78 a_0 = let b_? = ... in
79 x_1 = ... b ... in ...
82 Level 0 0 will make something get floated to a top-level "equals",
83 @Top@ makes it go right to the top.
85 The main function @lvlExpr@ carries a ``context level'' (@ctxt_lvl@).
86 That's meant to be the level number of the enclosing binder in the
87 final (floated) program. If the level number of a sub-expression is
88 less than that of the context, then it might be worth let-binding the
89 sub-expression so that it will indeed float. This context level starts
90 at @Level 0 0@; it is never @Top@.
93 type LevelledExpr = TaggedExpr Level
94 type LevelledArg = TaggedArg Level
95 type LevelledBind = TaggedBind Level
99 incMajorLvl :: Level -> Level
100 incMajorLvl Top = Level 1 0
101 incMajorLvl (Level major minor) = Level (major+1) 0
103 incMinorLvl :: Level -> Level
104 incMinorLvl Top = Level 0 1
105 incMinorLvl (Level major minor) = Level major (minor+1)
107 unTopify :: Type -> Level -> Level
109 | isUnLiftedType ty = case lvl of
110 Top -> Level 0 0 -- Unboxed floats can't go right
111 other -> lvl -- to the top
114 maxLvl :: Level -> Level -> Level
117 maxLvl l1@(Level maj1 min1) l2@(Level maj2 min2)
118 | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1
121 ltLvl :: Level -> Level -> Bool
123 ltLvl Top (Level _ _) = True
124 ltLvl (Level maj1 min1) (Level maj2 min2)
125 = (maj1 < maj2) || (maj1 == maj2 && min1 < min2)
127 ltMajLvl :: Level -> Level -> Bool
128 -- Tells if one level belongs to a difft *lambda* level to another
129 ltMajLvl l1 Top = False
130 ltMajLvl Top (Level 0 _) = False
131 ltMajLvl Top (Level _ _) = True
132 ltMajLvl (Level maj1 _) (Level maj2 _) = maj1 < maj2
134 isTopLvl :: Level -> Bool
136 isTopLvl other = False
138 isTopMajLvl :: Level -> Bool -- Tells if it's the top *lambda* level
139 isTopMajLvl Top = True
140 isTopMajLvl (Level maj _) = maj == 0
142 instance Outputable Level where
143 ppr Top = ptext SLIT("<Top>")
144 ppr (Level maj min) = hcat [ char '<', int maj, char ',', int min, char '>' ]
148 type LevelEnv = VarEnv (Var, Level)
149 -- We clone let-bound variables so that they are still
150 -- distinct when floated out; hence the Var in the range
152 extendLvlEnv :: LevelEnv -> [(Var,Level)] -> LevelEnv
153 -- Used when *not* cloning
154 extendLvlEnv env prs = foldl add env prs
156 add env (v,l) = extendVarEnv env v (v,l)
158 varLevel :: LevelEnv -> IdOrTyVar -> Level
160 = case lookupVarEnv env v of
161 Just (_,level) -> level
164 maxIdLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
165 maxIdLvl env var lvl | isTyVar var = lvl
166 | otherwise = case lookupVarEnv env var of
167 Just (_,lvl') -> maxLvl lvl' lvl
170 maxTyVarLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
171 maxTyVarLvl env var lvl | isId var = lvl
172 | otherwise = case lookupVarEnv env var of
173 Just (_,lvl') -> maxLvl lvl' lvl
177 %************************************************************************
179 \subsection{Main level-setting code}
181 %************************************************************************
184 setLevels :: [CoreBind]
189 = initLvl us (do_them binds)
191 -- "do_them"'s main business is to thread the monad along
192 -- It gives each top binding the same empty envt, because
193 -- things unbound in the envt have level number zero implicitly
194 do_them :: [CoreBind] -> LvlM [LevelledBind]
196 do_them [] = returnLvl []
198 = lvlTopBind b `thenLvl` \ (lvld_bind, _) ->
199 do_them bs `thenLvl` \ lvld_binds ->
200 returnLvl (lvld_bind ++ lvld_binds)
202 initialEnv = emptyVarEnv
204 lvlTopBind (NonRec binder rhs)
205 = lvlBind Top initialEnv (AnnNonRec binder (freeVars rhs))
206 -- Rhs can have no free vars!
208 lvlTopBind (Rec pairs)
209 = lvlBind Top initialEnv (AnnRec [(b,freeVars rhs) | (b,rhs) <- pairs])
212 %************************************************************************
214 \subsection{Bindings}
216 %************************************************************************
218 The binding stuff works for top level too.
224 -> LvlM ([LevelledBind], LevelEnv)
226 lvlBind ctxt_lvl env (AnnNonRec bndr rhs)
227 = setFloatLevel (Just bndr) ctxt_lvl env rhs ty `thenLvl` \ (final_lvl, rhs') ->
228 cloneVar ctxt_lvl bndr `thenLvl` \ new_bndr ->
230 new_env = extendVarEnv env bndr (new_bndr,final_lvl)
232 returnLvl ([NonRec (new_bndr, final_lvl) rhs'], new_env)
237 lvlBind ctxt_lvl env (AnnRec pairs) = lvlRecBind ctxt_lvl env pairs
240 %************************************************************************
242 \subsection{Setting expression levels}
244 %************************************************************************
247 lvlExpr :: Level -- ctxt_lvl: Level of enclosing expression
248 -> LevelEnv -- Level of in-scope names/tyvars
249 -> CoreExprWithFVs -- input expression
250 -> LvlM LevelledExpr -- Result expression
253 The @ctxt_lvl@ is, roughly, the level of the innermost enclosing
258 v = \x -> ...\y -> let r = case (..x..) of
262 When looking at the rhs of @r@, @ctxt_lvl@ will be 1 because that's
263 the level of @r@, even though it's inside a level-2 @\y@. It's
264 important that @ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we
265 don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE
266 --- because it isn't a *maximal* free expression.
268 If there were another lambda in @r@'s rhs, it would get level-2 as well.
271 lvlExpr _ _ (_, AnnType ty) = returnLvl (Type ty)
272 lvlExpr _ env (_, AnnVar v) = case lookupVarEnv env v of
273 Just (v',_) -> returnLvl (Var v')
274 Nothing -> returnLvl (Var v)
276 lvlExpr ctxt_lvl env (_, AnnCon con args)
277 = mapLvl (lvlExpr ctxt_lvl env) args `thenLvl` \ args' ->
278 returnLvl (Con con args')
280 lvlExpr ctxt_lvl env (_, AnnApp fun arg)
281 = lvlExpr ctxt_lvl env fun `thenLvl` \ fun' ->
282 lvlMFE ctxt_lvl env arg `thenLvl` \ arg' ->
283 returnLvl (App fun' arg')
285 lvlExpr ctxt_lvl env (_, AnnNote note expr)
286 = lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
287 returnLvl (Note note expr')
289 -- We don't split adjacent lambdas. That is, given
291 -- we don't float to give
292 -- \x -> let v = x+y in \y -> (v,y)
293 -- Why not? Because partial applications are fairly rare, and splitting
294 -- lambdas makes them more expensive.
296 lvlExpr ctxt_lvl env (_, AnnLam bndr rhs)
297 = lvlMFE incd_lvl new_env body `thenLvl` \ body' ->
298 returnLvl (mkLams lvld_bndrs body')
300 bndr_is_id = isId bndr
301 bndr_is_tyvar = isTyVar bndr
302 (bndrs, body) = go rhs
304 incd_lvl | bndr_is_id && not (all isOneShotLambda bndrs) = incMajorLvl ctxt_lvl
305 | otherwise = incMinorLvl ctxt_lvl
306 -- Only bump the major level number if the binders include
307 -- at least one more-than-one-shot lambda
309 lvld_bndrs = [(b,incd_lvl) | b <- (bndr:bndrs)]
310 new_env = extendLvlEnv env lvld_bndrs
312 go (_, AnnLam bndr rhs) | bndr_is_id && isId bndr
313 || bndr_is_tyvar && isTyVar bndr
314 = case go rhs of { (bndrs, body) -> (bndr:bndrs, body) }
317 lvlExpr ctxt_lvl env (_, AnnLet bind body)
318 = lvlBind ctxt_lvl env bind `thenLvl` \ (binds', new_env) ->
319 lvlExpr ctxt_lvl new_env body `thenLvl` \ body' ->
320 returnLvl (mkLets binds' body')
322 lvlExpr ctxt_lvl env (_, AnnCase expr case_bndr alts)
323 = lvlMFE ctxt_lvl env expr `thenLvl` \ expr' ->
324 mapLvl lvl_alt alts `thenLvl` \ alts' ->
325 returnLvl (Case expr' (case_bndr, incd_lvl) alts')
327 expr_type = coreExprType (deAnnotate expr)
328 incd_lvl = incMinorLvl ctxt_lvl
329 alts_env = extendVarEnv env case_bndr (case_bndr,incd_lvl)
331 lvl_alt (con, bs, rhs)
333 bs' = [ (b, incd_lvl) | b <- bs ]
334 new_env = extendLvlEnv alts_env bs'
336 lvlMFE incd_lvl new_env rhs `thenLvl` \ rhs' ->
337 returnLvl (con, bs', rhs')
340 @lvlMFE@ is just like @lvlExpr@, except that it might let-bind
341 the expression, so that it can itself be floated.
344 lvlMFE :: Level -- Level of innermost enclosing lambda/tylam
345 -> LevelEnv -- Level of in-scope names/tyvars
346 -> CoreExprWithFVs -- input expression
347 -> LvlM LevelledExpr -- Result expression
349 lvlMFE ctxt_lvl env (_, AnnType ty)
350 = returnLvl (Type ty)
352 lvlMFE ctxt_lvl env ann_expr
353 | isUnLiftedType ty -- Can't let-bind it
354 = lvlExpr ctxt_lvl env ann_expr
356 | otherwise -- Not primitive type so could be let-bound
357 = setFloatLevel Nothing {- Not already let-bound -}
358 ctxt_lvl env ann_expr ty `thenLvl` \ (final_lvl, expr') ->
361 ty = coreExprType (deAnnotate ann_expr)
365 %************************************************************************
367 \subsection{Deciding floatability}
369 %************************************************************************
371 @setFloatLevel@ is used for let-bound right-hand-sides, or for MFEs which
372 are being created as let-bindings
376 YES. -> (a) try abstracting type variables.
377 If we abstract type variables it will go further, that is, past more
378 lambdas. same as asking if the level number given by the free
379 variables is less than the level number given by free variables
380 and type variables together.
381 Abstract offending type variables, e.g.
383 to let v = /\ty' -> f ty' a b
385 so that v' is not stopped by the level number of ty
386 tag the original let with its level number
387 (from its variables and type variables)
389 YES. -> No point in let binding to float a WHNF.
390 Pin (leave) expression here.
391 NO. -> Will float past a lambda?
392 (check using free variables only, not type variables)
393 YES. -> do the same as (a) above.
394 NO. -> No point in let binding if it is not going anywhere
395 Pin (leave) expression here.
398 setFloatLevel :: Maybe Id -- Just id <=> the expression is already let-bound to id
399 -- Nothing <=> it's a possible MFE
400 -> Level -- of context
403 -> CoreExprWithFVs -- Original rhs
404 -> Type -- Type of rhs
406 -> LvlM (Level, -- Level to attribute to this let-binding
407 LevelledExpr) -- Final rhs
409 setFloatLevel maybe_let_bound ctxt_lvl env expr@(expr_fvs, _) ty
411 -- Now deal with (by not floating) trivial non-let-bound expressions
412 -- which just aren't worth let-binding in order to float. We always
413 -- choose to float even trivial let-bound things because it doesn't do
414 -- any harm, and not floating it may pin something important. For
421 -- Here, if we don't float v we won't float w, which is Bad News.
422 -- If this gives any problems we could restrict the idea to things destined
425 | not alreadyLetBound
426 && (expr_is_trivial || expr_is_bottom || not will_float_past_lambda)
428 = -- Pin trivial non-let-bound expressions,
429 -- or ones which aren't going anywhere useful
430 lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
431 returnLvl (safe_ctxt_lvl, expr')
434 The above case used to read (whnf_or_bottom || not will_float_past_lambda).
435 It was changed because we really do want to float out constructors if possible:
436 this can save a great deal of needless allocation inside a loop. On the other
437 hand, there's no point floating out nullary constructors and literals, hence
438 the expr_is_trivial condition.
441 | alreadyLetBound && not worth_type_abstraction
442 = -- Process the expression with a new ctxt_lvl, obtained from
443 -- the free vars of the expression itself
444 lvlExpr expr_lvl env expr `thenLvl` \ expr' ->
445 returnLvl (safe_expr_lvl, expr')
447 | otherwise -- This will create a let anyway, even if there is no
448 -- type variable to abstract, so we try to abstract anyway
449 = abstractWrtTyVars offending_tyvars ty env lvl_after_ty_abstr expr
450 `thenLvl` \ final_expr ->
451 returnLvl (safe_expr_lvl, final_expr)
452 -- OLD LIE: The body of the let, just a type application, isn't worth floating
453 -- so pin it with ctxt_lvl
454 -- The truth: better to give it expr_lvl in case it is pinning
455 -- something non-trivial which depends on it.
457 alreadyLetBound = maybeToBool maybe_let_bound
459 safe_ctxt_lvl = unTopify ty ctxt_lvl
460 safe_expr_lvl = unTopify ty expr_lvl
462 fvs = case maybe_let_bound of
464 Just id -> expr_fvs `unionVarSet` idFreeVars id
466 ids_only_lvl = foldVarSet (maxIdLvl env) tOP_LEVEL fvs
467 tyvars_only_lvl = foldVarSet (maxTyVarLvl env) tOP_LEVEL fvs
468 expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
469 lvl_after_ty_abstr = ids_only_lvl --`maxLvl` non_offending_tyvars_lvl
471 -- Will escape lambda if let-bound
472 will_float_past_lambda = ids_only_lvl `ltMajLvl` ctxt_lvl
474 -- Will escape (more) lambda(s)/type lambda(s) if type abstracted
475 worth_type_abstraction = (ids_only_lvl `ltLvl` tyvars_only_lvl)
476 && not expr_is_trivial -- Avoids abstracting trivial type applications
478 offending_tyvars = filter offending_tv (varSetElems fvs)
479 offending_tv var | isId var = False
480 | otherwise = ids_only_lvl `ltLvl` varLevel env var
482 expr_is_trivial = exprIsTrivial de_ann_expr
483 expr_is_bottom = exprIsBottom de_ann_expr
484 de_ann_expr = deAnnotate expr
487 Abstract wrt tyvars, by making it just as if we had seen
492 instead of simply E. The idea is that v can be freely floated, since it
493 has no free type variables. Of course, if E has no free type
494 variables, then we just return E.
497 abstractWrtTyVars offending_tyvars ty env lvl expr
498 = lvlExpr incd_lvl new_env expr `thenLvl` \ expr' ->
499 newLvlVar poly_ty `thenLvl` \ poly_var ->
501 poly_var_rhs = mkLams tyvar_lvls expr'
502 poly_var_binding = NonRec (poly_var, lvl) poly_var_rhs
503 poly_var_app = mkTyApps (Var poly_var) (mkTyVarTys offending_tyvars)
504 final_expr = Let poly_var_binding poly_var_app -- mkCoLet* requires Core
508 poly_ty = mkForAllTys offending_tyvars ty
510 -- These defns are just like those in the TyLam case of lvlExpr
511 incd_lvl = incMinorLvl lvl
512 tyvar_lvls = [(tv,incd_lvl) | tv <- offending_tyvars]
513 new_env = extendLvlEnv env tyvar_lvls
516 Recursive definitions. We want to transform
528 x1' = /\ ab -> let D' in e1
530 xn' = /\ ab -> let D' in en
534 where ab are the tyvars pinning the defn further in than it
535 need be, and D is a bunch of simple type applications:
541 The "_cl" indicates that in D, the level numbers on the xi are the context level
542 number; type applications aren't worth floating. The D' decls are
549 but differ in their level numbers; here the ab are the newly-introduced
553 lvlRecBind ctxt_lvl env pairs
554 | ids_only_lvl `ltLvl` tyvars_only_lvl
555 = -- Abstract wrt tyvars;
556 -- offending_tyvars is definitely non-empty
557 -- (I love the ASSERT to check this... WDP 95/02)
559 incd_lvl = incMinorLvl ids_only_lvl
560 tyvars_w_rhs_lvl = [(var,incd_lvl) | var <- offending_tyvars]
561 bndrs_w_rhs_lvl = [(var,incd_lvl) | var <- bndrs]
562 rhs_env = extendLvlEnv env (tyvars_w_rhs_lvl ++ bndrs_w_rhs_lvl)
564 mapLvl (lvlExpr incd_lvl rhs_env) rhss `thenLvl` \ rhss' ->
565 mapLvl newLvlVar poly_tys `thenLvl` \ poly_vars ->
566 mapLvl (cloneVar ctxt_lvl) bndrs `thenLvl` \ new_bndrs ->
568 -- The "d_rhss" are the right-hand sides of "D" and "D'"
569 -- in the documentation above
570 d_rhss = [ mkTyApps (Var poly_var) offending_tyvar_tys | poly_var <- poly_vars]
572 -- "local_binds" are "D'" in the documentation above
573 local_binds = zipWithEqual "SetLevels" NonRec bndrs_w_rhs_lvl d_rhss
575 poly_var_rhss = [ mkLams tyvars_w_rhs_lvl (mkLets local_binds rhs')
579 poly_binds = zipEqual "poly_binds" [(poly_var, ids_only_lvl) | poly_var <- poly_vars]
582 -- The new right-hand sides, just a type application,
583 -- aren't worth floating so pin it with ctxt_lvl
584 bndrs_w_lvl = new_bndrs `zip` repeat ctxt_lvl
585 new_env = extendVarEnvList env (bndrs `zip` bndrs_w_lvl)
587 -- "d_binds" are the "D" in the documentation above
588 d_binds = zipWithEqual "SetLevels" NonRec bndrs_w_lvl d_rhss
590 returnLvl (Rec poly_binds : d_binds, new_env)
593 = -- Let it float freely
594 mapLvl (cloneVar ctxt_lvl) bndrs `thenLvl` \ new_bndrs ->
596 bndrs_w_lvls = new_bndrs `zip` repeat expr_lvl
597 new_env = extendVarEnvList env (bndrs `zip` bndrs_w_lvls)
599 mapLvl (lvlExpr expr_lvl new_env) rhss `thenLvl` \ rhss' ->
600 returnLvl ([Rec (bndrs_w_lvls `zip` rhss')], new_env)
603 (bndrs,rhss) = unzip pairs
605 -- Finding the free vars of the binding group is annoying
606 bind_fvs = (unionVarSets (map fst rhss) `unionVarSet` unionVarSets (map idFreeVars bndrs))
610 ids_only_lvl = foldVarSet (maxIdLvl env) tOP_LEVEL bind_fvs
611 tyvars_only_lvl = foldVarSet (maxTyVarLvl env) tOP_LEVEL bind_fvs
612 expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
614 offending_tyvars = filter offending_tv (varSetElems bind_fvs)
615 offending_tv var | isId var = False
616 | otherwise = ids_only_lvl `ltLvl` varLevel env var
617 offending_tyvar_tys = mkTyVarTys offending_tyvars
619 tys = map idType bndrs
620 poly_tys = map (mkForAllTys offending_tyvars) tys
623 %************************************************************************
625 \subsection{Free-To-Level Monad}
627 %************************************************************************
630 type LvlM result = UniqSM result
639 newLvlVar :: Type -> LvlM Id
640 newLvlVar ty = getUniqueUs `thenLvl` \ uniq ->
641 returnUs (mkSysLocal SLIT("lvl") uniq ty)
643 cloneVar :: Level -> Id -> LvlM Id
644 cloneVar Top v = returnUs v -- Don't clone top level things
645 cloneVar _ v = getUniqueUs `thenLvl` \ uniq ->
646 returnUs (setVarUnique v uniq)