2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[WwLib]{A library for the ``worker/wrapper'' back-end to the strictness analyser}
7 module WwLib ( mkWwBodies, mkWWstr, mkWorkerArgs ) where
9 #include "HsVersions.h"
12 import CoreUtils ( exprType )
13 import Id ( Id, idType, mkSysLocal, idNewDemandInfo, setIdNewDemandInfo,
14 isOneShotLambda, setOneShotLambda, setIdUnfolding,
17 import IdInfo ( vanillaIdInfo )
19 import NewDemand ( Demand(..), DmdResult(..), Demands(..) )
20 import MkId ( realWorldPrimId, voidArgId, mkRuntimeErrorApp, rUNTIME_ERROR_ID,
21 mkUnpackCase, mkProductBox )
22 import TysWiredIn ( tupleCon )
24 import Coercion ( mkSymCoercion, splitNewTypeRepCo_maybe )
25 import BasicTypes ( Boxity(..) )
26 import Var ( Var, isId )
29 import Util ( zipWithEqual, notNull )
32 import List ( zipWith4 )
36 %************************************************************************
38 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
40 %************************************************************************
42 Here's an example. The original function is:
45 g :: forall a . Int -> [a] -> a
53 From this, we want to produce:
55 -- wrapper (an unfolding)
56 g :: forall a . Int -> [a] -> a
61 -- call the worker; don't forget the type args!
64 $wg :: forall a . Int# -> [a] -> a
66 $wg = /\ a -> \ x# ys ->
70 case x of -- note: body of g moved intact
75 Something we have to be careful about: Here's an example:
78 -- "f" strictness: U(P)U(P)
79 f (I# a) (I# b) = a +# b
81 g = f -- "g" strictness same as "f"
84 \tr{f} will get a worker all nice and friendly-like; that's good.
85 {\em But we don't want a worker for \tr{g}}, even though it has the
86 same strictness as \tr{f}. Doing so could break laziness, at best.
88 Consequently, we insist that the number of strictness-info items is
89 exactly the same as the number of lambda-bound arguments. (This is
90 probably slightly paranoid, but OK in practice.) If it isn't the
91 same, we ``revise'' the strictness info, so that we won't propagate
92 the unusable strictness-info into the interfaces.
95 %************************************************************************
97 \subsection{The worker wrapper core}
99 %************************************************************************
101 @mkWwBodies@ is called when doing the worker/wrapper split inside a module.
104 mkWwBodies :: Type -- Type of original function
105 -> [Demand] -- Strictness of original function
106 -> DmdResult -- Info about function result
107 -> [Bool] -- One-shot-ness of the function
108 -> UniqSM ([Demand], -- Demands for worker (value) args
109 Id -> CoreExpr, -- Wrapper body, lacking only the worker Id
110 CoreExpr -> CoreExpr) -- Worker body, lacking the original function rhs
112 -- wrap_fn_args E = \x y -> E
113 -- work_fn_args E = E x y
115 -- wrap_fn_str E = case x of { (a,b) ->
116 -- case a of { (a1,a2) ->
118 -- work_fn_str E = \a2 a2 b y ->
119 -- let a = (a1,a2) in
123 mkWwBodies fun_ty demands res_info one_shots = do
124 (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs fun_ty demands one_shots'
125 (work_args, wrap_fn_str, work_fn_str) <- mkWWstr wrap_args
126 let (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
127 -- Don't do CPR if the worker doesn't have any value arguments
128 -- Then the worker is just a constant, so we don't want to unbox it.
129 (wrap_fn_cpr, work_fn_cpr, _cpr_res_ty)
130 <- if any isId work_args then
131 mkWWcpr res_ty res_info
133 return (id, id, res_ty)
135 return ([idNewDemandInfo v | v <- work_call_args, isId v],
136 Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
137 mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args)
138 -- We use an INLINE unconditionally, even if the wrapper turns out to be
139 -- something trivial like
141 -- f = __inline__ (coerce T fw)
142 -- The point is to propagate the coerce to f's call sites, so even though
143 -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
144 -- fw from being inlined into f's RHS
146 one_shots' = one_shots ++ repeat False
150 %************************************************************************
152 \subsection{Making wrapper args}
154 %************************************************************************
156 During worker-wrapper stuff we may end up with an unlifted thing
157 which we want to let-bind without losing laziness. So we
158 add a void argument. E.g.
160 f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z
162 fw = /\ a -> \void -> E
163 f = /\ a -> \x y z -> fw realworld
165 We use the state-token type which generates no code.
168 mkWorkerArgs :: [Var]
169 -> Type -- Type of body
170 -> ([Var], -- Lambda bound args
171 [Var]) -- Args at call site
172 mkWorkerArgs args res_ty
173 | any isId args || not (isUnLiftedType res_ty)
176 = (args ++ [voidArgId], args ++ [realWorldPrimId])
180 %************************************************************************
182 \subsection{Coercion stuff}
184 %************************************************************************
187 We really want to "look through" coerces.
188 Reason: I've seen this situation:
190 let f = coerce T (\s -> E)
196 If only we w/w'd f, we'd get
197 let f = coerce T (\s -> fw s)
201 Now we'll inline f to get
209 Now we'll see that fw has arity 1, and will arity expand
210 the \x to get what we want.
213 -- mkWWargs is driven off the function type and arity.
214 -- It chomps bites off foralls, arrows, newtypes
215 -- and keeps repeating that until it's satisfied the supplied arity
219 -> [Bool] -- True for a one-shot arg; ** may be infinite **
220 -> UniqSM ([Var], -- Wrapper args
221 CoreExpr -> CoreExpr, -- Wrapper fn
222 CoreExpr -> CoreExpr, -- Worker fn
223 Type) -- Type of wrapper body
225 mkWWargs fun_ty demands one_shots
226 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe fun_ty = do
227 -- The newtype case is for when the function has
228 -- a recursive newtype after the arrow (rare)
229 -- We check for arity >= 0 to avoid looping in the case
230 -- of a function whose type is, in effect, infinite
231 -- [Arity is driven by looking at the term, not just the type.]
233 -- It's also important when we have a function returning (say) a pair
234 -- wrapped in a recursive newtype, at least if CPR analysis can look
235 -- through such newtypes, which it probably can since they are
237 (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs rep_ty demands one_shots
239 \ e -> Cast (wrap_fn_args e) (mkSymCoercion co),
240 \ e -> work_fn_args (Cast e co),
242 | notNull demands = do
243 wrap_uniqs <- getUniquesM
245 (tyvars, tau) = splitForAllTys fun_ty
246 (arg_tys, body_ty) = splitFunTys tau
248 n_demands = length demands
249 n_arg_tys = length arg_tys
250 n_args = n_demands `min` n_arg_tys
252 new_fun_ty = mkFunTys (drop n_demands arg_tys) body_ty
253 new_demands = drop n_arg_tys demands
254 new_one_shots = drop n_args one_shots
256 val_args = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
257 wrap_args = tyvars ++ val_args
258 {- ASSERT( notNull tyvars || notNull arg_tys ) -}
259 if (null tyvars) && (null arg_tys) then
260 pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands)
261 return ([], id, id, fun_ty)
264 (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) <-
265 mkWWargs new_fun_ty new_demands new_one_shots
267 return (wrap_args ++ more_wrap_args,
268 mkLams wrap_args . wrap_fn_args,
269 work_fn_args . applyToVars wrap_args,
273 = return ([], id, id, fun_ty)
276 applyToVars :: [Var] -> CoreExpr -> CoreExpr
277 applyToVars vars fn = mkVarApps fn vars
279 mk_wrap_arg :: Unique -> Type -> NewDemand.Demand -> Bool -> Id
280 mk_wrap_arg uniq ty dmd one_shot
281 = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal (fsLit "w") uniq ty) dmd)
283 set_one_shot True id = setOneShotLambda id
284 set_one_shot False id = id
288 %************************************************************************
290 \subsection{Strictness stuff}
292 %************************************************************************
295 mkWWstr :: [Var] -- Wrapper args; have their demand info on them
296 -- *Includes type variables*
297 -> UniqSM ([Var], -- Worker args
298 CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
299 -- and without its lambdas
300 -- This fn adds the unboxing
302 CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
303 -- and lacking its lambdas.
304 -- This fn does the reboxing
306 = return ([], nop_fn, nop_fn)
308 mkWWstr (arg : args) = do
309 (args1, wrap_fn1, work_fn1) <- mkWWstr_one arg
310 (args2, wrap_fn2, work_fn2) <- mkWWstr args
311 return (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
313 ----------------------
314 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
315 -- * wrap_fn assumes wrap_arg is in scope,
316 -- brings into scope work_args (via cases)
317 -- * work_fn assumes work_args are in scope, a
318 -- brings into scope wrap_arg (via lets)
319 mkWWstr_one :: Var -> UniqSM ([Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)
322 = return ([arg], nop_fn, nop_fn)
325 = case idNewDemandInfo arg of
327 -- Absent case. We don't deal with absence for unlifted types,
328 -- though, because it's not so easy to manufacture a placeholder
329 -- We'll see if this turns out to be a problem
330 Abs | not (isUnLiftedType (idType arg)) ->
331 return ([], nop_fn, mk_absent_let arg)
335 | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys)
336 <- deepSplitProductType_maybe (idType arg)
337 -> do uniqs <- getUniquesM
339 unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
340 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
341 unbox_fn = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
342 rebox_fn = Let (NonRec arg con_app)
343 con_app = mkProductBox unpk_args (idType arg)
344 (worker_args, wrap_fn, work_fn) <- mkWWstr unpk_args_w_ds
345 return (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
346 -- Don't pass the arg, rebox instead
348 -- `seq` demand; evaluate in wrapper in the hope
349 -- of dropping seqs in the worker
352 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
353 -- Tell the worker arg that it's sure to be evaluated
354 -- so that internal seqs can be dropped
356 return ([arg_w_unf], mk_seq_case arg, nop_fn)
357 -- Pass the arg, anyway, even if it is in theory discarded
360 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
361 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
363 -- f x y = x `seq` fw y
364 -- fw y = let x{Evald} = error "oops" in (x `seq` y)
365 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
366 -- we end up evaluating the absent thunk.
367 -- But the Evald flag is pretty weird, and I worry that it might disappear
368 -- during simplification, so for now I've just nuked this whole case
371 _other_demand -> return ([arg], nop_fn, nop_fn)
374 -- If the wrapper argument is a one-shot lambda, then
375 -- so should (all) the corresponding worker arguments be
376 -- This bites when we do w/w on a case join point
377 set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
379 set_one_shot | isOneShotLambda arg = setOneShotLambda
380 | otherwise = \x -> x
382 ----------------------
383 nop_fn :: CoreExpr -> CoreExpr
388 %************************************************************************
390 \subsection{CPR stuff}
392 %************************************************************************
395 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
396 info and adds in the CPR transformation. The worker returns an
397 unboxed tuple containing non-CPR components. The wrapper takes this
398 tuple and re-produces the correct structured output.
400 The non-CPR results appear ordered in the unboxed tuple as if by a
401 left-to-right traversal of the result structure.
405 mkWWcpr :: Type -- function body type
406 -> DmdResult -- CPR analysis results
407 -> UniqSM (CoreExpr -> CoreExpr, -- New wrapper
408 CoreExpr -> CoreExpr, -- New worker
409 Type) -- Type of worker's body
411 mkWWcpr body_ty RetCPR
412 | not (isClosedAlgType body_ty)
414 text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )
415 return (id, id, body_ty)
417 | n_con_args == 1 && isUnLiftedType con_arg_ty1 = do
418 -- Special case when there is a single result of unlifted type
420 -- Wrapper: case (..call worker..) of x -> C x
421 -- Worker: case ( ..body.. ) of C x -> x
422 (work_uniq : arg_uniq : _) <- getUniquesM
424 work_wild = mk_ww_local work_uniq body_ty
425 arg = mk_ww_local arg_uniq con_arg_ty1
426 con_app = mkProductBox [arg] body_ty
428 return (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
429 \ body -> workerCase (work_wild) body [arg] data_con (Var arg),
432 | otherwise = do -- The general case
433 -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
434 -- Worker: case ( ...body... ) of C a b -> (# a, b #)
437 (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
438 arg_vars = map Var args
439 ubx_tup_con = tupleCon Unboxed n_con_args
440 ubx_tup_ty = exprType ubx_tup_app
441 ubx_tup_app = mkConApp ubx_tup_con (map Type con_arg_tys ++ arg_vars)
442 con_app = mkProductBox args body_ty
444 return (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app) [(DataAlt ubx_tup_con, args, con_app)],
445 \ body -> workerCase (work_wild) body args data_con ubx_tup_app,
448 (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
449 n_con_args = length con_arg_tys
450 con_arg_ty1 = head con_arg_tys
452 mkWWcpr body_ty _other -- No CPR info
453 = return (id, id, body_ty)
455 -- If the original function looked like
456 -- f = \ x -> _scc_ "foo" E
458 -- then we want the CPR'd worker to look like
459 -- \ x -> _scc_ "foo" (case E of I# x -> x)
460 -- and definitely not
461 -- \ x -> case (_scc_ "foo" E) of I# x -> x)
463 -- This transform doesn't move work or allocation
464 -- from one cost centre to another
465 workerCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
466 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
467 workerCase bndr e args con body = mkUnpackCase bndr e args con body
471 %************************************************************************
473 \subsection{Utilities}
475 %************************************************************************
479 mk_absent_let :: Id -> CoreExpr -> CoreExpr
480 mk_absent_let arg body
481 | not (isUnLiftedType arg_ty)
482 = Let (NonRec arg abs_rhs) body
484 = panic "WwLib: haven't done mk_absent_let for primitives yet"
487 abs_rhs = mkRuntimeErrorApp rUNTIME_ERROR_ID arg_ty msg
488 msg = "Oops! Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
490 mk_seq_case :: Id -> CoreExpr -> CoreExpr
491 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
493 sanitiseCaseBndr :: Id -> Id
494 -- The argument we are scrutinising has the right type to be
495 -- a case binder, so it's convenient to re-use it for that purpose.
496 -- But we *must* throw away all its IdInfo. In particular, the argument
497 -- will have demand info on it, and that demand info may be incorrect for
498 -- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... }
499 -- Quite likely ww_arg isn't used in '...'. The case may get discarded
500 -- if the case binder says "I'm demanded". This happened in a situation
501 -- like (x+y) `seq` ....
502 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
504 mk_ww_local :: Unique -> Type -> Id
505 mk_ww_local uniq ty = mkSysLocal (fsLit "ww") uniq ty