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 )
18 import DataCon ( deepSplitProductType_maybe, deepSplitProductType )
19 import NewDemand ( Demand(..), DmdResult(..), Demands(..) )
20 import MkId ( realWorldPrimId, voidArgId, mkRuntimeErrorApp, rUNTIME_ERROR_ID,
21 mkUnpackCase, mkProductBox )
22 import TysWiredIn ( tupleCon )
23 import Type ( Type, isUnLiftedType, mkFunTys,
24 splitForAllTys, splitFunTys, isAlgType
26 import Coercion ( mkSymCoercion, splitNewTypeRepCo_maybe )
27 import BasicTypes ( Boxity(..) )
28 import Var ( Var, isId )
29 import UniqSupply ( returnUs, thenUs, getUniquesUs, UniqSM )
30 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
124 = mkWWargs fun_ty demands one_shots' `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
125 mkWWstr wrap_args `thenUs` \ (work_args, wrap_fn_str, work_fn_str) ->
127 (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
129 -- Don't do CPR if the worker doesn't have any value arguments
130 -- Then the worker is just a constant, so we don't want to unbox it.
131 (if any isId work_args then
132 mkWWcpr res_ty res_info
134 returnUs (id, id, res_ty)
135 ) `thenUs` \ (wrap_fn_cpr, work_fn_cpr, _cpr_res_ty) ->
137 returnUs ([idNewDemandInfo v | v <- work_args, isId v],
138 Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
139 mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args)
140 -- We use an INLINE unconditionally, even if the wrapper turns out to be
141 -- something trivial like
143 -- f = __inline__ (coerce T fw)
144 -- The point is to propagate the coerce to f's call sites, so even though
145 -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
146 -- fw from being inlined into f's RHS
148 one_shots' = one_shots ++ repeat False
152 %************************************************************************
154 \subsection{Making wrapper args}
156 %************************************************************************
158 During worker-wrapper stuff we may end up with an unlifted thing
159 which we want to let-bind without losing laziness. So we
160 add a void argument. E.g.
162 f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z
164 fw = /\ a -> \void -> E
165 f = /\ a -> \x y z -> fw realworld
167 We use the state-token type which generates no code.
170 mkWorkerArgs :: [Var]
171 -> Type -- Type of body
172 -> ([Var], -- Lambda bound args
173 [Var]) -- Args at call site
174 mkWorkerArgs args res_ty
175 | any isId args || not (isUnLiftedType res_ty)
178 = (args ++ [voidArgId], args ++ [realWorldPrimId])
182 %************************************************************************
184 \subsection{Coercion stuff}
186 %************************************************************************
189 We really want to "look through" coerces.
190 Reason: I've seen this situation:
192 let f = coerce T (\s -> E)
198 If only we w/w'd f, we'd get
199 let f = coerce T (\s -> fw s)
203 Now we'll inline f to get
211 Now we'll see that fw has arity 1, and will arity expand
212 the \x to get what we want.
215 -- mkWWargs is driven off the function type and arity.
216 -- It chomps bites off foralls, arrows, newtypes
217 -- and keeps repeating that until it's satisfied the supplied arity
221 -> [Bool] -- True for a one-shot arg; ** may be infinite **
222 -> UniqSM ([Var], -- Wrapper args
223 CoreExpr -> CoreExpr, -- Wrapper fn
224 CoreExpr -> CoreExpr, -- Worker fn
225 Type) -- Type of wrapper body
227 mkWWargs fun_ty demands one_shots
228 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe fun_ty
229 -- The newtype case is for when the function has
230 -- a recursive newtype after the arrow (rare)
231 -- We check for arity >= 0 to avoid looping in the case
232 -- of a function whose type is, in effect, infinite
233 -- [Arity is driven by looking at the term, not just the type.]
235 -- It's also important when we have a function returning (say) a pair
236 -- wrapped in a recursive newtype, at least if CPR analysis can look
237 -- through such newtypes, which it probably can since they are
239 = mkWWargs rep_ty demands one_shots `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
241 \ e -> Cast (wrap_fn_args e) (mkSymCoercion co),
242 \ e -> work_fn_args (Cast e co),
245 = getUniquesUs `thenUs` \ wrap_uniqs ->
247 (tyvars, tau) = splitForAllTys fun_ty
248 (arg_tys, body_ty) = splitFunTys tau
250 n_demands = length demands
251 n_arg_tys = length arg_tys
252 n_args = n_demands `min` n_arg_tys
254 new_fun_ty = mkFunTys (drop n_demands arg_tys) body_ty
255 new_demands = drop n_arg_tys demands
256 new_one_shots = drop n_args one_shots
258 val_args = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
259 wrap_args = tyvars ++ val_args
261 {- ASSERT( notNull tyvars || notNull arg_tys ) -}
262 if (null tyvars) && (null arg_tys) then
263 pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands)
264 returnUs ([], id, id, fun_ty)
269 new_one_shots `thenUs` \ (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
271 returnUs (wrap_args ++ more_wrap_args,
272 mkLams wrap_args . wrap_fn_args,
273 work_fn_args . applyToVars wrap_args,
277 = returnUs ([], id, id, fun_ty)
280 applyToVars :: [Var] -> CoreExpr -> CoreExpr
281 applyToVars vars fn = mkVarApps fn vars
283 mk_wrap_arg uniq ty dmd one_shot
284 = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal FSLIT("w") uniq ty) dmd)
286 set_one_shot True id = setOneShotLambda id
287 set_one_shot False id = id
291 %************************************************************************
293 \subsection{Strictness stuff}
295 %************************************************************************
298 mkWWstr :: [Var] -- Wrapper args; have their demand info on them
299 -- *Includes type variables*
300 -> UniqSM ([Var], -- Worker args
301 CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
302 -- and without its lambdas
303 -- This fn adds the unboxing
305 CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
306 -- and lacking its lambdas.
307 -- This fn does the reboxing
309 ----------------------
312 ----------------------
314 = returnUs ([], nop_fn, nop_fn)
317 = mkWWstr_one arg `thenUs` \ (args1, wrap_fn1, work_fn1) ->
318 mkWWstr args `thenUs` \ (args2, wrap_fn2, work_fn2) ->
319 returnUs (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
322 ----------------------
323 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
324 -- * wrap_fn assumes wrap_arg is in scope,
325 -- brings into scope work_args (via cases)
326 -- * work_fn assumes work_args are in scope, a
327 -- brings into scope wrap_arg (via lets)
331 = returnUs ([arg], nop_fn, nop_fn)
334 = case idNewDemandInfo arg of
336 -- Absent case. We don't deal with absence for unlifted types,
337 -- though, because it's not so easy to manufacture a placeholder
338 -- We'll see if this turns out to be a problem
339 Abs | not (isUnLiftedType (idType arg)) ->
340 returnUs ([], nop_fn, mk_absent_let arg)
344 | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys)
345 <- deepSplitProductType_maybe (idType arg)
346 -> getUniquesUs `thenUs` \ uniqs ->
348 unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
349 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
350 unbox_fn = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
351 rebox_fn = Let (NonRec arg con_app)
352 con_app = mkProductBox unpk_args (idType arg)
354 mkWWstr unpk_args_w_ds `thenUs` \ (worker_args, wrap_fn, work_fn) ->
355 returnUs (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
356 -- Don't pass the arg, rebox instead
358 -- `seq` demand; evaluate in wrapper in the hope
359 -- of dropping seqs in the worker
362 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
363 -- Tell the worker arg that it's sure to be evaluated
364 -- so that internal seqs can be dropped
366 returnUs ([arg_w_unf], mk_seq_case arg, nop_fn)
367 -- Pass the arg, anyway, even if it is in theory discarded
370 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
371 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
373 -- f x y = x `seq` fw y
374 -- fw y = let x{Evald} = error "oops" in (x `seq` y)
375 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
376 -- we end up evaluating the absent thunk.
377 -- But the Evald flag is pretty weird, and I worry that it might disappear
378 -- during simplification, so for now I've just nuked this whole case
381 other_demand -> returnUs ([arg], nop_fn, nop_fn)
384 -- If the wrapper argument is a one-shot lambda, then
385 -- so should (all) the corresponding worker arguments be
386 -- This bites when we do w/w on a case join point
387 set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
389 set_one_shot | isOneShotLambda arg = setOneShotLambda
390 | otherwise = \x -> x
394 %************************************************************************
396 \subsection{CPR stuff}
398 %************************************************************************
401 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
402 info and adds in the CPR transformation. The worker returns an
403 unboxed tuple containing non-CPR components. The wrapper takes this
404 tuple and re-produces the correct structured output.
406 The non-CPR results appear ordered in the unboxed tuple as if by a
407 left-to-right traversal of the result structure.
411 mkWWcpr :: Type -- function body type
412 -> DmdResult -- CPR analysis results
413 -> UniqSM (CoreExpr -> CoreExpr, -- New wrapper
414 CoreExpr -> CoreExpr, -- New worker
415 Type) -- Type of worker's body
417 mkWWcpr body_ty RetCPR
418 | not (isAlgType body_ty)
419 = WARN( True, text "mkWWcpr: non-algebraic body type" <+> ppr body_ty )
420 returnUs (id, id, body_ty)
422 | n_con_args == 1 && isUnLiftedType con_arg_ty1
423 -- Special case when there is a single result of unlifted type
425 -- Wrapper: case (..call worker..) of x -> C x
426 -- Worker: case ( ..body.. ) of C x -> x
427 = getUniquesUs `thenUs` \ (work_uniq : arg_uniq : _) ->
429 work_wild = mk_ww_local work_uniq body_ty
430 arg = mk_ww_local arg_uniq con_arg_ty1
431 con_app = mkProductBox [arg] body_ty
433 returnUs (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
434 \ body -> workerCase (work_wild) body [arg] data_con (Var arg),
437 | otherwise -- The general case
438 -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
439 -- Worker: case ( ...body... ) of C a b -> (# a, b #)
440 = getUniquesUs `thenUs` \ uniqs ->
442 (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
443 arg_vars = map Var args
444 ubx_tup_con = tupleCon Unboxed n_con_args
445 ubx_tup_ty = exprType ubx_tup_app
446 ubx_tup_app = mkConApp ubx_tup_con (map Type con_arg_tys ++ arg_vars)
447 con_app = mkProductBox args body_ty
449 returnUs (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app) [(DataAlt ubx_tup_con, args, con_app)],
450 \ body -> workerCase (work_wild) body args data_con ubx_tup_app,
453 (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
454 n_con_args = length con_arg_tys
455 con_arg_ty1 = head con_arg_tys
457 mkWWcpr body_ty other -- No CPR info
458 = returnUs (id, id, body_ty)
460 -- If the original function looked like
461 -- f = \ x -> _scc_ "foo" E
463 -- then we want the CPR'd worker to look like
464 -- \ x -> _scc_ "foo" (case E of I# x -> x)
465 -- and definitely not
466 -- \ x -> case (_scc_ "foo" E) of I# x -> x)
468 -- This transform doesn't move work or allocation
469 -- from one cost centre to another
471 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
472 workerCase bndr e args con body = mkUnpackCase bndr e args con body
476 %************************************************************************
478 \subsection{Utilities}
480 %************************************************************************
484 mk_absent_let arg body
485 | not (isUnLiftedType arg_ty)
486 = Let (NonRec arg abs_rhs) body
488 = panic "WwLib: haven't done mk_absent_let for primitives yet"
491 abs_rhs = mkRuntimeErrorApp rUNTIME_ERROR_ID arg_ty msg
492 msg = "Oops! Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
494 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
496 sanitiseCaseBndr :: Id -> Id
497 -- The argument we are scrutinising has the right type to be
498 -- a case binder, so it's convenient to re-use it for that purpose.
499 -- But we *must* throw away all its IdInfo. In particular, the argument
500 -- will have demand info on it, and that demand info may be incorrect for
501 -- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... }
502 -- Quite likely ww_arg isn't used in '...'. The case may get discarded
503 -- if the case binder says "I'm demanded". This happened in a situation
504 -- like (x+y) `seq` ....
505 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
507 mk_ww_local uniq ty = mkSysLocal FSLIT("ww") uniq ty