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 DynFlags ( DynFlags, DynFlag(..) )
12 import StaticFlags ( opt_LiberateCaseThreshold )
13 import CoreLint ( showPass, endPass )
15 import CoreUnfold ( couldBeSmallEnoughToInline )
16 import Id ( Id, setIdName, idName, setIdNotExported )
18 import Name ( localiseName )
20 import Util ( notNull )
23 This module walks over @Core@, and looks for @case@ on free variables.
25 if there is case on a free on the route to the recursive call,
26 then the recursive call is replaced with an unfolding.
35 => the inner f is replaced.
44 (note the NEED for shadowing)
55 Better code, because 'a' is free inside the inner letrec, rather
56 than needing projection from v.
58 Other examples we'd like to catch with this kind of transformation
64 We'd like to avoid the redundant pattern match, transforming to
68 last (x:(y:ys)) = last' y ys
71 last' _ (y:ys) = last' y ys
73 (is this necessarily an improvement)
80 drop n (x:xs) = drop (n-1) xs
82 Would like to pass n along unboxed.
84 Note [Scrutinee with cast]
85 ~~~~~~~~~~~~~~~~~~~~~~~~~~
87 f = \ t -> case (v `cast` co) of
90 Exactly the same optimistaion (unrolling one call to f) will work here,
91 despite the cast. See mk_alt_env in the Case branch of libCase.
94 To think about (Apr 94)
97 Main worry: duplicating code excessively. At the moment we duplicate
98 the entire binding group once at each recursive call. But there may
99 be a group of recursive calls which share a common set of evaluated
100 free variables, in which case the duplication is a plain waste.
102 Another thing we could consider adding is some unfold-threshold thing,
103 so that we'll only duplicate if the size of the group rhss isn't too
109 The ``level'' of a binder tells how many
110 recursive defns lexically enclose the binding
111 A recursive defn "encloses" its RHS, not its
114 letrec f = let g = ... in ...
119 Here, the level of @f@ is zero, the level of @g@ is one,
120 and the level of @h@ is zero (NB not one).
123 type LibCaseLevel = Int
125 topLevel :: LibCaseLevel
132 Int -- Bomb-out size for deciding if
133 -- potential liberatees are too big.
134 -- (passed in from cmd-line args)
136 LibCaseLevel -- Current level
138 (IdEnv LibCaseLevel) -- Binds all non-top-level in-scope Ids
139 -- (top-level and imported things have
142 (IdEnv CoreBind) -- Binds *only* recursively defined
143 -- Ids, to their own binding group,
144 -- and *only* in their own RHSs
146 [(Id,LibCaseLevel)] -- Each of these Ids was scrutinised by an
147 -- enclosing case expression, with the
148 -- specified number of enclosing
149 -- recursive bindings; furthermore,
150 -- the Id is bound at a lower level
151 -- than the case expression. The
152 -- order is insignificant; it's a bag
155 initEnv :: Int -> LibCaseEnv
156 initEnv bomb_size = LibCaseEnv bomb_size 0 emptyVarEnv emptyVarEnv []
158 bombOutSize (LibCaseEnv bomb_size _ _ _ _) = bomb_size
165 liberateCase :: DynFlags -> [CoreBind] -> IO [CoreBind]
166 liberateCase dflags binds
168 showPass dflags "Liberate case" ;
169 let { binds' = do_prog (initEnv opt_LiberateCaseThreshold) binds } ;
170 endPass dflags "Liberate case" Opt_D_verbose_core2core binds'
171 {- no specific flag for dumping -}
175 do_prog env (bind:binds) = bind' : do_prog env' binds
177 (env', bind') = libCaseBind env bind
184 libCaseBind :: LibCaseEnv -> CoreBind -> (LibCaseEnv, CoreBind)
186 libCaseBind env (NonRec binder rhs)
187 = (addBinders env [binder], NonRec binder (libCase env rhs))
189 libCaseBind env (Rec pairs)
190 = (env_body, Rec pairs')
192 (binders, rhss) = unzip pairs
194 env_body = addBinders env binders
196 pairs' = [(binder, libCase env_rhs rhs) | (binder,rhs) <- pairs]
198 env_rhs = if all rhs_small_enough rhss then extended_env else env
200 -- We extend the rec-env by binding each Id to its rhs, first
201 -- processing the rhs with an *un-extended* environment, so
202 -- that the same process doesn't occur for ever!
204 extended_env = addRecBinds env [ (adjust binder, libCase env_body rhs)
205 | (binder, rhs) <- pairs ]
207 -- Two subtle things:
208 -- (a) Reset the export flags on the binders so
209 -- that we don't get name clashes on exported things if the
210 -- local binding floats out to top level. This is most unlikely
211 -- to happen, since the whole point concerns free variables.
212 -- But resetting the export flag is right regardless.
214 -- (b) Make the name an Internal one. External Names should never be
215 -- nested; if it were floated to the top level, we'd get a name
216 -- clash at code generation time.
217 adjust bndr = setIdNotExported (setIdName bndr (localiseName (idName bndr)))
219 rhs_small_enough rhs = couldBeSmallEnoughToInline lIBERATE_BOMB_SIZE rhs
220 lIBERATE_BOMB_SIZE = bombOutSize env
228 libCase :: LibCaseEnv
232 libCase env (Var v) = libCaseId env v
233 libCase env (Lit lit) = Lit lit
234 libCase env (Type ty) = Type ty
235 libCase env (App fun arg) = App (libCase env fun) (libCase env arg)
236 libCase env (Note note body) = Note note (libCase env body)
237 libCase env (Cast e co) = Cast (libCase env e) co
239 libCase env (Lam binder body)
240 = Lam binder (libCase (addBinders env [binder]) body)
242 libCase env (Let bind body)
243 = Let bind' (libCase env_body body)
245 (env_body, bind') = libCaseBind env bind
247 libCase env (Case scrut bndr ty alts)
248 = Case (libCase env scrut) bndr ty (map (libCaseAlt env_alts) alts)
250 env_alts = addBinders (mk_alt_env scrut) [bndr]
251 mk_alt_env (Var scrut_var) = addScrutedVar env scrut_var
252 mk_alt_env (Cast scrut _) = mk_alt_env scrut -- Note [Scrutinee with cast]
253 mk_alt_env otehr = env
255 libCaseAlt env (con,args,rhs) = (con, args, libCase (addBinders env args) rhs)
261 libCaseId :: LibCaseEnv -> Id -> CoreExpr
263 | Just the_bind <- lookupRecId env v -- It's a use of a recursive thing
264 , notNull free_scruts -- with free vars scrutinised in RHS
265 = Let the_bind (Var v)
271 rec_id_level = lookupLevel env v
272 free_scruts = freeScruts env rec_id_level
280 addBinders :: LibCaseEnv -> [CoreBndr] -> LibCaseEnv
281 addBinders (LibCaseEnv bomb lvl lvl_env rec_env scruts) binders
282 = LibCaseEnv bomb lvl lvl_env' rec_env scruts
284 lvl_env' = extendVarEnvList lvl_env (binders `zip` repeat lvl)
286 addRecBinds :: LibCaseEnv -> [(Id,CoreExpr)] -> LibCaseEnv
287 addRecBinds (LibCaseEnv bomb lvl lvl_env rec_env scruts) pairs
288 = LibCaseEnv bomb lvl' lvl_env' rec_env' scruts
291 lvl_env' = extendVarEnvList lvl_env [(binder,lvl) | (binder,_) <- pairs]
292 rec_env' = extendVarEnvList rec_env [(binder, Rec pairs) | (binder,_) <- pairs]
294 addScrutedVar :: LibCaseEnv
295 -> Id -- This Id is being scrutinised by a case expression
298 addScrutedVar env@(LibCaseEnv bomb lvl lvl_env rec_env scruts) scrut_var
300 = LibCaseEnv bomb lvl lvl_env rec_env scruts'
301 -- Add to scruts iff the scrut_var is being scrutinised at
302 -- a deeper level than its defn
306 scruts' = (scrut_var, lvl) : scruts
307 bind_lvl = case lookupVarEnv lvl_env scrut_var of
311 lookupRecId :: LibCaseEnv -> Id -> Maybe CoreBind
312 lookupRecId (LibCaseEnv bomb lvl lvl_env rec_env scruts) id
313 = lookupVarEnv rec_env id
315 lookupLevel :: LibCaseEnv -> Id -> LibCaseLevel
316 lookupLevel (LibCaseEnv bomb lvl lvl_env rec_env scruts) id
317 = case lookupVarEnv lvl_env id of
321 freeScruts :: LibCaseEnv
322 -> LibCaseLevel -- Level of the recursive Id
323 -> [Id] -- Ids that are scrutinised between the binding
324 -- of the recursive Id and here
325 freeScruts (LibCaseEnv bomb lvl lvl_env rec_env scruts) rec_bind_lvl
326 = [v | (v,scrut_lvl) <- scruts, scrut_lvl > rec_bind_lvl]