2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
7 module WorkWrap ( wwTopBinds, mkWrapper ) where
9 #include "HsVersions.h"
12 import CoreUnfold ( certainlyWillInline )
13 import CoreLint ( showPass, endPass )
14 import CoreUtils ( exprType )
15 import MkId ( mkWorkerId )
16 import Id ( Id, idType, idStrictness, idArity, isOneShotLambda,
17 setIdStrictness, idInlinePragma,
18 setIdWorkerInfo, idCprInfo, setInlinePragma )
19 import Type ( Type, isNewType, splitForAllTys, splitFunTys )
20 import IdInfo ( mkStrictnessInfo, noStrictnessInfo, StrictnessInfo(..),
21 CprInfo(..), InlinePragInfo(..), isNeverInlinePrag,
24 import Demand ( Demand )
25 import UniqSupply ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
31 We take Core bindings whose binders have:
35 \item Strictness attached (by the front-end of the strictness
38 \item Constructed Product Result information attached by the CPR
43 and we return some ``plain'' bindings which have been
44 worker/wrapper-ified, meaning:
48 \item Functions have been split into workers and wrappers where
49 appropriate. If a function has both strictness and CPR properties
50 then only one worker/wrapper doing both transformations is produced;
52 \item Binders' @IdInfos@ have been updated to reflect the existence of
53 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
54 info for exported values).
59 wwTopBinds :: DynFlags
64 wwTopBinds dflags us binds
66 showPass dflags "Worker Wrapper binds";
68 -- Create worker/wrappers, and mark binders with their
69 -- "strictness info" [which encodes their worker/wrapper-ness]
70 let { binds' = workersAndWrappers us binds };
72 endPass dflags "Worker Wrapper binds"
73 (dopt Opt_D_dump_worker_wrapper dflags ||
74 dopt Opt_D_verbose_core2core dflags)
81 workersAndWrappers :: UniqSupply -> [CoreBind] -> [CoreBind]
83 workersAndWrappers us top_binds
85 mapUs wwBind top_binds `thenUs` \ top_binds' ->
86 returnUs (concat top_binds')
89 %************************************************************************
91 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
93 %************************************************************************
95 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
96 turn. Non-recursive case first, then recursive...
100 -> UniqSM [CoreBind] -- returns a WwBinding intermediate form;
101 -- the caller will convert to Expr/Binding,
104 wwBind (NonRec binder rhs)
105 = wwExpr rhs `thenUs` \ new_rhs ->
106 tryWW True {- non-recursive -} binder new_rhs `thenUs` \ new_pairs ->
107 returnUs [NonRec b e | (b,e) <- new_pairs]
108 -- Generated bindings must be non-recursive
109 -- because the original binding was.
111 ------------------------------
114 = mapUs do_one pairs `thenUs` \ new_pairs ->
115 returnUs [Rec (concat new_pairs)]
117 do_one (binder, rhs) = wwExpr rhs `thenUs` \ new_rhs ->
118 tryWW False {- recursive -} binder new_rhs
121 @wwExpr@ basically just walks the tree, looking for appropriate
122 annotations that can be used. Remember it is @wwBind@ that does the
123 matching by looking for strict arguments of the correct type.
124 @wwExpr@ is a version that just returns the ``Plain'' Tree.
127 wwExpr :: CoreExpr -> UniqSM CoreExpr
129 wwExpr e@(Type _) = returnUs e
130 wwExpr e@(Var _) = returnUs e
131 wwExpr e@(Lit _) = returnUs e
133 wwExpr (Lam binder expr)
134 = wwExpr expr `thenUs` \ new_expr ->
135 returnUs (Lam binder new_expr)
138 = wwExpr f `thenUs` \ new_f ->
139 wwExpr a `thenUs` \ new_a ->
140 returnUs (App new_f new_a)
142 wwExpr (Note note expr)
143 = wwExpr expr `thenUs` \ new_expr ->
144 returnUs (Note note new_expr)
146 wwExpr (Let bind expr)
147 = wwBind bind `thenUs` \ intermediate_bind ->
148 wwExpr expr `thenUs` \ new_expr ->
149 returnUs (mkLets intermediate_bind new_expr)
151 wwExpr (Case expr binder alts)
152 = wwExpr expr `thenUs` \ new_expr ->
153 mapUs ww_alt alts `thenUs` \ new_alts ->
154 returnUs (Case new_expr binder new_alts)
156 ww_alt (con, binders, rhs)
157 = wwExpr rhs `thenUs` \ new_rhs ->
158 returnUs (con, binders, new_rhs)
161 %************************************************************************
163 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
165 %************************************************************************
167 @tryWW@ just accumulates arguments, converts strictness info from the
168 front-end into the proper form, then calls @mkWwBodies@ to do
171 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
172 already been w-w'd! (You can end up with several liked-named Ids
173 bouncing around at the same time---absolute mischief.) So the
174 criterion we use is: if an Id already has an unfolding (for whatever
175 reason), then we don't w-w it.
177 The only reason this is monadised is for the unique supply.
180 tryWW :: Bool -- True <=> a non-recursive binding
181 -> Id -- The fn binder
182 -> CoreExpr -- The bound rhs; its innards
184 -> UniqSM [(Id, CoreExpr)] -- either *one* or *two* pairs;
185 -- if one, then no worker (only
186 -- the orig "wrapper" lives on);
187 -- if two, then a worker and a
189 tryWW non_rec fn_id rhs
190 | isNeverInlinePrag inline_prag || arity == 0
191 = -- Don't split things that will never be inlined
192 returnUs [ (fn_id, rhs) ]
194 | non_rec && not do_coerce_ww && certainlyWillInline fn_id
195 -- No point in worker/wrappering a function that is going to be
196 -- INLINEd wholesale anyway. If the strictness analyser is run
197 -- twice, this test also prevents wrappers (which are INLINEd)
198 -- from being re-done.
200 -- The do_coerce_ww test is so that
201 -- a function with a coerce should w/w to get rid
202 -- of the coerces, which can significantly improve its arity.
203 -- Example: f [] = return [] :: IO [Int]
204 -- f (x:xs) = return (x:xs)
205 -- If we aren't careful we end up with
206 -- f = \ x -> case x of {
207 -- x:xs -> __coerce (IO [Int]) (\ s -> (# s, x:xs #)
211 -- OUT OF DATE NOTE, kept for info:
212 -- It's out of date because now wrappers look very cheap
213 -- even when they are inlined.
214 -- In this case we add an INLINE pragma to the RHS. Why?
217 -- g = \yz -> ... -- And g is strict
218 -- Then f is small, so we don't w/w it. But g is big, and we do, so
219 -- g's wrapper will get inlined in f's RHS, which makes f look big now.
220 -- So f doesn't get inlined, but it is strict and we have failed to w/w it.
221 = returnUs [ (fn_id, rhs) ]
223 | not (do_strict_ww || do_cpr_ww || do_coerce_ww)
224 = returnUs [ (fn_id, rhs) ]
226 | otherwise -- Do w/w split
227 = mkWwBodies fun_ty arity wrap_dmds result_bot one_shots cpr_info `thenUs` \ (work_demands, wrap_fn, work_fn) ->
228 getUniqueUs `thenUs` \ work_uniq ->
230 work_rhs = work_fn rhs
231 proto_work_id = mkWorkerId work_uniq fn_id (exprType work_rhs)
232 `setInlinePragma` inline_prag
234 work_id | has_strictness = proto_work_id `setIdStrictness` mkStrictnessInfo (work_demands, result_bot)
235 | otherwise = proto_work_id
237 wrap_rhs = wrap_fn work_id
238 wrap_id = fn_id `setIdStrictness` wrapper_strictness
239 `setIdWorkerInfo` HasWorker work_id arity
240 `setInlinePragma` NoInlinePragInfo -- Put it on the worker instead
241 -- Add info to the wrapper:
242 -- (a) we want to set its arity
243 -- (b) we want to pin on its revised strictness info
244 -- (c) we pin on its worker id
246 returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
247 -- Worker first, because wrapper mentions it
248 -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
250 fun_ty = idType fn_id
251 arity = idArity fn_id -- The arity is set by the simplifier using exprEtaExpandArity
252 -- So it may be more than the number of top-level-visible lambdas
254 inline_prag = idInlinePragma fn_id
256 strictness_info = idStrictness fn_id
257 has_strictness = case strictness_info of
258 StrictnessInfo _ _ -> True
259 NoStrictnessInfo -> False
260 (arg_demands, result_bot) = case strictness_info of
261 StrictnessInfo d r -> (d, r)
262 NoStrictnessInfo -> ([], False)
264 wrap_dmds = setUnpackStrategy arg_demands
265 do_strict_ww = WARN( has_strictness && not result_bot && arity < length arg_demands && worthSplitting wrap_dmds result_bot,
266 text "Insufficient arity" <+> ppr fn_id <+> ppr arity <+> ppr arg_demands )
267 (result_bot || arity >= length arg_demands) -- Only if there's enough visible arity
268 && -- (else strictness info isn't valid)
270 worthSplitting wrap_dmds result_bot -- And it's useful
271 -- worthSplitting returns False for an empty list of demands,
272 -- and hence do_strict_ww is False if arity is zero
273 -- Also it's false if there is no strictness (arg_demands is [])
275 wrapper_strictness | has_strictness = mkStrictnessInfo (wrap_dmds, result_bot)
276 | otherwise = noStrictnessInfo
278 -------------------------------------------------------------
279 cpr_info = idCprInfo fn_id
280 do_cpr_ww = arity > 0 &&
285 -------------------------------------------------------------
286 do_coerce_ww = check_for_coerce arity fun_ty
287 -- We are willing to do a w/w even if the arity is zero.
293 -------------------------------------------------------------
294 one_shots = get_one_shots rhs
296 -- See if there's a Coerce before we run out of arity;
297 -- if so, it's worth trying a w/w split. Reason: we find
298 -- functions like f = coerce (\s -> e)
299 -- and g = \x -> coerce (\s -> e)
300 -- and they may have no useful strictness or cpr info, but if we
301 -- do the w/w thing we get rid of the coerces.
303 check_for_coerce arity ty
304 = length arg_tys <= arity && isNewType res_ty
305 -- Don't look further than arity args,
306 -- but if there are arity or fewer, see if there's
307 -- a newtype in the corner
309 (_, tau) = splitForAllTys ty
310 (arg_tys, res_ty) = splitFunTys tau
312 -- If the original function has one-shot arguments, it is important to
313 -- make the wrapper and worker have corresponding one-shot arguments too.
314 -- Otherwise we spuriously float stuff out of case-expression join points,
315 -- which is very annoying.
316 get_one_shots (Lam b e)
317 | isId b = isOneShotLambda b : get_one_shots e
318 | otherwise = get_one_shots e
319 get_one_shots (Note _ e) = get_one_shots e
320 get_one_shots other = noOneShotInfo
325 %************************************************************************
327 \subsection{The worker wrapper core}
329 %************************************************************************
331 @mkWrapper@ is called when importing a function. We have the type of
332 the function and the name of its worker, and we want to make its body (the wrapper).
335 mkWrapper :: Type -- Wrapper type
337 -> [Demand] -- Wrapper strictness info
338 -> Bool -- Function returns bottom
339 -> CprInfo -- Wrapper cpr info
340 -> UniqSM (Id -> CoreExpr) -- Wrapper body, missing worker Id
342 mkWrapper fun_ty arity demands res_bot cpr_info
343 = mkWwBodies fun_ty arity demands res_bot noOneShotInfo cpr_info `thenUs` \ (_, wrap_fn, _) ->
346 noOneShotInfo = repeat False