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 ( Unfolding, certainlyWillInline )
13 import CmdLineOpts ( opt_UF_CreationThreshold , opt_D_verbose_core2core,
14 opt_D_dump_worker_wrapper
16 import CoreLint ( beginPass, endPass )
17 import CoreUtils ( exprType, exprArity, exprEtaExpandArity )
18 import DataCon ( DataCon )
19 import MkId ( mkWorkerId )
20 import Id ( Id, idType, idStrictness, setIdArityInfo, isOneShotLambda,
21 setIdStrictness, idInlinePragma,
22 setIdWorkerInfo, idCprInfo, setInlinePragma )
24 import Type ( Type, isNewType, splitForAllTys, splitFunTys )
25 import IdInfo ( mkStrictnessInfo, noStrictnessInfo, StrictnessInfo(..),
26 CprInfo(..), exactArity, InlinePragInfo(..), WorkerInfo(..)
28 import Demand ( Demand, wwLazy )
30 import UniqSupply ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
36 We take Core bindings whose binders have:
40 \item Strictness attached (by the front-end of the strictness
43 \item Constructed Product Result information attached by the CPR
48 and we return some ``plain'' bindings which have been
49 worker/wrapper-ified, meaning:
53 \item Functions have been split into workers and wrappers where
54 appropriate. If a function has both strictness and CPR properties
55 then only one worker/wrapper doing both transformations is produced;
57 \item Binders' @IdInfos@ have been updated to reflect the existence of
58 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
59 info for exported values).
64 wwTopBinds :: UniqSupply
70 beginPass "Worker Wrapper binds";
72 -- Create worker/wrappers, and mark binders with their
73 -- "strictness info" [which encodes their worker/wrapper-ness]
74 let { binds' = workersAndWrappers us binds };
76 endPass "Worker Wrapper binds" (opt_D_dump_worker_wrapper ||
77 opt_D_verbose_core2core) binds'
83 workersAndWrappers :: UniqSupply -> [CoreBind] -> [CoreBind]
85 workersAndWrappers us top_binds
87 mapUs wwBind top_binds `thenUs` \ top_binds' ->
88 returnUs (concat top_binds')
91 %************************************************************************
93 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
95 %************************************************************************
97 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
98 turn. Non-recursive case first, then recursive...
102 -> UniqSM [CoreBind] -- returns a WwBinding intermediate form;
103 -- the caller will convert to Expr/Binding,
106 wwBind (NonRec binder rhs)
107 = wwExpr rhs `thenUs` \ new_rhs ->
108 tryWW True {- non-recursive -} binder new_rhs `thenUs` \ new_pairs ->
109 returnUs [NonRec b e | (b,e) <- new_pairs]
110 -- Generated bindings must be non-recursive
111 -- because the original binding was.
113 ------------------------------
116 = mapUs do_one pairs `thenUs` \ new_pairs ->
117 returnUs [Rec (concat new_pairs)]
119 do_one (binder, rhs) = wwExpr rhs `thenUs` \ new_rhs ->
120 tryWW False {- recursive -} binder new_rhs
123 @wwExpr@ basically just walks the tree, looking for appropriate
124 annotations that can be used. Remember it is @wwBind@ that does the
125 matching by looking for strict arguments of the correct type.
126 @wwExpr@ is a version that just returns the ``Plain'' Tree.
129 wwExpr :: CoreExpr -> UniqSM CoreExpr
131 wwExpr e@(Type _) = returnUs e
132 wwExpr e@(Var _) = returnUs e
133 wwExpr e@(Lit _) = returnUs e
135 wwExpr (Lam binder expr)
136 = wwExpr expr `thenUs` \ new_expr ->
137 returnUs (Lam binder new_expr)
140 = wwExpr f `thenUs` \ new_f ->
141 wwExpr a `thenUs` \ new_a ->
142 returnUs (App new_f new_a)
144 wwExpr (Note note expr)
145 = wwExpr expr `thenUs` \ new_expr ->
146 returnUs (Note note new_expr)
148 wwExpr (Let bind expr)
149 = wwBind bind `thenUs` \ intermediate_bind ->
150 wwExpr expr `thenUs` \ new_expr ->
151 returnUs (mkLets intermediate_bind new_expr)
153 wwExpr (Case expr binder alts)
154 = wwExpr expr `thenUs` \ new_expr ->
155 mapUs ww_alt alts `thenUs` \ new_alts ->
156 returnUs (Case new_expr binder new_alts)
158 ww_alt (con, binders, rhs)
159 = wwExpr rhs `thenUs` \ new_rhs ->
160 returnUs (con, binders, new_rhs)
163 %************************************************************************
165 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
167 %************************************************************************
169 @tryWW@ just accumulates arguments, converts strictness info from the
170 front-end into the proper form, then calls @mkWwBodies@ to do
173 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
174 already been w-w'd! (You can end up with several liked-named Ids
175 bouncing around at the same time---absolute mischief.) So the
176 criterion we use is: if an Id already has an unfolding (for whatever
177 reason), then we don't w-w it.
179 The only reason this is monadised is for the unique supply.
182 tryWW :: Bool -- True <=> a non-recursive binding
183 -> Id -- The fn binder
184 -> CoreExpr -- The bound rhs; its innards
186 -> UniqSM [(Id, CoreExpr)] -- either *one* or *two* pairs;
187 -- if one, then no worker (only
188 -- the orig "wrapper" lives on);
189 -- if two, then a worker and a
191 tryWW non_rec fn_id rhs
193 && certainlyWillInline fn_id
194 -- No point in worker/wrappering something that is going to be
195 -- INLINEd wholesale anyway. If the strictness analyser is run
196 -- twice, this test also prevents wrappers (which are INLINEd)
197 -- from being re-done.
199 -- OUT OF DATE NOTE, kept for info:
200 -- In this case we add an INLINE pragma to the RHS. Why?
203 -- g = \yz -> ... -- And g is strict
204 -- Then f is small, so we don't w/w it. But g is big, and we do, so
205 -- g's wrapper will get inlined in f's RHS, which makes f look big now.
206 -- So f doesn't get inlined, but it is strict and we have failed to w/w it.
207 -- It's out of date because now wrappers look very cheap
208 -- even when they are inlined.
209 = returnUs [ (fn_id, rhs) ]
211 | not (do_strict_ww || do_cpr_ww || do_coerce_ww)
212 = returnUs [ (fn_id, rhs) ]
214 | otherwise -- Do w/w split
215 = mkWwBodies fun_ty arity wrap_dmds result_bot one_shots cpr_info `thenUs` \ (work_demands, wrap_fn, work_fn) ->
216 getUniqueUs `thenUs` \ work_uniq ->
218 work_rhs = work_fn rhs
219 proto_work_id = mkWorkerId work_uniq fn_id (exprType work_rhs)
220 `setInlinePragma` inline_prag
222 work_id | has_strictness = proto_work_id `setIdStrictness` mkStrictnessInfo (work_demands, result_bot)
223 | otherwise = proto_work_id
225 wrap_arity = exprArity wrap_rhs -- Might be greater than the current visible arity
226 -- if the function returns bottom
228 wrap_rhs = wrap_fn work_id
229 wrap_id = fn_id `setIdStrictness` wrapper_strictness
230 `setIdWorkerInfo` HasWorker work_id wrap_arity
231 `setIdArityInfo` exactArity wrap_arity
232 `setInlinePragma` NoInlinePragInfo -- Put it on the worker instead
233 -- Add info to the wrapper:
234 -- (a) we want to set its arity
235 -- (b) we want to pin on its revised strictness info
236 -- (c) we pin on its worker id
238 returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
239 -- Worker first, because wrapper mentions it
240 -- Arrange to inline the wrapper unconditionally
242 fun_ty = idType fn_id
243 arity = exprEtaExpandArity rhs
245 -- Don't split something which is marked unconditionally NOINLINE
246 inline_prag = idInlinePragma fn_id
248 strictness_info = idStrictness fn_id
249 has_strictness = case strictness_info of
250 StrictnessInfo _ _ -> True
251 NoStrictnessInfo -> False
252 (arg_demands, result_bot) = case strictness_info of
253 StrictnessInfo d r -> (d, r)
254 NoStrictnessInfo -> ([], False)
256 wrap_dmds = setUnpackStrategy arg_demands
257 do_strict_ww = WARN( has_strictness && not result_bot && arity < length arg_demands && worthSplitting wrap_dmds result_bot,
258 text "Insufficient arity" <+> ppr fn_id <+> ppr arity <+> ppr arg_demands )
259 (result_bot || arity >= length arg_demands) -- Only if there's enough visible arity
260 && -- (else strictness info isn't valid)
262 worthSplitting wrap_dmds result_bot -- And it's useful
263 -- worthSplitting returns False for an empty list of demands,
264 -- and hence do_strict_ww is False if arity is zero
265 -- Also it's false if there is no strictness (arg_demands is [])
267 wrapper_strictness | has_strictness = mkStrictnessInfo (wrap_dmds, result_bot)
268 | otherwise = noStrictnessInfo
270 -------------------------------------------------------------
271 cpr_info = idCprInfo fn_id
272 do_cpr_ww = arity > 0 &&
277 -------------------------------------------------------------
278 do_coerce_ww = check_for_coerce arity fun_ty
279 -- We are willing to do a w/w even if the arity is zero.
285 -------------------------------------------------------------
286 one_shots = get_one_shots rhs
288 -- See if there's a Coerce before we run out of arity;
289 -- if so, it's worth trying a w/w split. Reason: we find
290 -- functions like f = coerce (\s -> e)
291 -- and g = \x -> coerce (\s -> e)
292 -- and they may have no useful strictness or cpr info, but if we
293 -- do the w/w thing we get rid of the coerces.
295 check_for_coerce arity ty
296 = length arg_tys <= arity && isNewType res_ty
297 -- Don't look further than arity args,
298 -- but if there are arity or fewer, see if there's
299 -- a newtype in the corner
301 (_, tau) = splitForAllTys ty
302 (arg_tys, res_ty) = splitFunTys tau
304 -- If the original function has one-shot arguments, it is important to
305 -- make the wrapper and worker have corresponding one-shot arguments too.
306 -- Otherwise we spuriously float stuff out of case-expression join points,
307 -- which is very annoying.
308 get_one_shots (Lam b e)
309 | isId b = isOneShotLambda b : get_one_shots e
310 | otherwise = get_one_shots e
311 get_one_shots (Note _ e) = get_one_shots e
312 get_one_shots other = noOneShotInfo
317 %************************************************************************
319 \subsection{The worker wrapper core}
321 %************************************************************************
323 @mkWrapper@ is called when importing a function. We have the type of
324 the function and the name of its worker, and we want to make its body (the wrapper).
327 mkWrapper :: Type -- Wrapper type
329 -> [Demand] -- Wrapper strictness info
330 -> Bool -- Function returns bottom
331 -> CprInfo -- Wrapper cpr info
332 -> UniqSM (Id -> CoreExpr) -- Wrapper body, missing worker Id
334 mkWrapper fun_ty arity demands res_bot cpr_info
335 = mkWwBodies fun_ty arity demands res_bot noOneShotInfo cpr_info `thenUs` \ (_, wrap_fn, _) ->
338 noOneShotInfo = repeat False