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}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 module WwLib ( mkWwBodies, mkWWstr, mkWorkerArgs ) where
16 #include "HsVersions.h"
19 import CoreUtils ( exprType )
20 import Id ( Id, idType, mkSysLocal, idNewDemandInfo, setIdNewDemandInfo,
21 isOneShotLambda, setOneShotLambda, setIdUnfolding,
24 import IdInfo ( vanillaIdInfo )
25 import DataCon ( deepSplitProductType_maybe, deepSplitProductType )
26 import NewDemand ( Demand(..), DmdResult(..), Demands(..) )
27 import MkId ( realWorldPrimId, voidArgId, mkRuntimeErrorApp, rUNTIME_ERROR_ID,
28 mkUnpackCase, mkProductBox )
29 import TysWiredIn ( tupleCon )
30 import Type ( Type, isUnLiftedType, mkFunTys,
31 splitForAllTys, splitFunTys, isAlgType
33 import Coercion ( mkSymCoercion, splitNewTypeRepCo_maybe )
34 import BasicTypes ( Boxity(..) )
35 import Var ( Var, isId )
36 import UniqSupply ( returnUs, thenUs, getUniquesUs, UniqSM )
37 import Util ( zipWithEqual, notNull )
39 import List ( zipWith4 )
43 %************************************************************************
45 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
47 %************************************************************************
49 Here's an example. The original function is:
52 g :: forall a . Int -> [a] -> a
60 From this, we want to produce:
62 -- wrapper (an unfolding)
63 g :: forall a . Int -> [a] -> a
68 -- call the worker; don't forget the type args!
71 $wg :: forall a . Int# -> [a] -> a
73 $wg = /\ a -> \ x# ys ->
77 case x of -- note: body of g moved intact
82 Something we have to be careful about: Here's an example:
85 -- "f" strictness: U(P)U(P)
86 f (I# a) (I# b) = a +# b
88 g = f -- "g" strictness same as "f"
91 \tr{f} will get a worker all nice and friendly-like; that's good.
92 {\em But we don't want a worker for \tr{g}}, even though it has the
93 same strictness as \tr{f}. Doing so could break laziness, at best.
95 Consequently, we insist that the number of strictness-info items is
96 exactly the same as the number of lambda-bound arguments. (This is
97 probably slightly paranoid, but OK in practice.) If it isn't the
98 same, we ``revise'' the strictness info, so that we won't propagate
99 the unusable strictness-info into the interfaces.
102 %************************************************************************
104 \subsection{The worker wrapper core}
106 %************************************************************************
108 @mkWwBodies@ is called when doing the worker/wrapper split inside a module.
111 mkWwBodies :: Type -- Type of original function
112 -> [Demand] -- Strictness of original function
113 -> DmdResult -- Info about function result
114 -> [Bool] -- One-shot-ness of the function
115 -> UniqSM ([Demand], -- Demands for worker (value) args
116 Id -> CoreExpr, -- Wrapper body, lacking only the worker Id
117 CoreExpr -> CoreExpr) -- Worker body, lacking the original function rhs
119 -- wrap_fn_args E = \x y -> E
120 -- work_fn_args E = E x y
122 -- wrap_fn_str E = case x of { (a,b) ->
123 -- case a of { (a1,a2) ->
125 -- work_fn_str E = \a2 a2 b y ->
126 -- let a = (a1,a2) in
130 mkWwBodies fun_ty demands res_info one_shots
131 = mkWWargs fun_ty demands one_shots' `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
132 mkWWstr wrap_args `thenUs` \ (work_args, wrap_fn_str, work_fn_str) ->
134 (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
136 -- Don't do CPR if the worker doesn't have any value arguments
137 -- Then the worker is just a constant, so we don't want to unbox it.
138 (if any isId work_args then
139 mkWWcpr res_ty res_info
141 returnUs (id, id, res_ty)
142 ) `thenUs` \ (wrap_fn_cpr, work_fn_cpr, _cpr_res_ty) ->
144 returnUs ([idNewDemandInfo v | v <- work_call_args, isId v],
145 Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
146 mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args)
147 -- We use an INLINE unconditionally, even if the wrapper turns out to be
148 -- something trivial like
150 -- f = __inline__ (coerce T fw)
151 -- The point is to propagate the coerce to f's call sites, so even though
152 -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
153 -- fw from being inlined into f's RHS
155 one_shots' = one_shots ++ repeat False
159 %************************************************************************
161 \subsection{Making wrapper args}
163 %************************************************************************
165 During worker-wrapper stuff we may end up with an unlifted thing
166 which we want to let-bind without losing laziness. So we
167 add a void argument. E.g.
169 f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z
171 fw = /\ a -> \void -> E
172 f = /\ a -> \x y z -> fw realworld
174 We use the state-token type which generates no code.
177 mkWorkerArgs :: [Var]
178 -> Type -- Type of body
179 -> ([Var], -- Lambda bound args
180 [Var]) -- Args at call site
181 mkWorkerArgs args res_ty
182 | any isId args || not (isUnLiftedType res_ty)
185 = (args ++ [voidArgId], args ++ [realWorldPrimId])
189 %************************************************************************
191 \subsection{Coercion stuff}
193 %************************************************************************
196 We really want to "look through" coerces.
197 Reason: I've seen this situation:
199 let f = coerce T (\s -> E)
205 If only we w/w'd f, we'd get
206 let f = coerce T (\s -> fw s)
210 Now we'll inline f to get
218 Now we'll see that fw has arity 1, and will arity expand
219 the \x to get what we want.
222 -- mkWWargs is driven off the function type and arity.
223 -- It chomps bites off foralls, arrows, newtypes
224 -- and keeps repeating that until it's satisfied the supplied arity
228 -> [Bool] -- True for a one-shot arg; ** may be infinite **
229 -> UniqSM ([Var], -- Wrapper args
230 CoreExpr -> CoreExpr, -- Wrapper fn
231 CoreExpr -> CoreExpr, -- Worker fn
232 Type) -- Type of wrapper body
234 mkWWargs fun_ty demands one_shots
235 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe fun_ty
236 -- The newtype case is for when the function has
237 -- a recursive newtype after the arrow (rare)
238 -- We check for arity >= 0 to avoid looping in the case
239 -- of a function whose type is, in effect, infinite
240 -- [Arity is driven by looking at the term, not just the type.]
242 -- It's also important when we have a function returning (say) a pair
243 -- wrapped in a recursive newtype, at least if CPR analysis can look
244 -- through such newtypes, which it probably can since they are
246 = mkWWargs rep_ty demands one_shots `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
248 \ e -> Cast (wrap_fn_args e) (mkSymCoercion co),
249 \ e -> work_fn_args (Cast e co),
252 = getUniquesUs `thenUs` \ wrap_uniqs ->
254 (tyvars, tau) = splitForAllTys fun_ty
255 (arg_tys, body_ty) = splitFunTys tau
257 n_demands = length demands
258 n_arg_tys = length arg_tys
259 n_args = n_demands `min` n_arg_tys
261 new_fun_ty = mkFunTys (drop n_demands arg_tys) body_ty
262 new_demands = drop n_arg_tys demands
263 new_one_shots = drop n_args one_shots
265 val_args = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
266 wrap_args = tyvars ++ val_args
268 {- ASSERT( notNull tyvars || notNull arg_tys ) -}
269 if (null tyvars) && (null arg_tys) then
270 pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands)
271 returnUs ([], id, id, fun_ty)
276 new_one_shots `thenUs` \ (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
278 returnUs (wrap_args ++ more_wrap_args,
279 mkLams wrap_args . wrap_fn_args,
280 work_fn_args . applyToVars wrap_args,
284 = returnUs ([], id, id, fun_ty)
287 applyToVars :: [Var] -> CoreExpr -> CoreExpr
288 applyToVars vars fn = mkVarApps fn vars
290 mk_wrap_arg uniq ty dmd one_shot
291 = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal FSLIT("w") uniq ty) dmd)
293 set_one_shot True id = setOneShotLambda id
294 set_one_shot False id = id
298 %************************************************************************
300 \subsection{Strictness stuff}
302 %************************************************************************
305 mkWWstr :: [Var] -- Wrapper args; have their demand info on them
306 -- *Includes type variables*
307 -> UniqSM ([Var], -- Worker args
308 CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
309 -- and without its lambdas
310 -- This fn adds the unboxing
312 CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
313 -- and lacking its lambdas.
314 -- This fn does the reboxing
316 ----------------------
319 ----------------------
321 = returnUs ([], nop_fn, nop_fn)
324 = mkWWstr_one arg `thenUs` \ (args1, wrap_fn1, work_fn1) ->
325 mkWWstr args `thenUs` \ (args2, wrap_fn2, work_fn2) ->
326 returnUs (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
329 ----------------------
330 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
331 -- * wrap_fn assumes wrap_arg is in scope,
332 -- brings into scope work_args (via cases)
333 -- * work_fn assumes work_args are in scope, a
334 -- brings into scope wrap_arg (via lets)
338 = returnUs ([arg], nop_fn, nop_fn)
341 = case idNewDemandInfo arg of
343 -- Absent case. We don't deal with absence for unlifted types,
344 -- though, because it's not so easy to manufacture a placeholder
345 -- We'll see if this turns out to be a problem
346 Abs | not (isUnLiftedType (idType arg)) ->
347 returnUs ([], nop_fn, mk_absent_let arg)
351 | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys)
352 <- deepSplitProductType_maybe (idType arg)
353 -> getUniquesUs `thenUs` \ uniqs ->
355 unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
356 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
357 unbox_fn = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
358 rebox_fn = Let (NonRec arg con_app)
359 con_app = mkProductBox unpk_args (idType arg)
361 mkWWstr unpk_args_w_ds `thenUs` \ (worker_args, wrap_fn, work_fn) ->
362 returnUs (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
363 -- Don't pass the arg, rebox instead
365 -- `seq` demand; evaluate in wrapper in the hope
366 -- of dropping seqs in the worker
369 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
370 -- Tell the worker arg that it's sure to be evaluated
371 -- so that internal seqs can be dropped
373 returnUs ([arg_w_unf], mk_seq_case arg, nop_fn)
374 -- Pass the arg, anyway, even if it is in theory discarded
377 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
378 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
380 -- f x y = x `seq` fw y
381 -- fw y = let x{Evald} = error "oops" in (x `seq` y)
382 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
383 -- we end up evaluating the absent thunk.
384 -- But the Evald flag is pretty weird, and I worry that it might disappear
385 -- during simplification, so for now I've just nuked this whole case
388 other_demand -> returnUs ([arg], nop_fn, nop_fn)
391 -- If the wrapper argument is a one-shot lambda, then
392 -- so should (all) the corresponding worker arguments be
393 -- This bites when we do w/w on a case join point
394 set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
396 set_one_shot | isOneShotLambda arg = setOneShotLambda
397 | otherwise = \x -> x
401 %************************************************************************
403 \subsection{CPR stuff}
405 %************************************************************************
408 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
409 info and adds in the CPR transformation. The worker returns an
410 unboxed tuple containing non-CPR components. The wrapper takes this
411 tuple and re-produces the correct structured output.
413 The non-CPR results appear ordered in the unboxed tuple as if by a
414 left-to-right traversal of the result structure.
418 mkWWcpr :: Type -- function body type
419 -> DmdResult -- CPR analysis results
420 -> UniqSM (CoreExpr -> CoreExpr, -- New wrapper
421 CoreExpr -> CoreExpr, -- New worker
422 Type) -- Type of worker's body
424 mkWWcpr body_ty RetCPR
425 | not (isAlgType body_ty)
426 = WARN( True, text "mkWWcpr: non-algebraic body type" <+> ppr body_ty )
427 returnUs (id, id, body_ty)
429 | n_con_args == 1 && isUnLiftedType con_arg_ty1
430 -- Special case when there is a single result of unlifted type
432 -- Wrapper: case (..call worker..) of x -> C x
433 -- Worker: case ( ..body.. ) of C x -> x
434 = getUniquesUs `thenUs` \ (work_uniq : arg_uniq : _) ->
436 work_wild = mk_ww_local work_uniq body_ty
437 arg = mk_ww_local arg_uniq con_arg_ty1
438 con_app = mkProductBox [arg] body_ty
440 returnUs (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
441 \ body -> workerCase (work_wild) body [arg] data_con (Var arg),
444 | otherwise -- The general case
445 -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
446 -- Worker: case ( ...body... ) of C a b -> (# a, b #)
447 = getUniquesUs `thenUs` \ uniqs ->
449 (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
450 arg_vars = map Var args
451 ubx_tup_con = tupleCon Unboxed n_con_args
452 ubx_tup_ty = exprType ubx_tup_app
453 ubx_tup_app = mkConApp ubx_tup_con (map Type con_arg_tys ++ arg_vars)
454 con_app = mkProductBox args body_ty
456 returnUs (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app) [(DataAlt ubx_tup_con, args, con_app)],
457 \ body -> workerCase (work_wild) body args data_con ubx_tup_app,
460 (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
461 n_con_args = length con_arg_tys
462 con_arg_ty1 = head con_arg_tys
464 mkWWcpr body_ty other -- No CPR info
465 = returnUs (id, id, body_ty)
467 -- If the original function looked like
468 -- f = \ x -> _scc_ "foo" E
470 -- then we want the CPR'd worker to look like
471 -- \ x -> _scc_ "foo" (case E of I# x -> x)
472 -- and definitely not
473 -- \ x -> case (_scc_ "foo" E) of I# x -> x)
475 -- This transform doesn't move work or allocation
476 -- from one cost centre to another
478 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
479 workerCase bndr e args con body = mkUnpackCase bndr e args con body
483 %************************************************************************
485 \subsection{Utilities}
487 %************************************************************************
491 mk_absent_let arg body
492 | not (isUnLiftedType arg_ty)
493 = Let (NonRec arg abs_rhs) body
495 = panic "WwLib: haven't done mk_absent_let for primitives yet"
498 abs_rhs = mkRuntimeErrorApp rUNTIME_ERROR_ID arg_ty msg
499 msg = "Oops! Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
501 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
503 sanitiseCaseBndr :: Id -> Id
504 -- The argument we are scrutinising has the right type to be
505 -- a case binder, so it's convenient to re-use it for that purpose.
506 -- But we *must* throw away all its IdInfo. In particular, the argument
507 -- will have demand info on it, and that demand info may be incorrect for
508 -- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... }
509 -- Quite likely ww_arg isn't used in '...'. The case may get discarded
510 -- if the case binder says "I'm demanded". This happened in a situation
511 -- like (x+y) `seq` ....
512 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
514 mk_ww_local uniq ty = mkSysLocal FSLIT("ww") uniq ty