2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[LiberateCase]{Unroll recursion to allow evals to be lifted from a loop}
7 module LiberateCase ( liberateCase ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( DynFlags, DynFlag(..), opt_LiberateCaseThreshold )
12 import CoreLint ( showPass, endPass )
14 import CoreUnfold ( couldBeSmallEnoughToInline )
15 import Id ( Id, setIdName, idName, setIdNotExported )
17 import Name ( localiseName )
19 import Util ( notNull )
22 This module walks over @Core@, and looks for @case@ on free variables.
24 if there is case on a free on the route to the recursive call,
25 then the recursive call is replaced with an unfolding.
34 => the inner f is replaced.
43 (note the NEED for shadowing)
54 Better code, because 'a' is free inside the inner letrec, rather
55 than needing projection from v.
57 Other examples we'd like to catch with this kind of transformation
63 We'd like to avoid the redundant pattern match, transforming to
67 last (x:(y:ys)) = last' y ys
70 last' _ (y:ys) = last' y ys
72 (is this necessarily an improvement)
79 drop n (x:xs) = drop (n-1) xs
81 Would like to pass n along unboxed.
84 To think about (Apr 94)
87 Main worry: duplicating code excessively. At the moment we duplicate
88 the entire binding group once at each recursive call. But there may
89 be a group of recursive calls which share a common set of evaluated
90 free variables, in which case the duplication is a plain waste.
92 Another thing we could consider adding is some unfold-threshold thing,
93 so that we'll only duplicate if the size of the group rhss isn't too
99 The ``level'' of a binder tells how many
100 recursive defns lexically enclose the binding
101 A recursive defn "encloses" its RHS, not its
104 letrec f = let g = ... in ...
109 Here, the level of @f@ is zero, the level of @g@ is one,
110 and the level of @h@ is zero (NB not one).
113 type LibCaseLevel = Int
115 topLevel :: LibCaseLevel
122 Int -- Bomb-out size for deciding if
123 -- potential liberatees are too big.
124 -- (passed in from cmd-line args)
126 LibCaseLevel -- Current level
128 (IdEnv LibCaseLevel) -- Binds all non-top-level in-scope Ids
129 -- (top-level and imported things have
132 (IdEnv CoreBind) -- Binds *only* recursively defined
133 -- Ids, to their own binding group,
134 -- and *only* in their own RHSs
136 [(Id,LibCaseLevel)] -- Each of these Ids was scrutinised by an
137 -- enclosing case expression, with the
138 -- specified number of enclosing
139 -- recursive bindings; furthermore,
140 -- the Id is bound at a lower level
141 -- than the case expression. The
142 -- order is insignificant; it's a bag
145 initEnv :: Int -> LibCaseEnv
146 initEnv bomb_size = LibCaseEnv bomb_size 0 emptyVarEnv emptyVarEnv []
148 bombOutSize (LibCaseEnv bomb_size _ _ _ _) = bomb_size
155 liberateCase :: DynFlags -> [CoreBind] -> IO [CoreBind]
156 liberateCase dflags binds
158 showPass dflags "Liberate case" ;
159 let { binds' = do_prog (initEnv opt_LiberateCaseThreshold) binds } ;
160 endPass dflags "Liberate case" Opt_D_verbose_core2core binds'
161 {- no specific flag for dumping -}
165 do_prog env (bind:binds) = bind' : do_prog env' binds
167 (env', bind') = libCaseBind env bind
174 libCaseBind :: LibCaseEnv -> CoreBind -> (LibCaseEnv, CoreBind)
176 libCaseBind env (NonRec binder rhs)
177 = (addBinders env [binder], NonRec binder (libCase env rhs))
179 libCaseBind env (Rec pairs)
180 = (env_body, Rec pairs')
182 (binders, rhss) = unzip pairs
184 env_body = addBinders env binders
186 pairs' = [(binder, libCase env_rhs rhs) | (binder,rhs) <- pairs]
188 env_rhs = if all rhs_small_enough rhss then extended_env else env
190 -- We extend the rec-env by binding each Id to its rhs, first
191 -- processing the rhs with an *un-extended* environment, so
192 -- that the same process doesn't occur for ever!
194 extended_env = addRecBinds env [ (setIdNotExported binder, libCase env_body rhs)
195 | (binder, rhs) <- pairs ]
197 -- Two subtle things:
198 -- (a) Reset the export flags on the binders so
199 -- that we don't get name clashes on exported things if the
200 -- local binding floats out to top level. This is most unlikely
201 -- to happen, since the whole point concerns free variables.
202 -- But resetting the export flag is right regardless.
204 -- (b) Make the name an Internal one. External Names should never be
205 -- nested; if it were floated to the top level, we'd get a name
206 -- clash at code generation time.
207 adjust bndr = setIdNotExported (setIdName bndr (localiseName (idName bndr)))
209 rhs_small_enough rhs = couldBeSmallEnoughToInline lIBERATE_BOMB_SIZE rhs
210 lIBERATE_BOMB_SIZE = bombOutSize env
218 libCase :: LibCaseEnv
222 libCase env (Var v) = libCaseId env v
223 libCase env (Lit lit) = Lit lit
224 libCase env (Type ty) = Type ty
225 libCase env (App fun arg) = App (libCase env fun) (libCase env arg)
226 libCase env (Note note body) = Note note (libCase env body)
228 libCase env (Lam binder body)
229 = Lam binder (libCase (addBinders env [binder]) body)
231 libCase env (Let bind body)
232 = Let bind' (libCase env_body body)
234 (env_body, bind') = libCaseBind env bind
236 libCase env (Case scrut bndr ty alts)
237 = Case (libCase env scrut) bndr ty (map (libCaseAlt env_alts) alts)
239 env_alts = addBinders env_with_scrut [bndr]
240 env_with_scrut = case scrut of
241 Var scrut_var -> addScrutedVar env scrut_var
244 libCaseAlt env (con,args,rhs) = (con, args, libCase (addBinders env args) rhs)
250 libCaseId :: LibCaseEnv -> Id -> CoreExpr
252 | Just the_bind <- lookupRecId env v -- It's a use of a recursive thing
253 , notNull free_scruts -- with free vars scrutinised in RHS
254 = Let the_bind (Var v)
260 rec_id_level = lookupLevel env v
261 free_scruts = freeScruts env rec_id_level
269 addBinders :: LibCaseEnv -> [CoreBndr] -> LibCaseEnv
270 addBinders (LibCaseEnv bomb lvl lvl_env rec_env scruts) binders
271 = LibCaseEnv bomb lvl lvl_env' rec_env scruts
273 lvl_env' = extendVarEnvList lvl_env (binders `zip` repeat lvl)
275 addRecBinds :: LibCaseEnv -> [(Id,CoreExpr)] -> LibCaseEnv
276 addRecBinds (LibCaseEnv bomb lvl lvl_env rec_env scruts) pairs
277 = LibCaseEnv bomb lvl' lvl_env' rec_env' scruts
280 lvl_env' = extendVarEnvList lvl_env [(binder,lvl) | (binder,_) <- pairs]
281 rec_env' = extendVarEnvList rec_env [(binder, Rec pairs) | (binder,_) <- pairs]
283 addScrutedVar :: LibCaseEnv
284 -> Id -- This Id is being scrutinised by a case expression
287 addScrutedVar env@(LibCaseEnv bomb lvl lvl_env rec_env scruts) scrut_var
289 = LibCaseEnv bomb lvl lvl_env rec_env scruts'
290 -- Add to scruts iff the scrut_var is being scrutinised at
291 -- a deeper level than its defn
295 scruts' = (scrut_var, lvl) : scruts
296 bind_lvl = case lookupVarEnv lvl_env scrut_var of
300 lookupRecId :: LibCaseEnv -> Id -> Maybe CoreBind
301 lookupRecId (LibCaseEnv bomb lvl lvl_env rec_env scruts) id
302 = lookupVarEnv rec_env id
304 lookupLevel :: LibCaseEnv -> Id -> LibCaseLevel
305 lookupLevel (LibCaseEnv bomb lvl lvl_env rec_env scruts) id
306 = case lookupVarEnv lvl_env id of
310 freeScruts :: LibCaseEnv
311 -> LibCaseLevel -- Level of the recursive Id
312 -> [Id] -- Ids that are scrutinised between the binding
313 -- of the recursive Id and here
314 freeScruts (LibCaseEnv bomb lvl lvl_env rec_env scruts) rec_bind_lvl
315 = [v | (v,scrut_lvl) <- scruts, scrut_lvl > rec_bind_lvl]