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, idDemandInfo, setIdDemandInfo,
14 isOneShotLambda, setOneShotLambda, setIdUnfolding,
17 import IdInfo ( vanillaIdInfo )
19 import Demand ( Demand(..), DmdResult(..), Demands(..) )
20 import MkCore ( mkRuntimeErrorApp, aBSENT_ERROR_ID )
21 import MkId ( realWorldPrimId, voidArgId,
22 mkUnpackCase, mkProductBox )
23 import TysWiredIn ( tupleCon )
25 import Coercion ( mkSymCoercion, splitNewTypeRepCo_maybe )
26 import BasicTypes ( Boxity(..) )
30 import Util ( zipWithEqual )
36 %************************************************************************
38 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
40 %************************************************************************
42 Here's an example. The original function is:
45 g :: forall a . Int -> [a] -> a
47 g = \/\ a -> \ x ys ->
53 From this, we want to produce:
55 -- wrapper (an unfolding)
56 g :: forall a . Int -> [a] -> a
58 g = \/\ a -> \ x ys ->
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 = do { let arg_info = demands `zip` (one_shots ++ repeat False)
125 ; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs emptyTvSubst fun_ty arg_info
126 ; (work_args, wrap_fn_str, work_fn_str) <- mkWWstr wrap_args
128 -- Don't do CPR if the worker doesn't have any value arguments
129 -- Then the worker is just a constant, so we don't want to unbox it.
130 ; (wrap_fn_cpr, work_fn_cpr, _cpr_res_ty)
131 <- if any isId work_args then
132 mkWWcpr res_ty res_info
134 return (id, id, res_ty)
136 ; let (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
137 ; return ([idDemandInfo v | v <- work_call_args, isId v],
138 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
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 %************************************************************************
186 We really want to "look through" coerces.
187 Reason: I've seen this situation:
189 let f = coerce T (\s -> E)
195 If only we w/w'd f, we'd get
196 let f = coerce T (\s -> fw s)
200 Now we'll inline f to get
208 Now we'll see that fw has arity 1, and will arity expand
209 the \x to get what we want.
212 -- mkWWargs just does eta expansion
213 -- 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
217 mkWWargs :: TvSubst -- Freshening substitution to apply to the type
218 -- See Note [Freshen type variables]
219 -> Type -- The type of the function
220 -> [(Demand,Bool)] -- Demands and one-shot info for value arguments
221 -> UniqSM ([Var], -- Wrapper args
222 CoreExpr -> CoreExpr, -- Wrapper fn
223 CoreExpr -> CoreExpr, -- Worker fn
224 Type) -- Type of wrapper body
226 mkWWargs subst fun_ty arg_info
227 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe fun_ty
228 -- The newtype case is for when the function has
229 -- a recursive newtype after the arrow (rare)
230 -- We check for arity >= 0 to avoid looping in the case
231 -- of a function whose type is, in effect, infinite
232 -- [Arity is driven by looking at the term, not just the type.]
234 -- It's also important when we have a function returning (say) a pair
235 -- wrapped in a recursive newtype, at least if CPR analysis can look
236 -- through such newtypes, which it probably can since they are
239 -- Note (Sept 08): This case applies even if demands is empty.
240 -- I'm not quite sure why; perhaps it makes it
242 = do { (wrap_args, wrap_fn_args, work_fn_args, res_ty)
243 <- mkWWargs subst rep_ty arg_info
245 \e -> Cast (wrap_fn_args e) (mkSymCoercion co),
246 \e -> work_fn_args (Cast e co),
250 = return ([], id, id, substTy subst fun_ty)
252 | Just (tv, fun_ty') <- splitForAllTy_maybe fun_ty
253 = do { let (subst', tv') = substTyVarBndr subst tv
254 -- This substTyVarBndr clones the type variable when necy
255 -- See Note [Freshen type variables]
256 ; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
257 <- mkWWargs subst' fun_ty' arg_info
258 ; return (tv' : wrap_args,
259 Lam tv' . wrap_fn_args,
260 work_fn_args . (`App` Type (mkTyVarTy tv')),
263 | ((dmd,one_shot):arg_info') <- arg_info
264 , Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
265 = do { uniq <- getUniqueM
266 ; let arg_ty' = substTy subst arg_ty
267 id = mk_wrap_arg uniq arg_ty' dmd one_shot
268 ; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
269 <- mkWWargs subst fun_ty' arg_info'
270 ; return (id : wrap_args,
271 Lam id . wrap_fn_args,
272 work_fn_args . (`App` Var id),
276 = WARN( True, ppr fun_ty ) -- Should not happen: if there is a demand
277 return ([], id, id, substTy subst fun_ty) -- then there should be a function arrow
279 applyToVars :: [Var] -> CoreExpr -> CoreExpr
280 applyToVars vars fn = mkVarApps fn vars
282 mk_wrap_arg :: Unique -> Type -> Demand -> Bool -> Id
283 mk_wrap_arg uniq ty dmd one_shot
284 = set_one_shot one_shot (setIdDemandInfo (mkSysLocal (fsLit "w") uniq ty) dmd)
286 set_one_shot True id = setOneShotLambda id
287 set_one_shot False id = id
290 Note [Freshen type variables]
291 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
292 mkWWargs may be given a type like (a~b) => <blah>
293 Which really means forall (co:a~b). <blah>
294 Because the name of the coercion variable, 'co', isn't mentioned in <blah>,
295 nested coercion foralls may all use the same variable; and sometimes do
298 However, when we do a worker/wrapper split, we must not use shadowed names,
300 f = /\ co /\co. fw co co
301 which is obviously wrong. Actually, the same is true of type variables, which
302 can in principle shadow, within a type (e.g. forall a. a -> forall a. a->a).
303 But type variables *are* mentioned in <blah>, so we must substitute.
305 That's why we carry the TvSubst through mkWWargs
307 %************************************************************************
309 \subsection{Strictness stuff}
311 %************************************************************************
314 mkWWstr :: [Var] -- Wrapper args; have their demand info on them
315 -- *Includes type variables*
316 -> UniqSM ([Var], -- Worker args
317 CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
318 -- and without its lambdas
319 -- This fn adds the unboxing
321 CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
322 -- and lacking its lambdas.
323 -- This fn does the reboxing
325 = return ([], nop_fn, nop_fn)
327 mkWWstr (arg : args) = do
328 (args1, wrap_fn1, work_fn1) <- mkWWstr_one arg
329 (args2, wrap_fn2, work_fn2) <- mkWWstr args
330 return (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
332 ----------------------
333 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
334 -- * wrap_fn assumes wrap_arg is in scope,
335 -- brings into scope work_args (via cases)
336 -- * work_fn assumes work_args are in scope, a
337 -- brings into scope wrap_arg (via lets)
338 mkWWstr_one :: Var -> UniqSM ([Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)
341 = return ([arg], nop_fn, nop_fn)
344 = case idDemandInfo arg of
346 -- Absent case. We don't deal with absence for unlifted types,
347 -- though, because it's not so easy to manufacture a placeholder
348 -- We'll see if this turns out to be a problem
349 Abs -> return ([], nop_fn, mk_absent_let arg)
353 | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys)
354 <- deepSplitProductType_maybe (idType arg)
355 -> do uniqs <- getUniquesM
357 unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
358 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
359 unbox_fn = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
360 rebox_fn = Let (NonRec arg con_app)
361 con_app = mkProductBox unpk_args (idType arg)
362 (worker_args, wrap_fn, work_fn) <- mkWWstr unpk_args_w_ds
363 return (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
364 -- Don't pass the arg, rebox instead
366 -- `seq` demand; evaluate in wrapper in the hope
367 -- of dropping seqs in the worker
370 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
371 -- Tell the worker arg that it's sure to be evaluated
372 -- so that internal seqs can be dropped
374 return ([arg_w_unf], mk_seq_case arg, nop_fn)
375 -- Pass the arg, anyway, even if it is in theory discarded
378 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
379 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
381 -- f x y = x `seq` fw y
382 -- fw y = let x{Evald} = error "oops" in (x `seq` y)
383 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
384 -- we end up evaluating the absent thunk.
385 -- But the Evald flag is pretty weird, and I worry that it might disappear
386 -- during simplification, so for now I've just nuked this whole case
389 _other_demand -> return ([arg], nop_fn, nop_fn)
392 -- If the wrapper argument is a one-shot lambda, then
393 -- so should (all) the corresponding worker arguments be
394 -- This bites when we do w/w on a case join point
395 set_worker_arg_info worker_arg demand = set_one_shot (setIdDemandInfo worker_arg demand)
397 set_one_shot | isOneShotLambda arg = setOneShotLambda
398 | otherwise = \x -> x
400 ----------------------
401 nop_fn :: CoreExpr -> CoreExpr
406 %************************************************************************
408 \subsection{CPR stuff}
410 %************************************************************************
413 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
414 info and adds in the CPR transformation. The worker returns an
415 unboxed tuple containing non-CPR components. The wrapper takes this
416 tuple and re-produces the correct structured output.
418 The non-CPR results appear ordered in the unboxed tuple as if by a
419 left-to-right traversal of the result structure.
423 mkWWcpr :: Type -- function body type
424 -> DmdResult -- CPR analysis results
425 -> UniqSM (CoreExpr -> CoreExpr, -- New wrapper
426 CoreExpr -> CoreExpr, -- New worker
427 Type) -- Type of worker's body
429 mkWWcpr body_ty RetCPR
430 | not (isClosedAlgType body_ty)
432 text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )
433 return (id, id, body_ty)
435 | n_con_args == 1 && isUnLiftedType con_arg_ty1 = do
436 -- Special case when there is a single result of unlifted type
438 -- Wrapper: case (..call worker..) of x -> C x
439 -- Worker: case ( ..body.. ) of C x -> x
440 (work_uniq : arg_uniq : _) <- getUniquesM
442 work_wild = mk_ww_local work_uniq body_ty
443 arg = mk_ww_local arg_uniq con_arg_ty1
444 con_app = mkProductBox [arg] body_ty
446 return (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
447 \ body -> workerCase (work_wild) body [arg] data_con (Var arg),
450 | otherwise = do -- The general case
451 -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
452 -- Worker: case ( ...body... ) of C a b -> (# a, b #)
455 (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
456 arg_vars = map Var args
457 ubx_tup_con = tupleCon Unboxed n_con_args
458 ubx_tup_ty = exprType ubx_tup_app
459 ubx_tup_app = mkConApp ubx_tup_con (map Type con_arg_tys ++ arg_vars)
460 con_app = mkProductBox args body_ty
462 return (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app) [(DataAlt ubx_tup_con, args, con_app)],
463 \ body -> workerCase (work_wild) body args data_con ubx_tup_app,
466 (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
467 n_con_args = length con_arg_tys
468 con_arg_ty1 = head con_arg_tys
470 mkWWcpr body_ty _other -- No CPR info
471 = return (id, id, body_ty)
473 -- If the original function looked like
474 -- f = \ x -> _scc_ "foo" E
476 -- then we want the CPR'd worker to look like
477 -- \ x -> _scc_ "foo" (case E of I# x -> x)
478 -- and definitely not
479 -- \ x -> case (_scc_ "foo" E) of I# x -> x)
481 -- This transform doesn't move work or allocation
482 -- from one cost centre to another
483 workerCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
484 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
485 workerCase bndr e args con body = mkUnpackCase bndr e args con body
489 %************************************************************************
491 \subsection{Utilities}
493 %************************************************************************
496 Note [Absent error Id]
497 ~~~~~~~~~~~~~~~~~~~~~~
498 We make a new binding for Ids that are marked absent, thus
499 let x = absentError "x :: Int"
500 The idea is that this binding will never be used; but if it
501 buggily is used we'll get a runtime error message.
503 We do this even for *unlifted* types (e.g. Int#). We define
504 absentError to *not* be a bottoming Id, and we treat it as
505 "ok for speculation" (see CoreUtils.okForSpeculation). That
506 means that the let won't get turned into a case, and will
507 be discarded if (as we fully expect) x turns out to be dead.
508 Coping with absence for unlifted types is important; see, for
512 mk_absent_let :: Id -> CoreExpr -> CoreExpr
513 mk_absent_let arg body
514 = Let (NonRec arg abs_rhs) body
517 abs_rhs = mkRuntimeErrorApp aBSENT_ERROR_ID arg_ty msg
518 msg = showSDocDebug (ppr arg <+> ppr (idType arg))
520 mk_seq_case :: Id -> CoreExpr -> CoreExpr
521 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
523 sanitiseCaseBndr :: Id -> Id
524 -- The argument we are scrutinising has the right type to be
525 -- a case binder, so it's convenient to re-use it for that purpose.
526 -- But we *must* throw away all its IdInfo. In particular, the argument
527 -- will have demand info on it, and that demand info may be incorrect for
528 -- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... }
529 -- Quite likely ww_arg isn't used in '...'. The case may get discarded
530 -- if the case binder says "I'm demanded". This happened in a situation
531 -- like (x+y) `seq` ....
532 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
534 mk_ww_local :: Unique -> Type -> Id
535 mk_ww_local uniq ty = mkSysLocal (fsLit "ww") uniq ty